从C读Lua表

bre*_*iba 6 c lua lua-api lua-table

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

我的Lua代码:

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

lstage.buildpollingtable(stages)
Run Code Online (Sandbox Code Playgroud)

我的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;
}
Run Code Online (Sandbox Code Playgroud)

我需要做什么来运行所有元素?此代码生成如下错误:

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

谁能解释我做错了什么?

lhf*_*lhf 4

您的表没有名为stage1等的字段,只有字段1, 2, 3。所以尝试一下

lua_rawgeti(L,1,1);
lua_rawgeti(L,1,2);
lua_rawgeti(L,1,3);
Run Code Online (Sandbox Code Playgroud)

代替

lua_getfield(L, 1, "stage1");
lua_getfield(L, 1, "stage2");
lua_getfield(L, 1, "stage3");
Run Code Online (Sandbox Code Playgroud)