Skip to content

Instantly share code, notes, and snippets.

@kirdaaa
Last active December 9, 2021 11:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kirdaaa/119310176d2e708bcbb387e547db506d to your computer and use it in GitHub Desktop.
Save kirdaaa/119310176d2e708bcbb387e547db506d to your computer and use it in GitHub Desktop.
local function iterateChildren(instance)
local children = instance:GetChildren()
local index = 0
print("creating a generator")
return function()
print("invoking the generator function")
index += 1
return children[index]
end
end
local folder = Instance.new("Folder", workspace)
Instance.new("Folder", folder).Name = "1"
Instance.new("Folder", folder).Name = "2"
Instance.new("Folder", folder).Name = "3"
for child in iterateChildren(workspace) do
print(child.Name)
end
--> creating a generator
--> invoking the generator function
--> 1
--> invoking the generator function
--> 2
--> invoking the generator function
--> 3
--> invoking the generator function
-- here it breaks the loop since the generator returned nil
-- Note that this generator does not have to go by order too
-- so it can be 3, 1, 2 or 2, 3, 1 ...
-- You can also write it as this
local generator = iterateChildren(folder)
for child in generator do
print(child.Name)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment