5

Despite searching hard, i couldn't find a valid Lua C API example for calling a Lua function returning a table. I'm new to Lua and the Lua C API, so don't assume too much. However i can read and have understood the principle of loading a Lua module from C and passing values via the stack and calling Lua code from C. However i did not find any example of how to handle a table return value.

What i want to do is call a Lua function that sets some values in a table (strings, ints, ) and i want to get these values back in the C code that called the function.

So the Lua function would be something like:

function f()
  t = {}
  t["foo"] = "hello"
  t["bar"] = 123
  return t
end

(I hope this is valid Lua code)

Could you please provide example C code of how to call this and retrieve the table contents in C.

Scrontch
  • 3,275
  • 5
  • 30
  • 45
  • 1
    This is pretty simple to do. Did you take a look at the [Lua reference manual](http://www.lua.org/manual/5.1/index.html#contents)? – Colonel Thirty Two Jun 07 '14 at 15:31
  • 2
    You couldn't retrieve whole Lua table and receive it as struct in C using Lua C API. You have to explicitly retrieve every field of Lua table. – Egor Skriptunoff Jun 07 '14 at 15:31
  • @Colonel Thirty Two: Of course i did this. But the Lua manual crucially lacks examples. As for my problem, the closest i think i got to my problem is in the description of: void lua_gettable (lua_State *L, int index); Pushes onto the stack the value t[k], where t is the value at the given valid index and k is the value at the top of the stack. This function pops the key from the stack (putting the resulting value in its place). I don't understand this sentence. I'm particularly confused about the verbs "push" and "pop" appearing in the same paragraph. What actually *does* this function?? – Scrontch Jun 07 '14 at 17:52

1 Answers1

12

Lua keeps a stack that is separate from the C stack.

When you call your Lua function, it returns its results as value on the Lua stack.

In the case of your function, it returns one value, so calling the function will return the table t on the top of the Lua stack.

You can call the function with

lua_getglobal(L, "f");
lua_call(L, 0, 1);     // no arguments, one result

Use lua_gettable to read values from the table. For example

lua_pushstring(L, "bar");  // now the top of the Lua stack is the string "bar"
                           // one below the top of the stack is the table t
lua_gettable(L, -2);       // the second element from top of stack is the table;
                           // now the top of stack is replaced by t["bar"]
x = lua_tointeger(L,-1);   // convert value on the top of the stack to a C integer
                           // so x should be 123 per your function
lua_pop(L, 1);             // remove the value from the stack

At this point the table t is still on the Lua stack, so you can continue to read more values from the table.

Doug Currie
  • 40,708
  • 1
  • 95
  • 119