Lua:从c函数调用中读取表参数

时间:2014-11-02 13:43:14

标签: lua lua-table lua-api

我真的不确定在Lua的C API中处理表。 我正在开发的界面需要我阅读 给我的c函数的表的内容:

example.lua:

myVector2 = {["x"]=20, ["y"]=30}
setSomePosition(myVector2)

C函数我注册为“setSomePosition”:

static int lSetSomePosition(lua_State *L)
{
    //number of arguments
    if(lua_gettop(L) != 1)
    {
        //error handling
        return 0;
    }
    //Need your help with the following:
    //extract tables values of indexes "x" and "y"

    return 0;
}

我知道有几种方法可以处理表格,有时您需要知道我所做的索引。我现在对这个问题感到困惑,研究的越多,我就越困惑。可能是因为我真的不知道如何用正确的术语描述我所追求的东西。

非常感谢一些好的注释示例代码,说明如何填补我的c函数中的空白:)

(如果您有一个易于理解的主题指南,请不要介意评论)

1 个答案:

答案 0 :(得分:2)

lua_getfield(L, 1, "x") //pushes a value of t["x"] onto the stack
lua_tonumber(L, -1) //returns the value at the top of the stack
lua_getfield(L, 1, "y") //pushes a value of t["y"] onto the stack
lua_tonumber(L, -1) //returns the value at the top of the stack