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

How do I get length of a table/array without using # or table.getn() ?

Asked by
igric 29
6 years ago

I want to get length of an array/table.

local mytable = {one = {value = 1}, two = {value = 2}}

print(#mytable)
print(table.getn(mytable))

Both will return 0. I want to find the way that will print 2 in this situation.

1 answer

Log in to vote
1
Answered by
Azarth 3141 Moderation Voter Community Moderator
6 years ago

You can't use the length operator on dictionaries, you'd have to loop through it.

local mytable = {one = {value = 1}, two = {value = 2}}

local function countNumberOfIndexes(thisTable)
    local count = 0
    for i,v in pairs(thisTable) do
        count = count + 1
    end
    return count
end

print( countNumberOfIndexes(mytable) )
Ad

Answer this question