2010-06-25 54 views
3

我有一個const char **這將是不同的長度,但我想從const char **創建一個Lua數組。從const char創建一個Lua表**

const char **是這樣

arg[0]="Red" 
arg[1]="Purple" 
arg[2]="Yellow" 

我需要這個數組轉換爲在Lua全局表,但我不知道如何去了解這個因爲我不太擅長操縱Lua。

回答

3
int main() 
{ 
    char* arg[3] = { 
     "Red", 
     "Purple", 
     "Yellow" }; 

    //create lua state 
    Lua_state* L = luaL_newstate(); 

    // create the table for arg 
    lua_createtable(L,3,0); 
    int table_index = lua_gettop(L); 

    for(int i =0; i<3; ++i) 
    { 
     // get the string on Lua's stack so it can be used 
     lua_pushstring(L,arg[i]); 

     // this could be done with lua_settable, but that would require pushing the integer as well 
     // the string we just push is removed from the stack 
     // notice the index is i+1 as lua is ones based 
     lua_rawseti(L,table_index,i+1); 
    } 

    //now put that table we've been messing with into the globals 
    //lua will remove the table from the stack leaving it empty once again 
    lua_setglobal(L,"arg"); 
} 
+0

好的,非常感謝你的回答,這很簡單。 我明白這些表現在是如何組織的。 – Nowayz 2010-06-25 01:35:57