【问题标题】:Read Lua table from C从 C 中读取 Lua 表
【发布时间】:2014-12-24 14:59:20
【问题描述】:

我正在尝试将 Lua 表传递给我的 C 程序,但我不知道该怎么做。

我的 Lua 代码:

local stages = {}
stages[1] = stage1
stages[2] = stage2
stages[3] = stage3

lstage.buildpollingtable(stages)

我的 C 代码:

static int lstage_build_polling_table (lua_State * L) {    
    luaL_checktype(L, 1, LUA_TTABLE);

    lua_getfield(L, 1, "stage1");
    lua_getfield(L, 1, "stage2");
    lua_getfield(L, 1, "stage3");

    stage_t s1 = lstage_tostage(L, -3);
    stage_t s2 = lstage_tostage(L, -2);
    stage_t s3 = lstage_tostage(L, -1);

    printf("%d\n",s1->priority);
    printf("%d\n",s2->priority);
    printf("%d\n",s3->priority);

    return 1;
}

我必须做什么才能在所有元素上运行?此代码生成如下错误:

'buildpollingtable' 的错误参数 #-3(lstage-Stage * 预期,得到表)

谁能解释我做错了什么?

【问题讨论】:

    标签: c lua lua-table lua-api


    【解决方案1】:

    您的表没有名为stage1 等的字段,只有字段123。所以试试

    lua_rawgeti(L,1,1);
    lua_rawgeti(L,1,2);
    lua_rawgeti(L,1,3);
    

    而不是

    lua_getfield(L, 1, "stage1");
    lua_getfield(L, 1, "stage2");
    lua_getfield(L, 1, "stage3");
    

    【讨论】:

    • 但是,错误信息应该是..., got nil。也许使用负数会让人困惑lstage_tostage
    • 它返回此错误:“警告:传递 'lua_getfield' 的参数 3 使指针从整数不进行强制转换 [默认启用]”=/ ...感谢您的帮助 @lhf
    • 耶!它的工作!有没有办法知道该表拥有多少个元素?因为在这种情况下我有 3 个元素,但我可以有 4,5,6...
    • 你知道我在哪里可以找到这种方法@lhf 的样本吗?
    • @Crasher,我建议你问一个单独的问题。
    猜你喜欢
    • 2015-09-02
    • 1970-01-01
    • 2015-01-18
    • 2013-06-03
    • 2016-01-08
    • 2011-04-27
    • 2015-05-21
    • 1970-01-01
    • 2021-03-11
    相关资源
    最近更新 更多