21 ms·
Actually, in Lua, which caused the original discussion, it’s legal to use x[0], since the language doesn’t distinguish between arrays and dictionaries (Lua call
by lrossi 6y ago
Actually, in Lua, which caused the original discussion, it’s legal to use x[0], since the language doesn’t distinguish between arrays and dictionaries (Lua calls them tables). But if you do that, the length calculation will be off by one.
I have seen some difficult to debug issues caused by this when I used to work on game scripts.
- mjevans 6y agoThat sounds like an implementation bug in the name of speed or memory size rather than a programming correctness bug. What's the correct behavior if the 'table' doesn't have any integers as keys, but instead other elements such as strings?
- lrossi 6y agoYou can use strings as keys. In fact, that’s how you can create objects. Also negative integers can be used as keys. But array operations will malfunction if you attempt to apply them to such a table. Here are some examples: http://www.lua.org/pil/2.5.html http://www.lua.org/pil/2.5.html and http://www.lua.org/pil/11.1.html http://www.lua.org/pil/11.1.html
- ufo 6y agoThe tricky thing is that the length operator in Lua (#) actually returns the largest integer index in the table. If you use 1-based arrays, that also happens to be the number of elements in the table. However, if you use 0-based arrays then it won't count the zero-th element. https://www.lua.org/manual/5.4/manual.html#3.4.7 https://www.lua.org/manual/5.4/manual.html#3.4.7