在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
C++ 调用Lua 全局变量(表)
lua_getglobal(lua, "ta"); //调用后栈顶放的就是全局变量
lua_getfield(lua, -1, "name");//
printf("lua ta = %s\n", lua_tostring(lua, -1));
lua_pop(lua, 2);
列子:
C++:
//c++调用Lua给Lua传递表和访问Lua的表-----------------------
////第一种
lua_getglobal(L,"conf"); //取表
lua_getfield(L,-1,"height");
printf("height= %d\n",(int)lua_tonumber(L,-1));
lua_getfield(L,-2,"titlename"); //取值
printf("title = %s\n",lua_tostring(L,-1));
lua_pop(L,3);
//第二种,每取一次就把值出栈
lua_getglobal(L,"conf"); //取表
lua_getfield(L,-1,"height");
printf("height= %d\n",(int)lua_tonumber(L,-1));
lua_pop(L,1);
lua_getfield(L,-1,"titlename"); //取值
printf("title = %s\n",lua_tostring(L,-1));
lua_pop(L,1);
lua_pop(L,1); //最后要表出栈
LUA:
------------------c++调用Lua给Lua传递表和访问Lua的表-----------------------
conf = {
titlename="first lua",
height = 1080
}
C++给Lua传递表:
lua_newtable(lua); /* creates a table 创建一个表*/
lua_pushstring(lua, "name"); //压入表
lua_pushstring(lua, "c to lua name");
lua_settable(lua, -3); //弹出key, value, 表在栈顶了
lua_setglobal(lua, "cvar"); //将栈顶位置设置全局变量并出栈
例子:
c++
//c++给Lua传递表
lua_newtable(L);
lua_pushstring(L,"name");
lua_pushstring(L,"xiaoming");
lua_settable(L,-3);
lua_pushstring(L,"age");
lua_pushnumber(L,20);
lua_settable(L,-3);
lua_setglobal(L,"testCToLuaTable"); //设为全局变量
lua:
-------------------c++传递给Lua全局变量表
print("test name c++ -> lua table="..testCToLuaTable["name"]);
print("test age c++ -> lua table="..testCToLuaTable.age);
|
请发表评论