Good Practices
Codes good practices, pitfalls and tips
LUA
Gain performance: Early Return
You're probably used to coding like this:
In LUA, you can skim a few processing cycles by using the early return style:
You can gain a significant amount of performance this way, especially when doing this in a loop.
Fixing/preventing nil access
LUA throws an exception if it encounters nil
in unexpected places. The corresponding error will look like this:
Open the corresponding file, find the correct line, and check what is being accessed there. It will look like variable.property
, or perhaps something will be concatenated to a string ("something something text" .. variable
).
You can assign a default value to the property in question:
While that won't solve any other problems, it will at least make the error go away.
Switch in LUA: Lookup Tables
Who doesn't know the problem? You want to know if your string is A, B, or C, but not D â and LUA doesn't have a switch statement.
Fortunately, there is a built-in and performant way to
Performance killers: strings
String concatenation and comparison can be the difference between a brief stutter and a complete freeze or even crash to desktop. This is not a joke â see here for more detail.
Comparing/Searching
Lua internalizes strings. That means these two strings will share a single representation in memory:
The comparison between those two strings will be almost-instant.
This becomes a problem when comparing strings in a loop (see Scopes):
Every single pass of the loop will create a memory representation of "This is the same object!" and then discard it again.
Takeaway:
If at all possible, define things outside the scope of loops!
Finding in strings
Lua's regex implementation is very limited. There is a limitation for pipes. For example, the following example will actually iterate twice after creating internal string representations:
It is faster to just do this:
On top of that, string.match
will return the entire string if no match is found:
The alternative:
Takeaway:
Avoid regex
prefer
String.find()
overString.match()
Concatenation
For a performance analysis of different kinds of string concatenation, check here.
Scopes
Don't do this (30% less performant):
Do this instead:
Last updated