lua-intf
lua-intf copied to clipboard
strange error in coroutine.
#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.
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.
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.
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.