Thursday, March 21, 2013
This week I have managed to get coroutines working properly in Garry's Mod. I am almost positive that no-one cares about coroutines but maybe that's because they've never worked properly?
The problem was that coroutines create a new lua_State. But my main Lua class stores the main Lua state and almost all of the bound engine functions use that state. So when you call them from a coroutine it uses the wrong state and the world explodes.
So I made it so that each bound function creates a LuaStateBlock class, which sets the state when its constructed but then sets it back when it's destructed. This worked great except for one huge thing. If you error out in a coroutine the world explodes.
This is because when you error in Lua it jumps to another point in code – and doesn't call the constructors! You can get around this by compiling it as c++ instead of c apparently. But I'm using LuaJIT and I didn't want to fuck shit up that much.
So my solution is to just never set the state back. Then any call to lua_call/lua_pcall I store the state before and restore it afterwards. Job done, coroutines work fine!
tl;dr; fixed something no-one cares about