The dark side of the --include statement

We all know that the only way to include shared files in RW Lua scripts is the --include statement. However, this has the nasty behaviour of not including the quoted file where the --include statement is found, but appending it to the end of the current file. This can be very nasty if you use it like this.

Colors.lua:
WHITE = 1
RED = 2

Main.lua:
--include=Colours.lua
myColour = RED

This is translated to:
--include=Colours.lua
myColour = RED
WHITE = 1
RED = 2

The lovely Lua implementation in RW says nothing about RED being undefined in the second line. It assigns nil to myColour and two lines later, it assigns 2 to RED.

The workaround found by Kuju is this: All signals must define a function Initialise. Now, this function is called after the whole Lua file is read, which means that all the values which you assigned anywhere outside any function are already assigned.

At the same time, you must beware of doing something with the world in Initialise, all you are allowed to do is setting internal values. Sending and receiving messages happens much later. If you want to see how much later, put a Print statement into the Initialise function and the block in Update which is only executed once (after "if gInitialise then").

Back to our problem, the solution now would look like this:
--include=Colours.lua
function Initialise()
myColour = RED
end

Now, this assignment will only be executed when RED has the value 2.


There is another problem with the --include statement: If one of the included files is missing in the first attempt, and you just add them (or rename them to fit, etc.), the blueprint editor adds the "late" files to the end of the resulting script, irrespective of the order of the --include statements.

You can prevent this from happening by deleting the scripts folder under Assets, then all these files are redone in the correct order. Alternatively, you can strictly separate initial definitions on the top-level from using them in Initialise to set further values. It is a bit tiresome, but then you need not worry about the behaviour of the blueprint editor.

No comments:

Post a Comment