Tables - Pitfalls and Bad Habits
Manipulating tables in an inefficient way is so common that instead of complaining, I am publishing a guide.
Feel free to share this guide all around the Lua programming community, especially beginners!
The examples below do not necessarily work as they are shown. They are only given for a teaching purpose.
Example 1
Description:
This example restricts the vehicle classes usable by some teams.
This example shows what not to do because using useless loops is inefficient.
Now let's expand every call of table.HasValue as a loop. This basically translates the function to its meaning.
Now you see clearly that you loop over tables by using table.HasValue. In 99% of situations, checking the presence of a value in a table is a waste of CPU time. Using this method is very bad for small tables, and it is insane for large tables.
The next code shows how to make your tables efficient, with no loop and no function calls! It only relies on the presence of a key (never a value): that is what keys are designed for.
We just check the value inside the table directly by using a key! If the value is true then the key is in the table, otherwise it is nil, which is equivalent to false in a condition. This process is very inexpensive and it is worth it.
This example uses tables containing keys that are numbers or strings, but they also can be entities, vectors, angles, etc.
Identical keys
Stay aware from something though: objects can have identical values but still be distinct!
Despite these angles being identical, they are 2 distinct objects in memory as you can see!
For instance, identical numbers, strings and booleans are always considered as the same. But functions, tables, Vectors, Angles and NULL Entitys can seem identical while actually being distinct in memory.