| Message |
Well, this might not be useful for your immediate needs, but I plan on releasing (at some point) a version for SmaugFUSS that has only one Lua state. But here's the general idea...
The thing is that there are some issues involved in this, which is why Nick used just one state in the first place.
1. How do you get character pointers to Lua?
This is relatively easy to solve, just use light userdata. But this creates the much more serious problem #2.
2. How does the Lua state store pointers to characters?
It is not safe to simply store the pointer; for that to work, you would have to clean the Lua state of all references to the character when the character is destroyed. This problem exists in C, of course, but is exacerbated by Lua's dynamic nature. The whole point of using Lua is that you can do things quickly and easily; somebody might store something without even thinking that it is an issue, causing later on a crash. If you have to regiment all of the Lua code extremely closely on a C pointer level, you have lost much of the benefit Lua was supposed to bring you.
My solution is to use a C++ solution that solves the above problem (in C++), but in Lua.
A while ago, Nick wrote an ID system where you store references by a unique reference number and not a memory pointer. When you want to access that reference, you ask the reference manager to give you the corresponding pointer. If that number has no associated pointer -- for instance, because the pointer was destroyed -- the manager returns NULL. You still must (obviously) check for NULL, but at least you have the option to do so, rather than having to simply trust that the pointer you have is still valid.
Shortly after Nick made his code public, I adapted it for use on my own game, managing rooms, objects and characters. It worked very nicely.
When I want to give a character reference to Lua, I pass in a special userdatum that encodes not the pointer but the ID number. When you use that userdatum to talk to the C++ side, you simply go through the pointer manager, and if it yields NULL, you can raise a Lua error to be safely handled.
Well, I described it a fair bit in this thread, if you're curious I would recommend it:
http://www.gammon.com.au/forum/bbshowpost.php?bbsubject_id=8000
You can skip down to "well, your ID system solves this problem" to get to the relevant bit.
The main thing to note is that this requires using C++ instead of C. But for FUSS, this is not really much of a change given that it already uses g++ as a compiler.
I should note that all of this actually works, in that I have Lua embedded on my game using this system; the command interpreter is now Lua-based as are some other things. I just need to clean things up and sort them out before releasing it as a FUSS thing. |
David Haley aka Ksilyan
Head Programmer,
Legends of the Darkstone
http://david.the-haleys.org | top |
|