Page 2 of 2
Re: Hi, I'm wondering how to create my first game
Posted: Thu Jan 17, 2013 8:23 am
by MarekkPie
If order doesn't matter, (and it often doesn't), it's better to use:
Code: Select all
for k,v in pairs(tbl) do --[[ code ]] end
It's a bit faster for not much of a change.
Re: Hi, I'm wondering how to create my first game
Posted: Thu Jan 17, 2013 8:24 am
by Nixola
Actually, ipairs is a bit faster than pairs, and the latter also iterates over every string index of the table
Re: Hi, I'm wondering how to create my first game
Posted: Thu Jan 17, 2013 8:40 am
by MarekkPie
Nixola wrote:Actually, ipairs is a bit faster than pairs, and the latter also iterates over every string index of the table
Looks like you're right; however, ipairs doesn't work if you happen to be using the table as a spare array or map:
Code: Select all
sparse = { [1] = 'one', [3] = 'three', [7] = 'seven' }
for k,v in pairs(sparse) do print(k,v) end
-- some order of ...
1 one
3 three
7 seven
for k,v in ipairs(sparse) do print(k,v) end
1 one
map = { foo = true, bar = false }
for k,v in pairs(map) do print(k,v) end
-- some order of ...
foo true
bar false
for k,v in ipairs(map) do print(k,v) end
-- nothing
When might this matter:
Maybe you have a big old entities table, something like:
Code: Select all
entities = {
player = Player(...),
}
for i = 1, NUM_OF_ENEMIES do table.insert(entities, Enemy()) end
for k,v in pairs(entities) do print(k,v) end
-- hits all the items in entities
for k,v in ipairs(entities) do print(k,v) end
-- skips player
Re: Hi, I'm wondering how to create my first game
Posted: Thu Jan 17, 2013 2:54 pm
by Robin
Q: which of these two functions is faster?
A: not asking this question will save you more time than any difference between these two functions.
Also: use ipairs if you use the table you're iterating over as a sequence (like array in JavaScript or list in Python), use pairs if you use the table you're iterating over as a mapping (like object in JavaScript or dict in Python).