Reputation: 37
Trying to understand exercise 5.1 in Programming in Lua, fourth edition
The code is included, but I don't understand what's going on
sunday = "monday" ; monday = "sunday"
print("After first line ", sunday, monday)
t = {sunday = "monday", [sunday] = monday}
print("Printing #t", #t)
for k = 1 , #t do
print(k, t[k])
end
print("After printing ipairs")
print(t.sunday, t[sunday], t[t.sunday])
The results I'm getting are as follows:-
After first line monday sunday
Printing #t 0
After printing ipairs
monday sunday sunday
It's basically line 3 that is confusing me. Why are the number of elements in t zero ??
Upvotes: 1
Views: 3215
Reputation: 38
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 t1 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).
Taken from the Lua 5.1 Manual
To correctly obtain the length of a table using the # operator, the table must be indexed with integers and be sequential. For example: t = {[1] = "monday", [2] = monday}
In your case, the keys of your table are strings. There are methods to loop through non-sequential tables, one of these methods is with the function pairs
.
t = {sunday = "monday", [sunday] = monday}
for k, v in pairs(t) do
print(k, v)
end
Likewise, to obtain the length of a non-sequential table, you could loop through the table and count the number of elements. How to get number of entries in a Lua table?
Upvotes: 1