Custom Iterator Functions

So, I was gladly surprised to find out you can actually put custom functions into iterators (through in f() do), I found this out using the example provided on Pages, however it looks really messy and just flew over me.

Anyway, onto what I want to know, how exactly you’d write one of these functions, so, lets say, a recreation of ipairs

local someList = {"foo", "bar"}

function ipairs(tab)
  --??
end

for key, value in ipairs(someList) do
  print(key,value)
end

You could read through Chapter 7 of the Programming in Lua handbook. It goes into detail about simple, stateless iterators, as well as more complex ones.

Honestly though… I’ve never used them and probably never will. Unless you’re writing a library and have some really specific use case, it’s almost always seems to make code a lot harder to read later on for not a whole lot of benefit. The default iterators are common, easy-to-read, and even optimized by Roblox to run natively under the hood in some cases.

1 Like

This thread can help you:

1 Like

The generic for statement works over functions, called iterators . On each iteration, the iterator function is called to produce a new value, stopping when this new value is nil . The generic for loop has the following syntax:

local iterator = function(tableQuery)
	local tableSize = select("#", unpack(tableQuery))
	local currentIndex = 0
	
	return function()
		currentIndex = currentIndex + 1

		if currentIndex <= tableSize then
			local TableEntity = tableQuery[currentIndex]
			return currentIndex, tableQuery[currentIndex]
		end
	end
end

for k, v in iterator({'hi', 'there'}) do
	print(k, v)
end
2 Likes