Write a loop that resets its running total inside the body and Lua will hand back the last value only. The language did exactly what you asked; what you asked was not what you meant. That gap is the shape of nearly every early Lua bug, and these seven account for most of them.
The seven, in the order you will hit them
Treat this as a map of the first month rather than a scolding. Every item below shows up in ordinary code within a week of starting, and each one has a cheap habit that prevents it.
- Forgetting
local. An assignment without it creates a global. In a 30-line script nothing bad happens; in a 300-line file two functions quietly share a variable and the symptom appears three functions away from the cause. - Treating
#tas a reliable count. The length operator is only dependable on a sequence. Delete a middle element by assigningniland the result can be either boundary of the hole. - Assuming zero-based indexing. Tables start at 1, and
for i = 0, n - 1skips the first item and readsnilat the end. - Changing a table while looping over it with
pairs. Behavior becomes unpredictable. Collect the keys you want to remove, then remove them after the loop. - Growing a string with
..in a loop. Each concatenation makes a new string. Push segments into a table and join them once withtable.concat. - Expecting
==or assignment to copy a table. Both work on the reference. A real copy needs a loop or a helper function. - Using
nilas a normal value.nilremoves a key from a table, so it cannot sit in the middle of a list or be stored in a config field you later check.
Two that deserve a closer look
Accidental globals are the expensive one because they fail late. Two helper functions that both use an unqualified result will overwrite each other, and the wrong answer shows up as a wrong number rather than a crash. A linter catches this before you ever run the file, which is why running one is worth the two minutes of setup.
The length operator violates intuition in a different way. #t is defined for sequences, and the moment a table has holes it can return any boundary. If you need a count while removing items, keep your own counter or use table.remove, which shifts the remaining elements down and preserves the sequence property.
Catching them earlier
None of these require deep knowledge to prevent, only a slightly more suspicious workflow:
- Run
luacheckon every file, even tiny ones, and read what it says about globals and unused variables. - Print the type as well as the value when something looks wrong, because a table and a string can both look reasonable in output.
- Reduce a failure to a ten-line file before asking anyone for help; the reduction often answers the question by itself.
A mistake in Lua is rarely exotic. It is usually a local you forgot to declare, a count you trusted, or a reference you thought was a copy. Knowing which three to check first turns a long debugging session into a quick glance.