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

5
尽管我努力搜索,但我无法找到一个有效的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

我希望这段代码是有效的Lua代码。

请提供示例C代码,说明如何在C语言中调用它并获取表格内容。


1
这很简单。你看过Lua参考手册了吗? - Colonel Thirty Two
2
使用Lua C API无法将整个Lua表作为结构体检索并接收。您必须显式地检索Lua表的每个字段。 - Egor Skriptunoff
@Colonel Thirty Two: 当然,我已经这样做了。但是Lua手册关键缺少示例。至于我的问题,我认为最接近我的问题的描述是:void lua_gettable(lua_State *L, int index); 将t[k]的值推入堆栈中,其中t是给定有效索引处的值,k是堆栈顶部的值。此函数从堆栈中弹出键(将结果值放在其位置)。我不理解这个句子。我特别困惑于“push”和“pop”这两个动词出现在同一段落中。这个函数到底是做什么的? - Scrontch
1个回答

12
Lua维护了一个独立于C栈的堆栈。当调用Lua函数时,它将结果作为值存储在Lua栈上。对于该函数,它只返回一个值,因此调用该函数将在Lua堆栈的顶部返回表't'。您可以使用以下方法调用该函数:
lua_getglobal(L, "f");
lua_call(L, 0, 1);     // no arguments, one result

使用 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

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


可以用!非常感谢。这是我一直在寻找的文档齐全的示例。 - Scrontch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接