Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua C API: Retrieve values from Lua function returning a table in C code

Tags:

c++

c

lua

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.

like image 526
Scrontch Avatar asked Dec 14 '22 22:12

Scrontch


1 Answers

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.

like image 97
Doug Currie Avatar answered Dec 17 '22 11:12

Doug Currie