Quantcast WoWInterface - View Single Post - Tables - count items in them
View Single Post
08-01-16, 09:23 AM   #1
Hiketeia
An Aku'mai Servant
 
Hiketeia's Avatar
AddOn Author - Click to view addons
Join Date: Apr 2016
Posts: 33
Tables - count items in them

I'm missing something here... transitioning from other languages to lua and I've got a gap somewhere I was hoping you could point it out to me and give me some reference material to fill in the gap...

I don't seem to be understanding tables correctly -- mostly the '#' meta and iterating over them. Here is some code:

Lua Code:
  1. function testTableAdd(count)
  2.    local t = {}
  3.    for i = 1, count do
  4.       print("Adding "..i)
  5.       t[i] = "Yes please ".. i
  6.       print(#t)
  7.    end
  8.    print("We counted "..#t.." times")
  9.    return t
  10. end
  11. print(testTableAdd(5))
  12. function testTableAddOutOfOrder()
  13.    local t = {}
  14.    t[3] = "three"
  15.    t[5] = "five"
  16.    t[15] = "wow"
  17.    print("We counted "..#t.." times")
  18.    return t
  19. end
  20. print(testTableAddOutOfOrder())

I was expecting "We counted 5 times" and "We counted 3 times", but the 2nd one says 0 -- but it has the 3 entries.

For the first I can iterate through them with a for i = 1, #t do but the second one that doesn't work since the # is 0. Using a 'pairs' do I got through the second. Hmmm... typing it out it is making more sense why the second loop was failing, because the indexes were different. But some background would still help.

I wonder in my bigger case if I should just fill in the gaps with nils and that might just solve my problem...

Is there a way to add to the table, just to the end of it?

I'm used to

t << 'new entry'

in something like ruby.

Thanks.
  Reply With Quote