Lua C API:从Lua函数中检索返回C代码表的值

Scr*_*tch 3 c c++ lua

尽管努力搜索,我找不到一个有效的Lua C API示例来调用返回表的Lua函数.我是Lua和Lua C API的新手,所以不要假设太多.但是,我可以阅读并理解从C加载Lua模块并通过堆栈传递值并从C调用Lua代码的原则.但是我没有找到如何处理表返回值的任何示例.

我想要做的是调用一个Lua函数,在表中设置一些值(字符串,整数,),我想在调用该函数的C代码中获取这些值.

因此Lua函数将类似于:

function f()
  t = {}
  t["foo"] = "hello"
  t["bar"] = 123
  return t
end
Run Code Online (Sandbox Code Playgroud)

(我希望这是有效的Lua代码)

能否请您提供示例C代码,了解如何调用此代码并在C中检索表内容.

Dou*_*rie 10

Lua保留一个与C堆栈分开的堆栈.

当您调用Lua函数时,它会将结果作为值返回到Lua堆栈.

在函数的情况下,它返回一个值,因此调用该函数将返回tLua堆栈顶部的表.

你可以用这个函数调用

lua_getglobal(L, "f");
lua_call(L, 0, 1);     // no arguments, one result
Run Code Online (Sandbox Code Playgroud)

用于lua_gettable从表中读取值.例如

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
Run Code Online (Sandbox Code Playgroud)

此时表t仍在Lua堆栈上,因此您可以继续从表中读取更多值.