Skip to content

Commit

Permalink
Merge pull request #11 from svermeulen/sverm/infinite-loop-fix
Browse files Browse the repository at this point in the history
Fix for the very common infinite loop issue, when forgetting to call getIterator
  • Loading branch information
Henkoglobin authored Feb 27, 2024
2 parents 5e0d46e + 43c0e77 commit d1b5189
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/lazylualinq.lua
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,13 @@ end
-- as other functions that return a sequence.
function linq.factory(fac)
return setmetatable({}, {
__call = fac,
__call = function(self, ...)
local numArgs = select('#', ...)
if numArgs > 0 then
error("Invalid use of lazylualinq sequence. Did you forget to call it (or getIterator) before using it inside a for loop?", 2)
end
return fac(self)
end,
__index = linq,
__len = function(self)
return self:count()
Expand Down
33 changes: 33 additions & 0 deletions test/intermediate/for_loop.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@

describe("for loop usage", function()
local linq = require("lazylualinq")

it("throws error when getIterator is not called", function()
local seq = linq { 1, 2, 3 }

assert.has_error(function()
for _x in seq do
end
end)

local items = {}
for x in seq() do
table.insert(items, x)
end

assert.is_same(#items, 3)
assert.is_same(items[1], 1)
assert.is_same(items[2], 2)
assert.is_same(items[3], 3)

items = {}
for x in seq:getIterator() do
table.insert(items, x)
end

assert.is_same(#items, 3)
assert.is_same(items[1], 1)
assert.is_same(items[2], 2)
assert.is_same(items[3], 3)
end)
end)

0 comments on commit d1b5189

Please sign in to comment.