How to read Lua table return value from C++

有些话、适合烂在心里 提交于 2019-12-07 10:34:58

问题


I have a Lua function that returns table (contains set of strings) the function run fine using this code:

lua_pushstring (lua, "funcname");  
lua_gettable   (lua, LUA_GLOBALSINDEX);
lua_pushstring(lua, "someparam");
lua_pcall (lua, 1, 1, 0);

the function returns a table. How do I read it's contents from my C++ code?


回答1:


If you are asking how to traverse the resulting table, you need lua_next (the link also contains an example). As egarcia said, if lua_pcall returns 0, the table the function returned can be found on top of the stack.




回答2:


If the function doesn't throw any errors, then lua_pcall will:

  1. Remove the parameters from the stack
  2. Push the result to the stack

This means that, if your function doesn't throw any errors, you can use lua_setfield right away - lua_pcall will work just like lua_call:

lua_pushstring (lua, "funcname");  
lua_gettable   (lua, LUA_GLOBALSINDEX);
lua_pushstring(lua, "someparam");
lua_pcall (lua, 1, 1, 0);
lua_setfield(L, LUA_GLOBALSINDEX, "a");        /* set global 'a' */

would be the equivalent of:

a = funcname(someparam)


来源:https://stackoverflow.com/questions/3970021/how-to-read-lua-table-return-value-from-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!