c++ - 从 C++ 访问函数环境中的 Lua 变量

标签 c++ lua

这可能是一个简单的问题,但我被难住了。这是针对 Lua 5.1 的。

我有一个在自己的环境中运行的脚本。在那个环境中,我有一个名为“plugin”的变量,我从 C++ 中设置如下:

    lua_getfield(L, LUA_REGISTRYINDEX, getScriptId());  // Put script's env table onto the stack  -- env_table

    lua_pushstring(L, "plugin");  //                           -- env_table, "plugin"
    luaW_push(L, this);       //                               -- env_table, "plugin", *this
    lua_rawset(L, -3);        // env_table["plugin"] = *this   -- env_table

    lua_pop(L, -1);           // Cleanup                       -- <<empty stack>>

在运行我的 Lua 脚本之前,我像这样设置函数环境:

 lua_getfield(L, LUA_REGISTRYINDEX, getScriptId());    // Push REGISTRY[scriptId] onto stack           -- function, table
 lua_setfenv(L, -2);                                   // Set that table to be the env for function    -- function

当我的脚本运行时,它可以像预期的那样看到插件变量并与之交互。到目前为止,一切都很好。

有一次,Lua 脚本调用了一个 C++ 函数,在该函数中,我想查看是否设置了插件变量。

我已经尝试了很多东西,但我似乎看不到插件变量。以下是我尝试过的 4 件事:

lua_getfield(L, LUA_ENVIRONINDEX, "plugin");
bool isPlugin = !lua_isnil(L, -1);
lua_pop(L, 1);    // Remove the value we just added from the stack

lua_getfield(L, LUA_GLOBALSINDEX, "plugin");
bool isPlugin2 = !lua_isnil(L, -1);
lua_pop(L, 1);    // Remove the value we just added from the stack

lua_getglobal(L, "plugin");
bool isPlugin3 = !lua_isnil(L, -1);
lua_pop(L, 1);    // Remove the value we just added from the stack

lua_pushstring(L, "plugin");
bool isPlugin4 = lua_isuserdata(L, -1);
lua_pop(L, 1);

不幸的是,所有 isPlugin 变量都返回 false。就好像从 Lua 调用的 C++ 函数看不到 Lua 环境中的变量集。

知道如何从 C++ 中查看插件变量吗?

谢谢!

最佳答案

Lua 中的每个函数都有它自己的 环境。他们不会继承调用他们的人的环境。因此,如果您的 C++ 函数不使用具有此 plugin 变量的环境,那么它将看不到它。

关于c++ - 从 C++ 访问函数环境中的 Lua 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13280474/

相关文章:

c++ - 声明 C++ 时指针的值

c++ - 如何在Makefile中对两组文件使用不同的规则?

lua - 根据选择插槽在 Lua 表中移动对象的最有效方法是什么?

lua - 使用 NodeMCU 检查电池状态?

c++ - 函数调用缺少参数列表错误

c++ - 如何使用 OpenSSL EVP 例程进行 RSA 公钥加密?

for-loop - lua for 循环使用

linux - 使用 ; 在 Lua 中连接问题

c++ - 如何让 Lua 迭代器返回 C 结构?

C++ 到 C 代码的转换,是否等价?