Someone Explain Iteration, dear god.

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
User avatar
Ryne
Party member
Posts: 444
Joined: Fri Jan 29, 2010 11:10 am

Someone Explain Iteration, dear god.

Post by Ryne »

Hello, I want to ask a question on iteration. I've been trying to read the entire PIL book, and understand it, though I'm stuck on all of the iteration/loop based things.

Could someone please explain this code, how it works, why it's worded the way it is, as if you were explaining it to a 10 year old?

Code: Select all

    local found = nil
    for i=1,a.n do
      if a[i] == value then
        found = i      -- save value of `i'
        break
      end
    end
    print(found)
I more or less don't understand what/why exactly "for i=1, 1.n" is there, the other code makes sense. The same goes for "for i,v in ipairs(arg) do" in this code as well.

Code: Select all

    function print (...)
      for i,v in ipairs(arg) do
        printResult = printResult .. tostring(v) .. "\t"
      end
      printResult = printResult .. "\n"
    end
Thanks a lot!
@rynesaur
User avatar
Robin
The Omniscient
Posts: 6506
Joined: Fri Feb 20, 2009 4:29 pm
Location: The Netherlands
Contact:

Re: Someone Explain Iteration, dear god.

Post by Robin »

OK, the first variant is the "simple" one, in terms of technology, maybe not in terms of understanding it.

Code: Select all

for i = a, b do
really means "do something a number of times" (which is what iteration means).

So

Code: Select all

for i = 1, 4 do
   print "hi"
end
is the same as

Code: Select all

print "hi"
print "hi"
print "hi"
print "hi"
The big difference is that with iteration, you're in charge how often the code gets repeated, it could be something else every single time.

Even more interesting is when you do "break" on a certain condition. "break" is a way to sort of bail out of the loop. "Okay, I said I was going to run this bit a hundred times, but after ten times, I realised I was already done, so you can skip on the ninety iterations to come."

And "i" (or whatever you call it) is the counter, that keeps track of where you are.

"while" and the other forms of iteration are mostly the same.

If you still don't get numerical for, say so and we'll go a bit more in depth.

Now, the second form of for:

Code: Select all

for something in iterator do
This is a bit of a higher level thing, and you can think of it like a "for each": "for each something in iterator do code"

Example:
"For each enemy in this level, update it."
Now tables in Lua are very simple and they are not what is called iterators.* So, in come the functions pairs and ipairs, which take a table and return an iterator.

Doing

Code: Select all

for index, item in ipairs(list) do
    print(index, item)
end
is equivalent to doing

Code: Select all

for index = 1, #list do -- you know the length operator?
    local item = list[index]
    print(index, item)
end
That means giving the above

Code: Select all

list = {}
list[1] = 4
list[2] = 6
list.hi = 2
list[100] = 8
will print

Code: Select all

1       4
2       6
Now pairs on the other hand iterates over all keys. That means it can't deliver them in order, but whatever. Doing a

Code: Select all

for key, item in pairs(list) do
    print(key, item)
end
will probably print something like

Code: Select all

2       6
hi      2
1       4
100     8
I hope this helps a bit.

* In languages like Python, this is different, you can do:

Code: Select all

friends = ["Ellie", "Morgan", "Chuck", "Devon"]
for person in friends:
    print person, "is my friend"
Help us help you: attach a .love.
User avatar
bartbes
Sex machine
Posts: 4946
Joined: Fri Aug 29, 2008 10:35 am
Location: The Netherlands
Contact:

Re: Someone Explain Iteration, dear god.

Post by bartbes »

Alright, for is your basic loop, there are 2 types of for loop, the generic for and the numerical for, let's start with the numerical one.
As you've seen it has this syntax:

Code: Select all

for variable=start, end, step do
--contents
end
Now what it does, first it sets the variable to start, and runs the code in the loop, then it adds step (defaults to 1 when not specified), checks whether the variable is less than or equal to end, and if so, runs the code in the loop again, it repeats this process until variable is bigger than end.
In case you do understand repeat .. until (possibly due to it sounding like words ;)), it's equivalent to this:

Code: Select all

variable = start
repeat
--contents
variable = variable + step
until variable > end
Does this help? If not, say so, if it does, say that as well, then I can write something up for generic for.

Pre-Post: Bah, robin ninjad me, but I'll post this anyway.
User avatar
tentus
Inner party member
Posts: 1060
Joined: Sun Oct 31, 2010 7:56 pm
Location: Appalachia
Contact:

Re: Someone Explain Iteration, dear god.

Post by tentus »

A little useful elaboration on for loops (you will use for loops a lot in video games, so it's pretty useful to get):

Any for loop has three clauses, though Lua has defaults that let you cut it down to fewer.
1. The init clause, which is usually something like i=1. This gives you a variable to work with in the loop.
2. The condition clause, which tells Lua when to stop. This is usually simple number (a.n is probably an integer in a table).
3. The next clause, which tells Lua how much the next iteration will be. This is defaulted to 1, so in each loop the i value is 1 greater than the one before.

In a lot of languages, you have to manually say something like for(i=1; i==number; i++), but lua lets you say the same thing much simpler: for i=1, number. Now, sometimes you want that extra control, like iterating backwards through an array, or jumping forwards in larger units. Then your Lua would look like this: for i=1, screenWidth, 32 (if you wanted to do something across your screenWidth every 32 pixels).

Edit: Humbug, bart ninjad me, but I'm posting too.
Kurosuke needs beta testers
User avatar
Ryne
Party member
Posts: 444
Joined: Fri Jan 29, 2010 11:10 am

Re: Someone Explain Iteration, dear god.

Post by Ryne »

Okay, that makes a lot better sense now. The issue is that in the PIL book they really don't explain those at all. Thanks a lot guys!
@rynesaur
User avatar
Robin
The Omniscient
Posts: 6506
Joined: Fri Feb 20, 2009 4:29 pm
Location: The Netherlands
Contact:

Re: Someone Explain Iteration, dear god.

Post by Robin »

Ryne wrote:Okay, that makes a lot better sense now. The issue is that in the PIL book they really don't explain those at all. Thanks a lot guys!
This reminds me of Project LoveChild (especially the "as if you were explaining it to a 10 year old?"). This is definitely one of the things it should explain.

Unfortunately it's not the best time to start that all up again.

When the time comes, would you be interested in cooperating as a sort of beta-tester (and maybe more)?
Help us help you: attach a .love.
User avatar
Ryne
Party member
Posts: 444
Joined: Fri Jan 29, 2010 11:10 am

Re: Someone Explain Iteration, dear god.

Post by Ryne »

Robin wrote:
Ryne wrote:Okay, that makes a lot better sense now. The issue is that in the PIL book they really don't explain those at all. Thanks a lot guys!
This reminds me of Project LoveChild (especially the "as if you were explaining it to a 10 year old?"). This is definitely one of the things it should explain.

Unfortunately it's not the best time to start that all up again.

When the time comes, would you be interested in cooperating as a sort of beta-tester (and maybe more)?
Yes. :)
@rynesaur
User avatar
TechnoCat
Inner party member
Posts: 1611
Joined: Thu Jul 30, 2009 12:31 am
Location: Denver, CO
Contact:

Re: Someone Explain Iteration, dear god.

Post by TechnoCat »

All of these explanations are excellent and explain general case. But, I want to talk about this specific example a little bit.
Ryne wrote:Could someone please explain this code, how it works, why it's worded the way it is, as if you were explaining it to a 10 year old?

Code: Select all

    local found = nil
    for i=1,a.n do
      if a[i] == value then
        found = i      -- save value of `i'
        break
      end
    end
    print(found)
