Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
3

Table is printing zero?

Asked by
RoyMer 301 Moderation Voter
6 years ago

Why is #list printing 0? Is there any way to make it print 2 without having to do it manually with a for loop?

local list = {
    ["hi"] = 123,
    ["dog"] = 12345,
}

print(#list)

1 answer

Log in to vote
3
Answered by
Avigant 2374 Moderation Voter Community Moderator
6 years ago

The # operator applied to a table in Lua 5.1 is defined in the manual as:

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).

In practice, for you this means that your string dictionary keys won't be counted for the length of the table.

There is no way to over-ride the behavior of the # operator on tables in Lua 5.1.

1
sorry avingangt but i think ud2v3cf has gotten you beat... i will vote for him in the nexgt election, LegitimatlyMe 519 — 6y
3
One may find an extended discussions of your answer at: https://stackoverflow.com/questions/2705793/how-to-get-number-of-entries-in-a-lua-table. As extension to your answer, yes, the table will have to be counted "manually with a for loop". P.s. one must remember that we are on RBX Lua rather than Lua, so Roblox can eventually (hopefully) implement their solution... Ribasu 127 — 6y
1
avigant is under attack D: LegitimatlyMe 519 — 6y
Ad

Answer this question