tags:

views:

1210

answers:

4
myTable = {}
myTable["foo"] = 12
myTable["bar"] = "blah"
print(#myTable) -- this prints 0

Do I actually have to iterate through the items in the table to get the number of keys?

numItems = 0
for k,v in pairs(myTable) do
    numItems = numItems + 1
end
print(numItems) -- this prints 2
+3  A: 

I experimented with both the # operator and table.getn(). I thought table.getn() would do what you wanted but as it turns out it's returning the same value as #, namely 0. It appears that dictionaries insert nil placeholders as necessary.

Looping over the keys and counting them seems like the only way to get the dictionary size.

Aaron Saarela
print(table.getn(myTable))This prints 0.
Jay
# is shorthand for table.getn so you will get same results
serioys sam
+1  A: 

Anything helpful here? http://lua-users.org/wiki/TablesTutorial

Chris
+3  A: 

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). so only way to get length is iterate over it.

serioys sam
A: 

I have the same issue and doing a loop to get the count is not acceptable in my circumstance. This is what I'm currently doing, which I still consider inelegant, but for my situation is better than a loop within a loop:

local t = {}
for i=1,10 do
  t["k"..i] = "v"..i
  t.count = (t.count or 0) + 1
end
print("t.count = " .. t.count)
assertEquals(t.count,10)

I would love if someone could show us a better way

allumbra