首页 > 解决方案 > LUA & C++:如何在 LUA 代码中正确使用 C++ 函数

问题描述

我目前正在学习在 C++ 代码中使用 LUA。我到了无法弄清楚如何在 LUA 代码中使用 C++ 函数的地步。

我想在 C++ 中创建简单的函数,然后在 LUA 中使用它。我的方法如下(取自一些教程):

在 main.cpp 中:

void write(const char* str) {
    std::cout<<str<<std::endl;
}

static int l_write(lua_State* L) {
    const char* str = lua_tostring(L, 1); // get function argument
    write(str); // calling C++ function with this argument...
    return 0; // nothing to return!
}

int main(){
    lua_State* L = luaL_newstate();
    luaL_openlibs(L); // load default Lua libs

        if (luaL_loadfile(L, "test.lua")) {
            std::cout<<"Error loading script"<<std::endl;
        }

    lua_pushcfunction(L, l_write);
    lua_setglobal(L, "write"); // this is how function will be named in Lua
    lua_pcall(L, 0, 0, 0); // run script
}

在 test.lua 我有:

write("Hello, world!")
write("The square root of 2 is "..math.sqrt(2))
x = 42
write("We can use variables too, x = "..x)

问题出现在这段代码的最开始:我什至无法加载脚本luaL_loadfile(L, "test.lua")返回值 7(这是因为我检查了 NIME_AGAIN 7 /* 暂时没有资源 */)。

只要我不使用我的自定义 c++ 函数,其他一切都可以正常工作。我可以正常从 LUA 文件中加载值,可以执行函数等。

我想LUA在读取文件后已经编译它然后找出不存在的函数名称,即“write”并在读取这个文件的情况下返回错误,这可能吗?如果是这样如何解决这个问题,以及如何正确使用这个功能?

标签: c++lua

解决方案


嗯,伙计们。这很奇怪,但我做过lua_pop(L, 1)一次,运行然后删除它,现在它工作得很好哦


推荐阅读