从C中读取Lua表。

我正在尝试将 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;
}

我需要做什么才能遍历所有元素?这段代码会生成如下错误:

糟糕的参数 #-3 给 'buildpollingtable' (lstage-Stage * expected, got table)

有谁能解释一下我哪里做错了吗?

点赞
用户107090
用户107090

你的表格中没有字段名为 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");
2014-10-29 02:16:43