lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Tue, May 7, 2019 at 6:50 PM Philippe Verdy <verdy_p@wanadoo.fr> wrote:
No, 0 is not a valide sequence number... Sequences in Lua are restricted to ordinals from 1 to N (without holes).

Note that the first comment about length of numbers was still accurate: it said it used a default conversion of numbers to string. But all the problem is the formatting of this number. PHP made a choice for such representation of numbers as strings, Java as well, for their builtin converters. C/C++ did not make any choice, as the result is dependant of the context and there's no default format.

In Lua there's also a default format, the one you see in consoles when printing numbers: this is this format that allows a length to be meaningful.

But string lengths are conceprtually the same as sequence lengths in Lua tables (strings in lua are a compact form to store an indexed table of characters enumerable as a valid sequence).

For Lua numbers however you need a converter to generate a sequence (of digits in some base, or signs, or decimal and grouping separators, or exponent prefix). Without it you cannot enumerate numbers with a well defined positional index for use as if they were table keys.

Note that even if sequence numbers cannot be 0, the sequence length can be 0 of the sequence of empty or is equal to the last key of the enumerated sequence.

As I said, 0 represents the empty set. It IS a sequence, but it's a sequence containing nothing. A loop over the 0 sequence will iterate 0 times. 

The default format doesn't allow the length to be meaningful as you describe, because that format is platform-specific and varies based on the underlying C library implementation. Furthermore, while it can be called "meaningful" in the sense that you can assign a meaning to it, that doesn't mean it's a useful meaning. That meaning would imply that n[i] would return the i'th character of the string representation of the number, which is -- again -- a choice you could make that would be well-defined but why would that ever be something you'd want to do, as opposed to converting the number to a string first?

If Lua offered a range() function like Python's that could be used analogously to ipairs(), then #n would match the length of the sequence returned by range(). You could similarly define a chars() iterator function for strings such that #s would match the length of that sequence. This would make a very clean symmetry: tables with ipairs(), strings with chars(), numbers with range(), and all of them have the same behavior with #.

That said, #n == abs(n) is also a very defensible argument. Instead of trying to generalize numbers as sequences like I did in my previous post, this instead generalizes # as a notion of size. This doesn't have any useful properties with regards to sequences or iteration, but it's robustly non-arbitrary in its meaning.

/s/ Adam