The wiki says it says the length of the table, but I dont get it. Does it mean that it turns the string into a table like [H, e, l, l, o]? And then lists the length of it? And does it start at the number 0? Like string[0] == 'H'? Thank you
The # is the length operator. To quote the Lua 5.1 manual:
The length of a table t is defined to be any integer index n such that t[n] is not nil and t[n+1] is nil; moreover, if t[1] is nil, n can be zero. For a regular array, with non-nil values from 1 to a given n, its length is exactly that n, the index of its last value. If the array has "holes" (that is, nil values between other non-nil values), then #t can be any of the indices that directly precedes a nil value (that is, it may consider any such nil value as the end of the array).
Arrays in Lua begin at 1.
It is important to note that though you can typically set the behavior of the #
operator on values / data types with __len
, in Lua 5.1 specifically you cannot implement the __len
metatable field for tables.
The #
operator returns the length of a table or string.
Example:
local words = {“Hello”, “Hi”, “Hope the reader”, “of this has a good day”} print(#words)
The code above will print 4. As you can see, there are 4 objects inside the table.
The following example will print how many letters there are in a word, this counts spaces as well. We won’t use them, but it’s a good thing to know.
local word = “Compatible” print(#word)
The above code will print 10. There are 10 letters in the word “Compatible”, so it will print 10.