4

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
nir
  • 161
  • 2
  • 7

2 Answers2

5

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.

sbk
  • 9,212
  • 4
  • 32
  • 40
  • 1
    `lua_next()` will enumerate all of contents of the table, however, it may be easier to directly access the table if the index is known. `lua_gettable()`, `lua_getfield()`, `lua_rawget()`, or `lua_rawgeti()` can all access the contents of a table if an index is known. – gwell Oct 19 '10 at 19:40
  • @gwell: true, but given that OP used `lua_gettable` in his sample, I assumed he already knows about some of those at least. – sbk Oct 20 '10 at 12:18
1

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)
kikito
  • 51,734
  • 32
  • 149
  • 189