c++ - Lua C API: Retrieve values from Lua function returning a table in C code -
despite searching hard, couldn't find valid lua c api example calling lua function returning table. i'm new lua , lua c api, don't assume much. can read , have understood principle of loading lua module c , passing values via stack , calling lua code c. did not find example of how handle table return value.
what want call lua function sets values in table (strings, ints, ) , want these values in c code called function.
so lua function like:
function f() t = {} t["foo"] = "hello" t["bar"] = 123 return t end
(i hope valid lua code)
could please provide example c code of how call , retrieve table contents in c.
lua keeps stack separate c stack.
when call lua function, returns results value on lua stack.
in case of function, returns 1 value, calling function return table t
on top of lua stack.
you can call function with
lua_getglobal(l, "f"); lua_call(l, 0, 1); // no arguments, 1 result
use lua_gettable
read values table. example
lua_pushstring(l, "bar"); // top of lua stack string "bar" // 1 below top of stack table t lua_gettable(l, -2); // second element top of stack table; // top of stack replaced t["bar"] x = lua_tointeger(l,-1); // convert value on top of stack c integer // x should 123 per function lua_pop(l, 1); // remove value stack
at point table t
still on lua stack, can continue read more values table.
Comments
Post a Comment