Script structure

From Bitfighter

Levelgen and Robot scripts share the same general program structure. They generally contain three sections, and are executed during the corresponding phases:

  1. Global variable declarations (Load Phase)
  2. Initialization code (Initialization Phase)
  3. Event handlers (Event Phase)

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. Only 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. Note that to reduce errors, all variables used in the event handling code must be explicitly declared, either during the Load or Initialization phases, or using the local or global keywords.