Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

What are all the generic loop functions?

I would really like to know, right now all I can understand is the index function. Would someone mind explaining the rest?

3 answers

pairs, ipairs and next are the built-in global functions used in generic for loops for indexing through tables. I don't know anything about an "index" function.

local t={'a','b','c','d','e','f',a=1,b=2,c=4,d=8,e=16,f=32}
for _,v in pairs(t)do
	print(_,v)
end

Output:

1	a
2	b
3	c
4	d
5	e
6	f
d	8
e	16
f	32
a	1
b	2
c	4

pairs has no particular order for indices that are non-numerical.

for _,v in ipairs(t)do
	print(_,v)
end

Output:

1	a
2	b
3	c
4	d
5	e
6	f

ipairs does not index non-numerical indices at all.

for _,v in next,t do
	print(_,v)
end

Output:

(same output as pairs)

Calling next(t) will tell you whether or not the table is empty.

The generic for loop can also be used with your own functions:

for v in function(_,n)
	return(n or 0)+1
end do
	print(v)
end

This will count up forever.

2 comments

0

I don't quite get it... what's the difference?

0

pairs indexes numerical indices in order and then non-numerical indices in no particular order, where the two arguments are the key and the value. ipairs indexes only numerical indices, where the two arguments are the numerical index and its value. A generic for loop using the next function accomplishes the same thing as pairs. Custom generic for functions are uncommon, you will probably never see

While true do -- Infinite Loop, crashes if there is no wait()
print("hi")
wait(1)
end
for i = 1,10 do --For loop. This loop will print yo 10 times. 
print("yo")
end

This discussion is preserved as it was. New answers, comments, and votes are closed.