Search code examples
c++lualuabridge

Calling C++ class function from LUA script


I'm attempting to learn how to use lua/luabridge to call member function of a class, but I'm having some trouble:

Here is the simple test class:

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

And the code that uses it:

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;
}

And finally, the lua script:

proxy:doSomething("calling a function!")

There is probably several errors here, but specifically what I want to do, is call the the member function for the proxy instance, from the lua script, as if I was calling:

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

I'm aware that there are a lot of similar questions, but none I have found so far directly answers my question.

Currently the script does not even load/execute so I'm a bit puzzled.


Solution

  • As it turned out, I had to change the code to:

    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;
    }
    

    And change the script:

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

    This actually works better for me. The script wouldn't work because the lua stack didn't know anything about the proxy instance, and I had to call a lua function directly, which, in turn, called the class member function.

    I don't know if there is an easier way to do it, but this is good enough for me.