|
|
|
|
|
by john_reel
3495 days ago
|
|
Honestly, it’s a great article. That said, there’s nothing wrong with nils in tables in Lua if you know what you’re doing. Yes, they can introduce weird behaviors, (particularly with the # operator) but if you understand how next, pairs, ipairs, and # work, which are required if you want predictable table iteration behavior in Lua, then this shouldn’t be an issue. I think it’s dangerous to say that nils terminate tables if you’re not going to explain table iteration in Lua. Edit: Here's a picture example showing how easily nils can cause confusion if you're using a #table based loop. https://i.imgur.com/qW0XoSs.png for i,v in pairs(table) will go through an entire table. for i,v in ipairs(table) will stop at a nil. It's meant for consistent behavior in tables with numerical indices. |
|
Also, another thing to remember is that a Lua table can have both a sequence and non-numerical (e.g. string) keys. So
is a valid sequence. Using n to store the length of the "array" part is a common Lua idiom when you want array behavior but cannot guarantee a valid sequence. For example, table.pack creates a table out of a variable argument list; but because any of the arguments might be nil, it sets n as the length of the argument list. Of course, you have to explicitly make use of n in those cases.Lots of people complain about this aspect of Lua. But Lua is very minimalist and there aren't any obvious alternatives. Lua could try to keep track of the maximum numeric index, but that can have poor asymptotic behavior unless Lua used a binary tree for tables instead of arrays and hashes. Lua could implement a type-safe array object, but that violates a core design guideline of Lua, which is that it provides the table as the only primitive for compound data structures. And in any event, it's trivial to implement your own array implementation using metamethods to maintain the invariants of a table while providing transparent support for # and ipairs.