C++ 和 Lua - 尝试索引 nil 值错误

标签 c++ visual-c++ lua visual-studio-2013

我目前正在学习如何让 Lua 与 C++ 一起工作,我偶然发现了这个问题。 这是我当前正在使用的小应用程序:

#include <lua.5.2.3\src\lua.hpp>
#include <iostream>
#include <string>

int pluacall(lua_State *L){
    std::cout << "Called from inside Lua." << std::endl;
    return 0;
}

int main(){
    std::string x;
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);

    luaL_Reg _funcs[] = { { "CppFunc", pluacall }, {} };

    if (luaL_dofile(L, "test.lua")){
        std::cout << "Error: " << lua_tostring(L, -1) << std::endl;
        lua_pop(L, 1);
    }

    luaL_setfuncs(L, _funcs, 0);

    lua_getglobal(L, "sup");
    if (lua_pcall(L, 0, 0, 0)){
        std::cout << "Error: " << lua_tostring(L, -1) << std::endl;
        lua_pop(L, 1);
    }


    std::cout << "Test";
    std::getline(std::cin, x);

    lua_close(L);
    return 0;
}

一切都完美无缺,直到我添加了luaL_setfuncs(...)

现在应用程序崩溃并出现以下错误:

PANIC:调用 Lua API 时出现不 protected 错误(尝试索引 nil 值)

我要完全诚实,我完全不知道为什么它不起作用或者这个错误意味着什么(谷歌今天不是我的 friend )。有什么想法吗?

可能还值得一提的是,我没有将 Lua 库与我的应用程序链接,而是将它们编译在一起(所有 Lua 源都添加到项目中)

编辑:这是我正在测试的 Lua 脚本

function sup()
    io.write("Hey.\n")
    CppFunc()
    return 1
end

最佳答案

void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup);

将数组 l 中的所有函数(请参阅 luaL_Reg)注册到堆栈顶部的表中(在可选的上值下方,请参阅下一步)。


void luaL_newlib (lua_State *L, const luaL_Reg *l);

创建一个新表并在其中注册列表 l 中的函数。它的实现如下宏:

 (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))

要么在 luaL_setfuncs 之前插入 luaL_newlibtable(L, _funcs),要么使用 luaL_newlib(L, _funcs) 代替。如果您不想将函数注册到单独的表中,而是注册到全局命名空间中,可以使用以下方法:

lua_pushvalue(L, LUA_GLOBALSINDEX); // push _G table
luaL_setfuncs(L, _funcs, 0); // set funcs on _G
lua_pop(L, 1); // pop _G

关于C++ 和 Lua - 尝试索引 nil 值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20962634/

相关文章:

visual-c++ - 获取错误 LNK2019 : unresolved external symbol when compiling SDL2 code in Windows using MSVC

encryption - 无法解密加密数据lua

mysql - 为什么 MySQL 查询在此 Lua 脚本中失败?

class - Lua:需要模块时如何返回模块本身?

c++ - 如何在 C++ 中使用 RegQueryValueEx(..) 从注册表中读取 REG_MULTI_SZ 类型的值

c++ - 启用 arch :SSE2 makes program slower

c++ - C++ 中的 NULL 和 __null 有什么区别?

c++ - 信号处理程序是否意味着无限期运行?

c++ - 在 C++ 中的类声明中初始化 const 成员

c++ - 如何从 C++ 程序中打开 *.mht 文件?