Lua and lua_State - concurrent scripts - How To?

Started by
9 comments, last by Sphet 20 years, 6 months ago
The way I like to handle things is this:

First of all, all of my levels are randomly generated by way of scripts, which can access primitive level construction functions defined in engine code.

I create a class I call Context, which defines the current state going into a script, and provides such members as CurrentObject, which is a reference to the object calling the script. Objects of the same type can share ScriptObjects, which hold the script code, but before they call the script they set the CurrentObject member of Context so that once the script starts executing, it has a reference to the calling object and can use that calling object to keep track of any object-local state that should be remembered between calls.

So, your lamp objects could all have a reference to a single ScriptObject which implements a script turning on or turning off the lamp. If your event loop pumps the event ON_HOUR as Kylotan suggested, then each time an ON_HOUR event is passed to a lamp, the lamp sets Context.CurrentObject to itself then calls it''s OnHour ScriptObject. That script could then obtain the reference to the current object from the context, perform any necessary manipulations, then exit.

Each ScriptObject can be as simple as a std::string holding actual code, or a buffer holding compiled code... whatever you want.

For instance, here is a simple example. In my game, I have a type of object called UseableObject, which has a pointer to an OnUse script that is executed when the right mouse button is clicked on the item in inventory. Each time OnUseEvent() is called, the item does a couple things:

Context.SetCurrentUseableObject(this);
OnUse.ExecuteScript();
Context.ClearCurrentUseableObject();


OnUse is a ScriptObject that contains merely an std::string (for now) which holds a snippet of code. In the example of a simple Potion of Healing, something like this might suffice:

"local Item=Context:GetCurrentUseableItem() Player:HealLife(500) Item:DestroySelf()"

The global Lua state has a global reference to Player (as I got tired of extracting it from context). In this example, the script retrieves the calling object''s reference via GetCurrentUseableItem(), heals the player, then destroys the calling object and exits.


Of course, I am sort of locked into using Lua 4.0, due to an unbelievable amount of work I have no desire to re-write using Lua 5, so this approach may not be what you are looking for.


Josh
vertexnormal AT linuxmail DOT org

Check out Golem: Lands of Shadow, an isometrically rendered hack-and-slash inspired equally by Nethack and Diablo.

This topic is closed to new replies.

Advertisement