【问题标题】:Calling C++ class function from LUA script从 LUA 脚本调用 C++ 类函数
【发布时间】:2018-08-31 02:28:45
【问题描述】:

我正在尝试学习如何使用 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!");

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

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

【问题讨论】:

  • 你需要一个实例。你试过local p = proxy()p:doSomething("calling a function!")吗?
  • 并将void doSomething(char* str) 更改为const char*std::string(vinniefalco.github.io/LuaBridge/Manual.html)
  • 都没有用。不过,我确实取得了一些进展,我会更新问题。

标签: c++ lua luabridge


【解决方案1】:

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

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 函数,而该函数又调用了类成员函数。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-15
    • 2018-04-23
    • 1970-01-01
    • 2017-01-07
    • 2013-08-24
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    相关资源
    最近更新 更多