2015-08-15 66 views
3

我有一個std::list對象,我想給Lua一個返回它的多維位置的函數。所以,我需要創建表的表:如何從C函數通過for循環返回一張表格到Lua

{{1,2,3...,512}, {1,2,3...,512},...,512} 

lua_newtable(L); 

    for (int i = 0; i < 512; i++) 
    { 
     lua_newtable(L); 

     lua_pushnumber(L, pos[i]); 
     lua_rawseti(L, -2, i); 
     lua_rawseti(L, -2, i+1); 

     for (int j = 0; j < 512; j++) 
     { 
       //pos[i][j] 
     } 
    } 

我想通過試錯嘗試,但因爲我不知道該如何調試它,現在,我真的失去了。

+2

我認爲你應該嘗試對問題進行重新說明,使其更清楚。什麼是「它的多維立場」。另外,什麼是「對象」。在lua中,您只能推送lua原始類型,函數,用戶數據....其他幾個。你想要推送用戶數據的東西,還是你有一些其他功能在手,知道如何推動它們?是你試圖弄清楚的部分,還是主要是關於「如何使用C api製作表格表」 –

+0

感謝您的關注。我將努力學習英語。 – Candy

回答

2

我想你想創建512x512尺寸的嵌套表(或矩陣)。

static int CreateMatrix(lua_State *L) { 
    lua_newtable(L); 
    for(int i = 0; i < 512; i++) { 
     lua_pushnumber(L, i + 1); // parent table index 
     lua_newtable(L);    // child table 
     for(int j = 0; j < 512; j++) { 
      lua_pushnumber(L, j + 1); // this will be the child's index 
      lua_pushnumber(L, j + 1); // this will be the child's value 
      lua_settable(L, -3); 
     } 
     lua_settable(L, -3); 
    } 
    return 1; 
} 

你當然可以使用你自己的值/索引。

+0

這就是我想要的。謝謝你,再次:) – Candy

0

由於您事先知道表的大小,因此可以避免使用lua_createtable重新分配內存,並使用rawseti來避免重新分配內存。

static int make_matrix(lua_State *L) { 
    lua_createtable(L, 512, 0); 
    for (int i = 0; i < 512; ++i) { 
     lua_createtable(L, 512, 0); 
     for (int j = 0; j < 512; ++j) { 
      lua_pushnumber(L, i + j); // push some value, e.g. "pos[i][j]" 
      lua_rawseti(L, -2, j + 1); 
     } 
     lua_rawseti(L, -2, i + 1); 
    } 
    return 1; 
}