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:
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.
You should also define the table t outside the function. Right now you are (re)creating the table every time the function runs, which is terribad.
For production functions, it depends on the purpose of the table, and the frequency with which the function will be run. If it's an OnUpdate script, or running in response to UNIT_AURA events, yes, creating a new table on each run is a big no-no. If it's running in response to a user entering a slash command, or an infrequent event like PLAYER_ENTERING_WORLD, it's not really a big deal, and you should do whatever makes more sense scope-wise for the content/purpose of the table.
|All times are GMT -6. The time now is 03:06 PM.|
vBulletin © 2020, Jelsoft Enterprises Ltd
© 2004 - 2020 MMOUI