FOR_ALL


for variable in all( table ) do
variable a local variable name (used within this loop) that will hold the value data (right column data of the table)
table variable name of a numbered table

This loop will repeat the code after do for each entry of a numbered table provided as an argument. As it loops, it will also set the value for each entry as whatever variable name you give them after for.


Example:

HighScores
john 143
bob 99
kim 984
for score in all( highscores )
	print( score )
end

-- prints: 143 99 984


Also Works with Strings

If you want to loop through each character in a string, then this loop can even handle strings in replace of the table argument.

For example:

string = "hello world"

for character in all(string) do
	print( character )
end

--prints:
h
e
l
l
o

w
o
r
l
d



Useful with Nested Tables

If you are using Nested Tables / Collection of Objects, then this loop is very good for iterating through each inner table and makes it easy to manipulate each inner table.

For example, here is an enemies table of enemy tables:

enemies={
	{ name="goomba", sprite=10, x=30, y=15 },
	{ name="koopa", sprite=11, x=40, y=35 },
	{ name="boo", sprite=12, x=50, y=65 }
}
Enemies
1
name goomba
sprite 10
x 30
y 15
2
name koopa
sprite 11
x 40
y 35
3
name boo
sprite 12
x 60
y 55

We can use the for in all loop with this table, to update and draw each enemy object easily like this:

function _update()
	for e in all(enemies) do
		e.x+=1
		e.y+=1
	end
end

function _draw()
	for e in all(enemies) do
		spr(e.sprite,e.x,e.y)
	end
end

This loop allows us to consider each enemy table as e, and then update every enemy's x and y position, and draw every enemy with a single line with their own sprite and position.


Images in this Guide by NerdyTeachers is licensed under CC BY-SA 4.0

2155

15 Jun 2023

Font