2014-10-29 68 views
6

我試圖將一個Lua表傳遞給我的C程序,但我不知道該怎麼做。從C讀取Lua表

我的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; 
} 

什麼我必須做的所有在運行的元素?此代碼會產生如下錯誤:

bad argument #-3 to 'buildpollingtable' (lstage-Stage * expected, got table)

任何人都可以解釋我做錯了什麼?

回答

4

您的表沒有名爲stage1等的字段,只有字段1,2,3。因此,嘗試的

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"); 
+0

但是,錯誤消息應該是'...,得到了nil'。也許使用負數會使'lstage_tostage'混淆。 – lhf 2014-10-29 02:34:08

+0

它返回這個錯誤:「警告:通過'lua_getfield'的參數3使得指針從整數沒有施放[默認情況下啓用]」=/...感謝您的幫助@lhf – Crasher 2014-10-30 00:37:25

+1

@Crasher,你用代碼'lua_rawgeti'? – lhf 2014-10-30 00:38:50