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

我正在尝试学习如何使用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 << "错误:脚本未加载(" << filename << ")" << std::endl;
        L = 0;
        return -1;
    }

    return 0;
}

最后,lua脚本:

proxy:doSomething("调用函数!")

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

p.doSomething("调用函数!");

我知道有很多类似的问题,但我找到的没有一个直接回答我的问题。

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

点赞
用户1683902
用户1683902

事实证明, 我必须更改代码:

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 栈不知道 proxy 实例的任何信息,我必须直接调用 lua 函数,然后再调用类成员函数。

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

2018-03-21 21:02:03