简体   繁体   English

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

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

Despite searching hard, i couldn't find a valid Lua C API example for calling a Lua function returning a table. 尽管努力搜索,我找不到一个有效的Lua C API示例来调用返回表的Lua函数。 I'm new to Lua and the Lua C API, so don't assume too much. 我是Lua和Lua C API的新手,所以不要假设太多。 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. 但是我可以阅读并理解从C加载Lua模块并通过堆栈传递值并从C调用Lua代码的原则。但是我没有找到如何处理表返回值的任何示例。

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. 我想要做的是调用一个Lua函数,在表中设置一些值(字符串,整数,),我想在调用该函数的C代码中获取这些值。

So the Lua function would be something like: 因此Lua函数将类似于:

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

(I hope this is valid Lua code) (我希望这是有效的Lua代码)

Could you please provide example C code of how to call this and retrieve the table contents in C. 能否请您提供示例C代码,了解如何调用此代码并在C中检索表内容。

Lua keeps a stack that is separate from the C stack. Lua保留一个与C堆栈分开的堆栈。

When you call your Lua function, it returns its results as value on the Lua stack. 当您调用Lua函数时,它会将结果作为值返回到Lua堆栈。

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. 在函数的情况下,它返回一个值,因此调用该函数将返回Lua堆栈顶部的表t

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. 使用lua_gettable从表中读取值。 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. 此时表t仍然在Lua堆栈上,因此您可以继续从表中读取更多值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM