"do" on its own does not create a loop. This, for example, is not a loop:
Code:
do
local n = 42
function PrintN()
print("The number is:", n)
end
end
"do ... end" creates a scoping block. In the above example, the variable "n" is only available inside the "do ... end" block, but the function "PrintN" is available anywhere, since it isn't local to the block.
A loop simply defines a "do ... end" block, and adds some code that causes the block to be repeated.
Code:
for i = 1, 3 do
print(i * 3)
end
... is simply a shortcut for doing:
Code:
local i = 1
print(i * 3)
i = i + 1
print(i * 3)
i = i + 1
print(i * 3)
Of course, you could also simplify that to:
Code:
print(1 * 3)
print(2 * 3)
print(3 * 3)
But, depending on the complexity of the task you need to repeat with an incrementing value, a loop rapidly becomes far more efficient to write and maintain.
Also, loops make it much easier to run a block of code X times, where X is not a number of you know beforehand and can change depending on other factors. For example, if you wanted to print the names of everyone in your guild, you could do:
Code:
local name = GetGuildRosterInfo(1)
if name then print(name) end
name = GetGuildRosterInfo(2)
if name then print(name) end
name = GetGuildRosterInfo(3)
if name then print(name) end
name = GetGuildRosterInfo(4)
if name then print(name) end
... and so on and so forth all the way up to 1000 (the current maximum size of a guild). Obviously this would be extremely tedious to write, even worse to modify (if you wanted to change what happened for each guild member, for example), and take up a lot of space. A loop can make that much less painful:
Code:
for i = 1, GetNumGuildMembers() do
local name = GetGuildRosterInfo(i)
print(name)
end
Here, the upper limit on the loop is dynamic, and depends on how many characters are actually in your guild when you run the code.
We can also use the "break" operator to stop running a loop before it reaches the maximum index. This is useful for things like getting information about buffs on the player, since there is no function that tells you how many buffs are on you.
Code:
local total = 0
for i = 1, 40 do
local name = UnitBuff("player", i)
if name then
print("Buff #" .. i .. ": " .. name)
total = total + 1
else
break
end
end
print("Total buffs: " .. total)
We use 40 as the upper limit on the loop, because that's the maximum number of buffs you can have, but we also use the "break" operator so that after we've gotten through all of the buffs, we don't keep running the loop. If you only have 3 buffs, for example, the loop will only run 4 times (once for each buff, then once more to determine that there aren't any more buffs) instead of 40 times.