Iterators and Generic For
Filter Loop
Combine ipairs with an if guard to keep selected values.
Filter Loop
filter_loop.lua
local limit =
local kept = 0
local last = 0
for _, value in ipairs({2, 4, 6, 8}) do
if value >= limit then
kept = kept + 1
last = value
end
end
print("limit=" .. limit)
print("kept=" .. kept)
print("last=" .. last)
local limit =
local kept = 0
local last = 0
for _, value in ipairs({2, 4, 6, 8}) do
if value >= limit then
kept = kept + 1
last = value
end
end
print("limit=" .. limit)
print("kept=" .. kept)
print("last=" .. last)
local limit =
local kept = 0
local last = 0
for _, value in ipairs({2, 4, 6, 8}) do
if value >= limit then
kept = kept + 1
last = value
end
end
print("limit=" .. limit)
print("kept=" .. kept)
print("last=" .. last)
guarded iteration
A loop can visit every value while an `if` statement decides which values affect the accumulated result.