[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: lua idiom: iteration with skips?
- From: "Matthew M. Burke" <mmburke@...>
- Date: Sat, 22 Apr 2006 16:17:17 -0400
Gregg Reynolds wrote:
I need to iterate over a list of items with skip logic. For example, if
item[i] fits some criteria, then skip to item[i+n] else skip to item[i+m].
If I understand the manual, altering an iteration variable is a no-no,
so I can't use a for loop for this.
Here's yet another way to skin this cat. I think it's fairly lua-ish
because a number of other languages don't allow you to take this approach:
function hopscotch(table, processor)
local index = 1
return function ()
if (table[index] == nil) then
return nil
else
local i = index
index = index + processor(table[index])
return i, table[i]
end
end
end
t = {20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
37, 38, 39}
--- if the value is even, we'll skip ahead 3
-- otherwise, we'll skip ahead 5
function p(v)
if ( math.floor(v/2) == v/2) then
return 3
else
return 5
end
end
for k,v in hopscotch(t, p) do
print(k, v)
end
Matt