2010-10-21 55 views
5

我在C中創建了一個Lua表,但我不確定如何將該表推到堆棧的頂部,因此我可以將它傳遞給一個Lua函數。推一個Lua表

有誰知道如何做到這一點?

這是我當前的代碼:

lua_createtable(state, libraries.size(), 0); 
int table_index = lua_gettop(state); 
for (int i = 0; i < libraries.size(); i++) 
{ 
    lua_pushstring(state, libraries[i].c_str()); 
    lua_rawseti(state, table_index, i + 1); 
} 

lua_settable(state, -3); 

[ Push other things ] 
[ Call function ] 

回答

7

這裏有一個快速的輔助功能,推動字符串表

void l_pushtablestring(lua_State* L , char* key , char* value) { 
    lua_pushstring(L, key); 
    lua_pushstring(L, value); 
    lua_settable(L, -3); 
} 

這裏我使用的輔助函數來創建表,並把它傳遞給函數

// create a lua function 
luaL_loadstring(L, "function fullName(t) print(t.fname,t.lname) end"); 
lua_pcall(L, 0, 0, 0); 

// push the function to the stack 
lua_getglobal(L, "fullName"); 

// create a table in c (it will be at the top of the stack) 
lua_newtable(L); 
l_pushtablestring(L, "fname", "john"); 
l_pushtablestring(L, "lname", "stewart"); 

// call the function with one argument 
lua_pcall(L, 1, 0, 0); 
+0

我會如何將兩個不同的表推送到相同的功能? – 2010-10-21 14:42:49

+0

lua_pcall中的第二個參數是傳遞給函數的參數數量,所以您可以將兩個表都推入堆棧,然後將pcall更改爲lua_pcall(L,2,0,0); – 2010-10-21 16:01:19

1

表已經在堆棧,lua_newtable離開它,不是嗎?

+0

如果是這樣,我必須錯誤地製作表格。你能告訴我應該如何創建桌子嗎?它需要包含的是一些字符串。例如 – 2010-10-21 13:46:14

+1

請參閱http://www.lua.org/source/5.1/lua.c.html#getargs。或向我們展示您的代碼。 – lhf 2010-10-21 13:49:55

1

我做了一個小片段開源解決方案將簡單的Lua字典表從C中推送到Lua。

你可以看看here,應該工作得很好。