lua-intf icon indicating copy to clipboard operation
lua-intf copied to clipboard

strange error in coroutine.

Open yihuang opened this issue 8 years ago • 4 comments

#include "lua.h"
#include "LuaIntf/LuaIntf.h"

using namespace LuaIntf;

class Test
{
public:
    Test (lua_State* L) {
        value = LuaRef::createTable(L);
    }
    virtual ~Test () = default;

    LuaRef value;
};

int main() {
    lua_State* L = luaL_newstate();
    luaL_openlibs(L);
    LuaBinding(L)
        .beginClass<Test>("Test")
        .addConstructor(LUA_ARGS(lua_State*))
            .addVariable("value", &Test::value)
        .endClass();
    if (luaL_dofile(L, "main.lua")) {
        printf("%s\n", lua_tostring(L, -1));
    }
}

main.lua:

t = Test()
print(t.value)
local co = coroutine.create(function()
    print(t.value)
end)
coroutine.resume(co)

Output:

table: 0x7f8a33d12e30
userdata: 0x7f8a33d12ee8

In coroutine, the LuaRef is returned as userdata.

yihuang avatar Aug 19 '16 11:08 yihuang

I get it, LuaRef store the lua_State it created in, but different lua coroutine has different lua_State instance. But LuaRef::pushToStack use the lua_State it stores, not the current coroutine state. Add a lua_State argument to LuaRef::pushToStack can solve this specific problem, but I wonder is there other similar situations.

yihuang avatar Aug 20 '16 00:08 yihuang

There is another problem with coroutine which maybe more annoying, a LuaRef may hold a coroutine's lua_State which could be freed when the coroutine is gc-ed.

yihuang avatar Aug 20 '16 06:08 yihuang

I've changed LuaRef to only store main thread state, the problem should be fixed now.

For 5.2, it just works. For 5.1, your first usage of LuaRef should be in main thread, since LuaBinding use LuaRef inside, call LuaBinding in main thread works too.

yihuang avatar Aug 20 '16 08:08 yihuang