luaaa icon indicating copy to clipboard operation
luaaa copied to clipboard

Passing lua_State* to constructor

Open mck1117 opened this issue 2 years ago • 2 comments

class MyClass {
public:
    MyClass(lua_State* l) {
        luaL_error(l, "first constructor called");
    }

    MyClass(lua_State* l, int x) {
        if (x > 100) {
            luaL_error(l, "oops, X too large!");
        }
    }
}

.......

LuaClass<MyClass> myClass(l, "myClass");

// These both compile
myClass.ctor<lua_State*>();
myClass.ctor<lua_State*, int>();

then you have the lua

local obj1 = myClass.new()        -- works, passes lua state properly
local obj = myClass.new(200)    -- doesn't work, causes runtime error!

The second one causes:

bad argument #2 to 'new' (string expected, got userdata)

The problem is that LuaStack<lua_State*>::get() correctly just returns the lua state, but it causes the indices to be wrong for all following parameters, since it doesn't actually occupy a spot on the stack like all other args do.

See https://github.com/rusefi/rusefi/pull/4391/files# for our solution, adding a specialization to PlacementConstructorCaller when the first parameter is a lua_State*, and passing it directly instead of relying on the LuaStack<lua_State*>::get() function (maybe this one shouldn't even exist, as the ignored idx parameter is in fact the root of this bug?).

mck1117 avatar Jul 27 '22 18:07 mck1117

use myClass:new() instead of myClass.new() here. this is a know issue in current version, will be fixed in next release.

gengyong avatar Jul 27 '22 18:07 gengyong

this is a know issue in current version, will be fixed in next release.

Cool - thanks. Our current workaround works fine, so we're in no rush.

mck1117 avatar Jul 28 '22 05:07 mck1117