Search code examples
c++lualuabridge

Pass C++ object to Lua function using LuaBridge or Lua


I have a big object constructed from C++ (that I have exposed to Lua) and I want to be processed in Lua.

I can pass any simple type to a Lua function (int, string) using lua_pushinteger, lua_pushstring but not a C++ class. I have tried lua_pushlightuserdata by pushing a pointer to my object but no luck.

function process(object) --object is the c++ passed function
--return processed data
end

How can I do that? Is that even possible?

Please note that I want to pass to Lua a specific instance constructed in C++. I can expose the constructor and simply use class but I will need to make the class a singleton. This is not acceptable.


Solution

  • If you've registered your class using LuaBridge, then you have to push the Object pointer into the Lua State machine using the LuaBridge methods. LuaBridge pushes the pointer and then sets meta information on the object using lua_setmetatable. This metatable contains the actual description of the object.

    using namespace luabridge;
    // L = lua_state*
    
    // Register class
    getGlobalNamespace(L)
    .beginClass<MyObjectClass>("MyObjectClass")
        .addData<float>("value", &MyObjectClass::value)
        .addFunction("method", &MyObjectClass::method)
    .endClass();
    
    MyObjectClass myObject; // single instance
    
    // lookup script function in global table
    LuaRef processFunc = getGlobal(L, "process");
    
    if(processFunc.isFunction()){
         processFunc(&myObject);
    }
    

    Lua script

    function process(object) --object is the c++ passed function
       local a = object:method("params")
       return object.value * a;
    end