Coroutines

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

7 thoughts on “Coroutines

  1. i have not touched lua for a while until now, but i used coroutines at least a few times, so, umm, maybe helpful.

    also still waiting on the linux release, it’s awesomiums problem right now, but might as well clean everything up and shave a few seconds off the release date.
    *twiddle thumbs*

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s