lua在C/C++中使用table生成对应键及值
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"); }