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
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 »

1) i is a local variable that's given a number by the for statement. You can use any name you want, not just i. It's handy in case you want to know what iteration you're on in the middle of each iteration. For instance, for i=1,20 do print(i) end would print the numbers one through twenty.

2) Since it's getting its number from the for statement, no, you don't need to declare it. Just remember that because it's local, it ceases to exist outside the statement. You could declare it beforehand if you want, but I don't see any point in that.

3) i equals 1 because we just told it it did. i=1,10 means "i is 1, do the following block of code and add 1 to i, and repeat until i is 10".

a.n means that a is a table, and n is a number it contains. In other words, a = { n=9 }, or whatever number it's supposed to be. You could likewise say a = {fish="salmon"} and print(a.fish) (it'd print "salmon"). But as others have said, this isn't a good way of doing it. A much better one is #a, which returns the number of values a contains.
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+.
pekka
Party member
Posts: 206
Joined: Thu Jan 07, 2010 6:48 am
Location: Oulu, Finland
Contact:

Re: Someone Explain Iteration, dear god.

Post by pekka »

Ryne wrote: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!
It's useful to remember that this all is convention. The designers of Lua decided they wanted a for loop with such syntax, so it is in the language, and works as they have specified it. Particularly, in the construct for ??? do the ??? part has a special meaning that only works exactly so in this particular context.

So, if you look at code, you first spot the pair for and do, and then work out what the inner part does. When you know what a for loop is supposed to do, you can answer your questions as follows:

1: There must always be some for loop variable. This time its name is 'i'.
2. You never have to declare for loop variable beforehand. You only do it if you need to do it for a specific reason.
3. The for loop variable varies over time. When it says i = a, b, then i takes all the values from a to b in, once each.

You can read the statement for x = 1, 10 do many ways. One possibility is: let x take all the values from one to ten and execute the following code.

Here is an example you can modify and run. If you don't yet have the command line lua interpreter, please install it as it is far quicker & simpler to test little code snippets with it than with Löve. You can learn much faster if you try all the things you read from the book and then modify and test the code until you know precisely what it means!

Code: Select all

for loopVar = 1, 10, 3 do
    print("A new loop iteration begins. The value of loopVar is now: " .. loopVar)
    print("Its square is: " .. loopVar * loopVar)
    print("This iteration ends.")
end
print("The loop has finished now.")
Try changing the three values in the number for loop to verify that they mean the beginning, the end, and the step for each iteration, respectively. Try the triple 10, -10, -4 for example.

You should keep this code snippet as a reference for later. You can build on this to understand the more advanced uses of the for loop in Lua.
User avatar
ghostwriter
Prole
Posts: 38
Joined: Sat Dec 11, 2010 11:08 pm

Re: Someone Explain Iteration, dear god.

Post by ghostwriter »

In case it's still not clear, in the code you posted "i" is incremented in every iteration. It sort of tells you how many times you have run the loop. For example:

Code: Select all

for i=1,4 do
    print i
end
is equivalent to

Code: Select all

print 1
print 2
print 3
print 4
When the loop runs, "i" starts with a value of 1, then increases by one every time until it gets to 4.
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, I think we can lock this thread or something. There's two pages of explanations of loops, and after the first three replies, Ryne already said:
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!
Help us help you: attach a .love.
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 »

Perhaps a few explainations of pairs and ipairs are in order then.
Kurosuke needs beta testers
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 »

But... But... Where else are we going to be able to express our love for explaining loops?
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 »

TechnoCat wrote:But... But... Where else are we going to be able to express our love for explaining loops?
While talking about Lua, the cat!
Kurosuke needs beta testers
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 »

tentus wrote:Perhaps a few explainations of pairs and ipairs are in order then.
Dude, first reply. I gave an explanation of both pairs and ipairs. :ehem:
Help us help you: attach a .love.
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 »

Only one reply though. I was honestly surprised that you were the only one who touched the subject, and it's one well worth covering in depth in my opinion.

To post a working example of some for-reals game code using pairs, see the way that I handle players/enemies/npcs below:

First, I have a table called actors, which holds subtables of each actor type. This is (effectively) in love.load:

Code: Select all

	actors = {
		avatars = {},
		baddies = {},
		bosses = {},
		npcs = {}
	}
Because each actor is an object in its own right, they all have an update function that is run individually using a for loop inside a for-pairs loop inside of love.update:

Code: Select all

	for key, value in pairs(actors) do 
		for i=1, #actors[key] do 
			actors[key][i]:update(dt)
		end
	end
The inner loop can be numerical because of how I stick baddies into the game (this is one of several ways to do this, but this works particularly well if we want to add an extra one in after we've started playing):

Code: Select all

actors.baddies[#actors.baddies + 1] = baddie:new()
And then drawing them is pretty much the exact same situation:

Code: Select all

	for key, value in pairs(actors) do 
		for i=1, #actors[key] do 
			actors[key][i]:draw()
		end
	end
The above code gives me a great deal of flexibility and control in each level. I use the same system for level geometry, items, even projectile attacks.
Kurosuke needs beta testers
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 »

tentus wrote: Because each actor is an object in its own right, they all have an update function that is run individually using a for loop inside a for-pairs loop inside of love.update:

Code: Select all

	for key, value in pairs(actors) do 
		for i=1, #actors[key] do 
			actors[key][i]:update(dt)
		end
	end
The inner loop can be numerical because of how I stick baddies into the game (this is one of several ways to do this, but this works particularly well if we want to add an extra one in after we've started playing):

Code: Select all

actors.baddies[#actors.baddies + 1] = baddie:new()
Why do you do that instead of

Code: Select all

for key, value in pairs(actors) do 
	for k, a in ipairs(value) do 
		a:update(dt)
	end
end
And

Code: Select all

table.insert(actors.baddies, baddie:new())
Surely these are both faster and easier to work with?
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+.
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot] and 79 guests