Last night on Twitch I did another tutorial about scenario creation, this time it covered the much more complex topic of using LUA scripting to add a lot of other cool things to your scenarios.
I thought i’d start this blog to allow me to put other commentary on the topic as well as provide access to various script snippets to help you reproduce the techniques in your own work.
I’m not going to go in to great step by step detail, that was covered in the show and available on YouTube.
The video from the show is here: https://www.youtube.com/watch?v=1RcO_og8q7M
Once you’ve got your script created and have a scary blank window in your editor of choice (I use Notepad++), the first thing you’re going to want to do is drop some definitions in to make the code easier to read as we go. Here they are – just copy and pasted to the top of your script file:
-- true/false defn FALSE = 0 TRUE = 1 -- condition return values CONDITION_NOT_YET_MET = 0 CONDITION_SUCCEEDED = 1 CONDITION_FAILED = 2 -- Message types MT_INFO = 0 -- large centre screen pop up MT_ALERT = 1 -- top right alert message MSG_TOP = 1 MSG_VCENTRE = 2 MSG_BOTTOM = 4 MSG_LEFT = 8 MSG_CENTRE = 16 MSG_RIGHT = 32 MSG_SMALL = 0 MSG_REG = 1 MSG_LRG = 2
Next, you’ll want to put in the standard function definitions that the game will call:
function OnEvent(event) end function TestCondition(condition) end
Anyone who codes a lot knows the golden rule about not putting too much code in any one single function. Unfortunately these two functions are going to inherently get very big with lots of “if this then that else if this then the other etc etc”. Fortunately LUA comes to the rescue with a neat capability that I didn’t cover in the show. Modify the above two functions to read as follows:
function OnEvent(event) return _G["OnEvent" .. event](); end function TestCondition(condition) return _G["TestCondition" .. event](); end
What this does is mean that every event or condition can now be placed in to its own function!
So where we might have had this before:
function OnEvent(event) if (event == "IntroText") then -- do some stuff end end
Now we’ve got this:
function OnEventIntroText() -- do some stuff end function OnEvent(event) _G["OnEvent" .. event](); end
Now any time you want to add a new event you just need to add a new function.
The same applies with conditions; using the snippet above for the modified TestCondition, the conditions will now go to their own function such as this:
function TestConditionOverspeed() return CONDITION_NOT_YET_MET; end
That’s the foundations of your script in place, in future articles i’ll start covering specific features.
I’d love to hear your feedback on this article, not just if you like it but if there’s anything you think could be improved!