I more or less don't understand what/why exactly "for i=1, 1.n" is there, the other code makes sense.
The "a.n" is the length of the table ("n" being the number of items is a mathematical convention). This is not the best way to specify length of the table and should probably be "#a".

This iteration is being used to test if a value is in the table. Before the iteration you define the value of "value" to check for and set "found" to false. Now it iterates over the table "a.n" times. If the value is found, set found equal to the value and "break". "break" leaves the current loop (a "for" in this case).

So if the "for" loop is done and "found" is still nil, then the value you are looking for doesn't exist in the table. Or at least, not over the part you iterated. These are not the values you are looking for. FORCE MINDTRICK

Another note is that if the value shows up more than once in a table, you will only find the first one. Also, this form of searching is O(N) time complexity. And if you plan to do a lot of searching in your code on the fly on large sets of items (more than 5000 probably), consider learning some more advanced data structures.
User avatar
Taehl
Dreaming in associative arrays
Posts: 1025
Joined: Mon Jan 11, 2010 5:07 am
Location: CA, USA
Contact:

Re: Someone Explain Iteration, dear god.

Post by Taehl »

Iterators are wonderful. For a more practical example, say you want to be able to draw a bunch of enemies on the screen, but you don't know how many, and enemies may be spawned or killed at any time (perfect for a zombie game ;) ). How would you ever do it without iterators? You probably wouldn't. But WITH iterators, it becomes amazingly simple. Just make a table with your enemies (I'm making each enemy a table, or if you're familiar with some other languages, an "object")...

