获取全局变量
lua文件
main.lua
1 2 |
width = 1920 height = 1080 |
C++文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#include <iostream> extern "C" { #include <lua.h> #include <luaxlib.h> #include <lualib.h> } int main() { lua_State * lua = luaL_newstate(); luaL_openlibs(lua); luaopen_base(lua); if(luaL_loadfile(lua,"main.lua")) { const std::string error = lua_tostring(lua,-1); std::cout << "lua file load error:" << error << std::endl; return -1; } if(lua_pcall(lua,0,0,0)) { const std::string error = lua_tostring(lua,-1); std::cout << "lua pcall error:" << error << std::endl; return -1; } //获取全局变量 lua_getgloble(lua,"width"); int width = lua_tonumber(lua,-1); lua_getgloble(lua,"heigth"); int height = lua_tonumber(lua,-1); lua_pop(lua,1); std::cout << "width = " << width << std::endl; std::cout << "height = " << height << std:: endl; lua_close(lua); return 0; } |
设置全局变量
lua文件
main.lua
1 |
print("C++ set gobal:"..ssss) |
C++函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#include <iostream> extern "C" { #include <lua.h> #include <luaxlib.h> #include <lualib.h> } int main() { lua_State * lua = luaL_newstate(); luaL_openlibs(lua); luaopen_base(lua); //在打开文件之前,给lua文件添加全局变量 lua_pushstring(lua,"helllolll"); //将刚压入栈的数据设置为全局变量并命名为ssss lua_setglobal(lua,"ssss"); if(luaL_loadfile(lua,"main.lua")) { const std::string error = lua_tostring(lua,-1); std::cout << "lua file load error:" << error << std::endl; return -1; } if(lua_pcall(lua,0,0,0)) { const std::string error = lua_tostring(lua,-1); std::cout << "lua pcall error:" << error << std::endl; return -1; } lua_close(lua); return 0; } |
声明:本文为原创文章,版权归Aet所有,欢迎分享本文,转载请保留出处!
你可能也喜欢
- ♥ Lua程序设计:三11/13
- ♥ Lua_基础 结构控制09/27
- ♥ Lua_调用 C++函数:传递数组参数10/06
- ♥ Lua_调用 C++函数:传递普通参数10/01
- ♥ Lua_基础 保留值&&变量09/27
- ♥ Lua_调用 C++如何和Lua结合09/27