How to use the "in"

Some people think they know how to use “in”, because they think the only way to use it is like this:

for v, i in pairs() do
end

or

for v, i in ipairs() do
end

But thats not the only way to use it:

“in” needs a function to work. “pairs” and “ipairs” are functions that returns other functions.
To follow the loop the function needs to return something.

Example:

function example()
	local value = 1
	
	return value
end

for value in example do
	print(value)
end

Output:
1(inf)

But thats not the best way because is a loop without end. Like “pairs” and “ipairs” you can make a function that returns a function, also you can return the first parameter for the new function, if you return one more parameter, that parameter will only pass in the first new function call, else will give you the number of the call. To stop the loop you need to return nothing, also you can return more than one value.

Example:

function example(number)
	local newFunction = function(firstParameter, otherParameter)
		local value = number
		number-=1
		
		if value > 0 then
			return value, firstParameter, otherParameter
		end
	end
	
	local firstParmeter = "A number"
	local otherParameter = "Only first call"
	
	return newFunction, firstParmeter, otherParameter
end

for value, firstParameter, otherParameter in example(10) do
	print(value, firstParameter, otherParameter)
end

Output:
10 A number Only first call
9 A number 10
8 A number 9
7 A number 8
6 A number 7
5 A number 6
4 A number 5
3 A number 4
2 A number 3
1 A number 2

Thanks for read. I hope this was interesting and helpful. There can be more info but this is the basic to learn how to use “in”.

16 Likes

Thanks for taking the time to explain this. I’ve never really used in in any of these ways besides next and pairs.

This is very helpful, thanks! I do feel like this would fit better in Community Tutorials.

Never thought of this before, I always thought pairs and ipairs returned a custom iterator object but never considered why that would make no sense.

Thank you for this. I’ve always used them for in-pairs.

2 Likes