Ok so i have a funny story. Not sure if any of you would care or understand what I’m saying, but it’s very funny so I’ll post it anyway.
So turns out coroutines created in Lua scripts don’t work because of the way I implemented the lua state class. Which is a big problem.
You see, I wanted it so the code would call luaState.pushNumber(3)
with luaState
being a lua state object, instead of having to write luaPushNumber(luaState, 3)
with luaState
being the memory address to the lua state. However to do this I made it keep track of all the Lua states created to map the memory address to the corresponding LuaState class.
Now a problem arises when Lua code calls coroutine.create
, where it creates a new lua state. And the JS code doesn’t know. So when the lua code calls a JavaScript function, it doesn’t recognize the LuaState pointer so it uses undefined
instead of a LuaState instance. Which will obviously cause problems.
So these are some options I thought of:
- Make the C code tell JavaScript that a new thread was created. This would mean modifying the Lua source code to do so, and to make it tell JavaScript the thread was garbage collected as well.
- Make a temporary LuaState when an address that represents a thread is used. This would be a fine solution if I didn’t also keep track of the userdata pointers. However, getting rid of the userdata tracking would mean that the code would have to use peek/poke memory addresses instead of using names.
- Get rid of all this object-oriented crap just use pointers like a Real Programmer™
Ok so I have calmed down at this point and I thought of a pretty solid solution. It’s basically #2 of the list of options I thought of. It makes a new LuaState wrapper everytime a JS function is called. The only thing that differentiates different states is its pointer, so I only need to store that.
For userdatas, I define a userdata type and give it a name. When a userdata is created, I call it with the name of the userdata type. When JS code is called with a userdata as an argument, I cast it into the expeted userdata type. Isn’t it a very innovative and creative solution? (Not like it’s the only way to do if it were in C code)