Search code examples
c++bindinglualuabridge

Using LuaBridge with pointers to built-in types


Let's consider the following C function :

void returnMultipleValuesByPointer(int* ret0, int* ret1, int* ret2)
{
    *ret0 = 0;
    *ret1 = 1;
    *ret2 = 2;
}

How to I expose it in Lua using LuaBridge ? All the documentation and examples illustrate complex cases where the pointed objects are classes but I can't find how to deal with such a simple case...

The trivial approach (ie luabridge::getGlobalNamespace(L).addFunction("test", &returnMultipleValuesByPointer)) compiles but does not understand the values are to be passed by address.


Solution

  • You can't do this directly. You have to write a wrapper method that will convert the parameters into return values. This requires writing such a method. For example, if these are pure return values (ie: they don't take parameters):

    int lua_ReturnMultipleValuesByPointer(lua_State *L)
    {
      int ret0;
      int ret1;
      int ret2;
      returnMultipleValuesByPointer(&ret0, &ret1, &ret2);
      lua_pushinteger(L, ret0);
      lua_pushinteger(L, ret1);
      lua_pushinteger(L, ret2);
      return 3;
    }
    

    You will need to register this with "addCFunction", since it's a standard Lua function.