Hi, I'm wondering how to create my first game

General discussion about LÖVE, Lua, game development, puns, and unicorns.
User avatar
MarekkPie
Inner party member
Posts: 587
Joined: Wed Dec 28, 2011 4:48 pm
Contact:

Re: Hi, I'm wondering how to create my first game

Post 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.
User avatar
Nixola
Inner party member
Posts: 1949
Joined: Tue Dec 06, 2011 7:11 pm
Location: Italy

Re: Hi, I'm wondering how to create my first game

Post by Nixola »

Actually, ipairs is a bit faster than pairs, and the latter also iterates over every string index of the table
lf = love.filesystem
ls = love.sound
la = love.audio
lp = love.physics
lt = love.thread
li = love.image
lg = love.graphics
User avatar
MarekkPie
Inner party member
Posts: 587
Joined: Wed Dec 28, 2011 4:48 pm
Contact:

Re: Hi, I'm wondering how to create my first game

Post 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
User avatar
Robin
The Omniscient
Posts: 6506
Joined: Fri Feb 20, 2009 4:29 pm
Location: The Netherlands
Contact:

Re: Hi, I'm wondering how to create my first game

Post 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).
Help us help you: attach a .love.
Post Reply

Who is online

Users browsing this forum: No registered users and 3 guests