c ++ lua设置全局变量时出错

编程入门 行业动态 更新时间:2024-10-28 04:17:44
本文介绍了c ++ lua设置全局变量时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有下面的代码:

lua_State *lua; lua = lua_open(); luaL_openlibs(lua); std::string code = "print(gvar)\n" "function test()\n" "print(gvar)\n" "end\n"; if(!luaL_loadstring(lua, code.c_str())){ if (lua_pcall(lua, 0, 0, 0)){ const char* error = lua_tostring(lua, -1); lua_pop(lua, 1); } } lua_pushstring(lua, "100"); lua_setglobal(lua, "gvar"); if (lua_pcall(lua, 0, 0, 0)){ const char* error = lua_tostring(lua, -1); // returns "attempt to call a nil value" lua_pop(lua, 1); } lua_close(lua);

调用函数并获取全局变量很好,但是当我尝试设置全局变量时,调用nil值。我不明白为什么是这样?

Calling functions and getting global variables works fine, but when i try to set global variable i get "attempt to call a nil value". And i cant understand why is that?

推荐答案

if(!luaL_loadstring(lua, code.c_str())){ if (lua_pcall(lua, 0, 0, 0)){ const char* error = lua_tostring(lua, -1); lua_pop(lua, 1); } }

此代码将字符串加载到匿名函数中使用 luaL_loadstring(),将它放在堆栈上,然后使用 lua_pcall(lua,0,0,0)执行函数。

This code loads string into a anonymous function using luaL_loadstring(), puts it on the stack and then executes the function using lua_pcall(lua, 0, 0, 0).

lua_pushstring(lua, "100"); lua_setglobal(lua, "gvar"); if (lua_pcall(lua, 0, 0, 0)){ const char* error = lua_tostring(lua, -1); // returns "attempt to call a nil value" lua_pop(lua, 1); }

这段代码将字符串推入堆栈,然后设置全局变量 gvar 。在调用 lua_setglobal()后,堆栈上应该没有任何东西。

This piece of code pushes string onto the stack then sets global variable gvar. There should be nothing on the stack after call to lua_setglobal(). The var is already there.

现在,您尝试使用 lua_pcall 调用位于堆栈顶部的函数$ c>,但是栈是空的 - 这就是为什么你得到尝试调用一个nil值消息。

Now after that you try to call a function which is at the top of the stack with lua_pcall, but the stack is empty - that's why you get attempt to call a nil value message.

更多推荐

c ++ lua设置全局变量时出错

本文发布于:2023-07-20 22:04:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1171494.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:全局变量   lua

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!