2012-11-10 36 views
1

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

{ {x,y}, {x,y}, {x,y}...} 

而且因爲它的所有名單上的表,我需要創建它,而迭代列表..

lua_newtable(L_p); // table at 0 
    int tableIndex = 1; // first entry at 1 

    for( std::list<AmmoDropped*>::iterator it = m_inputAmmosDropped.begin(); 
      it != m_inputAmmosDropped.end(); 
      ++it){ 

     // what do I do here 

     ++tableIndex; 

    } 

    // returns the table 
    return 1; 

的整數鍵索引,並通過「X」和「Y」:

positions[0].x 
positions[0].y 

標識通過試錯嘗試,但因爲我不知道/不具有如何調試它,現在,我真的失去了..

+0

相關http://stackoverflow.com/questions/453769/how-do -i-create-a-lua-table-in-c-and-pass-it-to-a-lua-function –

+0

參見我的圖書館https://github.com/prapin/LuaClassBasedCall – prapin

回答

1

它會是這樣的:

lua_newtable(L); // table at 0 
int tableIndex = 1; // first entry at 1 

for(std::list<AmmoDropped*>::iterator it = m_inputAmmosDropped.begin(); 
     it != m_inputAmmosDropped.end(); 
     ++it){ 
    lua_createtable(L, 2, 0); // a 2 elements subtable 
    lua_pushnumber(L, it->x); 
    lua_rawseti(L, -2, 1);  // x is element 1 of subtable 
    lua_pushnumber(L, it->y); 
    lua_rawseti(L, -2, 2);  // y is element 2 of subtable 
    lua_rawseti(L, -3, tableIndex++) // table {x,y} is element tableIndex 
} 
return 1; 

警告:這是從我的頭頂未經測試的代碼...