Code: Select all

enemies = {}		-- enemies will be stored in here

function spawnEnemy(x,y)
	local e = {
		x = x or 50,	-- spawnEnemy can be called with coordinates,
		y = y or 50,	-- but if none are given, default to the position (50, 50)
		i = graphics.enemy,		-- pretend graphics.enemy is a drawable
	}
	table.insert(enemies, e)
end

for i=1,100 do		-- another example of an iteration: spawn 100 enemies at random places
	spawnEnemy(math.random(800), math.random(600))
end
And then you need to draw them. But since we're using iterators, it's the easiest thing in the world:

Code: Select all

function love.graphics.draw()
	for k,enemy in ipairs(enemies) do
		love.graphics.draw(enemy.i, enemy.x,enemy.y, 0, 1,1, 16,16)
	end
end
In for loops k and v are oft-used variable names (short for "key" and "value", that is, the index and contents of each item in the table), but you can use any variable names you want. Note how I use enemy.i, enemy.x, and enemy.y - those are the i, x, and y given to the enemy in spawnEnemy(), and since each enemy is a different table, each one can have unique values. So not only could you have each enemy have its own coordinates, you could give them different sprites, too. You could just as easily run their AI or movement with iterations.

When an enemy is killed, simply use table.remove(enemies, k) to get rid of it. Since it's gone from the enemies table, it will no longer be iterated on (that is, it'll stop being drawn) and will shortly be removed from memory by Lua's excellent garbage-collection.
Earliest Love2D supporter who can't Love anymore. Let me disable pixel shaders if I don't use them, dammit!
Lenovo Thinkpad X60 Tablet, built like a tank. But not fancy enough for Love2D 0.10.0+.
User avatar
Ryne
Party member
Posts: 444
Joined: Fri Jan 29, 2010 11:10 am

Re: Someone Explain Iteration, dear god.

Post by Ryne »

Thanks for the detailed explanations guys. I just find myself looking at something like:

Code: Select all

    local found = nil
    for i=1,a.n do
      if a[i] == value then
        found = i      -- save value of `i'
        break
      end
    end
    print(found)
And asking myself:

1. Why is that "i" there?
2. Was I suppose to declare the "i" before hand?
3. why is "i" equal to 1? and what is "a.n".

Thanks again guys!
@rynesaur
Post Reply

Who is online

Users browsing this forum: Semrush [Bot] and 83 guests