c++ - 从 LUA 脚本调用 C++ 类函数

标签 c++ lua luabridge

我正在尝试学习如何使用 lua/luabridge 来调用类的成员函数,但我遇到了一些麻烦:

这是简单的测试类:

class proxy
{
public:
    void doSomething(char* str)
    {
        std::cout << "doDomething called!: " << str << std::endl;
    }
};

以及使用它的代码:

int main()
{
    lua_State* L = luaL_newstate();
    luaL_openlibs(L);
    proxy p;
    luabridge::getGlobalNamespace(L)
        .beginClass<proxy>("proxy")
        .addFunction("doSomething", &proxy::doSomething)
        .endClass();

    std::string filename("test.lua");
    if (luaL_dofile(L, filename.c_str()) || lua_pcall(L, 0, 0, 0)) {
        std::cout << "Error: script not loaded (" << filename << ")" << std::endl;
        L = 0;
        return -1;
    }

    return 0;
}

最后,lua 脚本:

proxy:doSomething("calling a function!")

这里可能有几个错误,但我特别想做的是从 lua 脚本中调用 proxy 实例的成员函数,就好像我在调用:

p.doSomething("calling a function!");

我知道有很多类似的问题,但到目前为止我还没有找到直接回答我问题的问题。

目前脚本甚至没有加载/执行,所以我有点困惑。

最佳答案

事实证明,我不得不将代码更改为:

int main()
{
    lua_State* L = luaL_newstate();
    luaL_openlibs(L);
    proxy p;
    luabridge::getGlobalNamespace(L)
        .beginClass<proxy>("proxy")
        .addFunction("doSomething", &proxy::doSomething)
        .endClass();

    std::string filename("test.lua");
    if (luaL_dofile(L, filename.c_str())) {
        std::cout << "Error: script not loaded (" << filename << ")" << std::endl;
        L = 0;
        return -1;
    }
    // new code
    auto doSomething = luabridge::getGlobal(L, "something");
    doSomething(p);
    return 0;
}

并更改脚本:

function something(e)
    e:doSomething("something")
end

这实际上对我来说效果更好。该脚本无法运行,因为 lua 堆栈对代理实例一无所知,我不得不直接调用一个 lua 函数,该函数又调用类成员函数。

我不知道是否有更简单的方法,但这对我来说已经足够了。

关于c++ - 从 LUA 脚本调用 C++ 类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49415317/

相关文章:

c++ - 有条件地从 C++ 调用 Lua 函数

c++ - Luabridge:删除时堆损坏(_CrtIsValidHeapPointer)

c++ - seekp() 以二进制模式替换部分文件时出现问题

c++ - 在 C++ 游戏引擎中使用 Lua 定义 NPC 行为

c++ - 使用字符数组反转字符串

Lua读取只读文件

c++ - 有没有用 Luabridge 向 Lua 公开 sf::Event 的好方法?

c++ - Xerces-C 在根名称中放置冒号时失败

function - 了解 lua 函数如何工作?

从 C 'globally' 更改 Lua 中的全局变量