Lua中的堆棧
Lua中的堆棧主要是用來C和Lua進行交互。lua中的堆棧可以通過正數索引和負數索引兩中方式進行索引。正數索引就是棧底爲1,向上依次+1。負數索引就是棧頂爲-1,依次向下-1。
在C中訪問堆棧時,要先用 lua_getglobal(l, 變量名)方法將想要訪問的變量入棧,這時變量是存放在棧頂的,如果變量是一個table的話,還要通過lua_pushstring(l, 變量名)方法將要訪問的變量名入棧,此時通過lua_gettable會從棧頂拿到變量名,在全局表中進行查找變量的值,找到後將值入棧,C就可以在棧頂拿到對應的值了。
luaL_dofile(pL, "helloLua.lua");
lua_getglobal(pL, "helloTable");
lua_pushstring(pL, "name");
lua_gettable(pL, -2);
const char* result = lua_tostring(pL, -1);
lua_pop(pL, -1);
luaL_dofile(pL, "helloLua.lua");
lua_getglobal(pL, “Add);
lua_pushinteger(pL, 1);
lua_pushinteger(pL, 2);
lua_pcall(pL, 2, 1, 0 ) //2,兩個參數;1,1個返回值
const char* result = lua_tointeger (pL, -1);
lua_pop(pL, -1);