0 Replies - 314 Views - Last Post: 25 August 2009 - 08:41 AM

#1 KYA   User is offline

  • Wubba lubba dub dub!
  • member icon

Reputation: 3202
  • View blog
  • Posts: 19,235
  • Joined: 14-September 07

[LUA]Creating Your Own Iterator

Posted 25 August 2009 - 08:41 AM

Description: Implement where you may need a custom iterator to traverse your data. The default for loop has its own built in iterator, but you can create your own to suit your needs. Includes example usage.
--creating your own iterator
function values(t)
	local i = 0
	return function () --anon function, creates a closure
		i = i + 1
		return t[i]
	end
end

--example usage
myArray = {10, 20, 30}
for item in values(myArray) do		--using our created iterator (for each implementation)
	print(item)			--continues until nil is returned
end



Is This A Good Question/Topic? 0
  • +

Page 1 of 1