2010-10-21 18 views
5

Stworzyłem tabelę Lua w C, ale nie jestem pewien, jak przesunąć ten stół na stos, aby móc go przekazać do funkcji Lua.Przesuwanie tabeli Lua

Czy ktoś wie, jak to zrobić?

To jest mój bieżący kod:

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 ] 

Odpowiedz

7

Oto funkcja szybkiego pomocnika naciskać struny do stołu

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

Tutaj mogę używać funkcji pomocnika do tworzenia tabeli i przekazać go do funkcji

// 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

Jak przesunąć dwie różne tabele do tej samej funkcji? –

+0

Drugim argumentem w lua_pcall jest liczba argumentów przekazywanych do funkcji, dzięki czemu można byłoby przenieść obie tabele na stos, a następnie zmienić PCall na lua_pcall (L, 2, 0, 0); –

1

Stół jest już w stosie, gdzie lua_newtable opuścił go, prawda?

+0

Jeśli tak, to muszę zrobić niepoprawnie tabelę. Czy możesz mi powiedzieć, jak powinienem stworzyć stół? Wszystko, co musi zawierać, to niektóre ciągi. –

+1

Zobacz na przykład http://www.lua.org/source/5.1/lua.c.html#getargs. Lub pokaż nam swój kod. – lhf

1

zrobiłem mały fragment open source, które rozwiązuje przesuwanie prostych tabel słownika Lua z C na Lua.

Możesz to sprawdzić here, powinien działać dobrze.