Script structure
Levelgen and Robot scripts share the same general program structure. They generally contain three sections, and are executed during the corresponding phases:
- Global variable declarations (Load Phase)
- Initialization code (Initialization Phase)
- Event handlers (Event Phase)
Note that as of 05a, levelgen scripts do not have an Event Phase, and are terminated after the Initialization Phase. This will change with a future release.
During the "Load Phase" the script is essentially "executed" in order to get all the functions loaded into the global namespace where they can be called by Bitfighter. Any code that is not contained in a function is run, and while you can possibly do some useful things during this phase (especially with a levelgen), it is really best to restrict any "loose code" (i.e. not contained in a function) to defining global variables. Any variables defined in this phase are considered global unless the local keyword is used. Command line args passed to the script are NOT available during this phase.
Immediately following the Load Phase is the Initialization Phase. Initialization essentially consists of running a function called main(). All scripts are required to have a main() function, but it can be empty. This is a good time to set variables and create any structures that might be needed by the script. Any variables created in main() are considered global unless declared with the local keyword, but your scripts will be clearer if they are declared during the Load Phase. Command line args passed to the script are available, and are stored in the arg table (which is the Lua standard).
As the game proceeds, events may occur that trigger calls to the script. Generally, scripts need to register to receive a particular event (see the list of events). When an event occurs in the game, the corresponding function is called in the script, where it can take action accordingly. Each game frame, a Tick event is fired, and if a script has a function called onTick(), it will be executed. Scripts do not need to register to receive Tick events.