Mryeetmemes

Using coroutines as iterators

Jul 6th, 2021
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. local function BasePartIterator(Table)
  2. local Length = #Table;
  3. local Thread = coroutine.create(function(_, Index)
  4. if (not Index) then --// If we're not passed an Index, make it 1;
  5. Index = 1;
  6. else
  7. Index = Index + 1; --// Otherwise increase it
  8. end
  9.  
  10. for i = Index, Length do --// From the current Index to the Length
  11. if (Table[i]:IsA("BasePart")) then
  12. coroutine.yield(Table[i], i); --// These will be passed back again next iteration
  13. end
  14. end
  15.  
  16. --// If none is found then it'll return nil, nil stops the for loop iterating
  17. end
  18.  
  19. return function() --// Iterator
  20. local Success, BasePart, Index = coroutine.resume(Thread)
  21. return BasePart, Index;
  22. end
  23. end
  24.  
  25. local WorkspaceDescendants = workspace:GetDescendants();
  26. for BasePart, IndexFound in BasePartIterator(WorkspaceDescendants) do
  27. print(BasePart:IsA("BasePart")); --// Always true
  28. print(WorkspaceDescendants[i] == BasePart); --// Also always true
  29. end
Advertisement
Add Comment
Please, Sign In to add comment