如何从Lua中的C代码访问多维表?

嗨,我对这个看似简单的任务感到非常困惑。我可以访问传递给 C 函数的表的属性,但无法访问其中创建的任何子表的成员。

基本上,我想简单地从属性表中提取字符串,以便根据用户的期望创建一个“轮子”。

以下是我到目前为止的代码(尝试了很多,我的大脑已经炸了)

Lua 侧:

--Function
createSomething( "wheel", { canInflate = true, properties = { "large", "full" } } )

C 侧:

// 我可以轻松地检索表中的任何值,但似乎无法提取表“属性”中的子表。
if( lua_istable(L, 2) ) {
    lua_getfield(L, 2, "canInflate");  // 提取 key 为“canInflate”的值。将该值推到堆栈的顶部
    static int canInflate = lua_toboolean(L, -1); // 获取 bool 类型的值,该值现在位于堆栈的顶部(索引:-1)

    //printf("can inflate is %d\n", canInflate);
    //lua_pop(L, 1); // 弹出该值,因为我们现在已经用完了

}

//尝试获取属性表
if ( lua_istable(L, 2) ) {
    lua_getfield(L, 2, "properties");

    const char *str = lua_tostring(L, -1);

    printf( "properties 1 = %s\n", str); // NULL

    lua_pop(L, 2);
}

非常感谢任何对此有帮助的回复。

点赞
用户513763
用户513763

你遇到的问题与你如何在 Lua 中指定表有关:以下3个语句的结果完全相同:

t = { 'full','large'}
t = { [1] = 'full', [2] = 'large'}
t={};t[1]='full';t[2]='large'

你想要的是使用字符串作为键而不是值(就像你的代码和上面的示例中所做的那样):

t={full=true,large=true}
-- 或者
t={}; t.full=true; t.large=true

如果你使用字符串作为键,你的 C 代码应该能够正常工作。

2012-07-13 14:23:39