int nTop = lua_gettop(L); // 棧內初始數,假設當前爲0 lua_newtable(L); // push table lua_pushstring(L,"Line"); // push key "Line" lua_pushcfunction(L, Line); // push value (function)Line; // int Line(lua_State* pLua) // 當前棧值對應類型: table(-3),string(-2),function(-1) lua_settable(L,-3); // table["Line"] = Line, pop key(-2) & value(-1) // 當前棧值對應類型: table(-1) lua_pushstring(L, "Circle"); // push key "Circle" lua_pushcfunction(L, Circle); // push value (function)Circle; // int Circle(lua_State* pLua) lua_settable(L, -3); // table["Circle"] = Circle, pop key & value, pop key(-2) & value(-1) lua_setglobal(L,"Draw"); // 設置table(stack top)爲全局變量,表名爲Draw, 同時 pop stacktop // 當前棧爲空 lua_settop(L,nTop); // 設置棧頂爲初始數 lua_dostring(L,"Draw.Line(100,50,34,34)"); //lua調用C/C++中的Line函數. 全局變量Draw(table),key("Line")對應的函數(int Line(lua_State* pLua)),100,50,34,34,依次push入棧
// 查看lua棧內容
void stackDump(lua_State* L) {
int top = lua_gettop(L);
for (int i = 1; i <= top; ++i) { int t = lua_type(L, i); switch (t) { case LUA_TSTRING: printf("'%s'", lua_tostring(L, i));break; case LUA_TBOOLEAN: printf(lua_toboolean(L, i) ? "true" : "false");break; case LUA_TNUMBER: printf("'%g'", lua_tonumber(L, i));break; default: printf("'%s'", lua_typename(L, t));break; } printf(" "); } printf("\n"); }