Ian
01-07-2007, 02:48 AM
It took me a bit to figure out how to make iterators in Lua actually useful. I first wrote a summation function using the pairs() function, but that wasn't enough. I wanted to be able to iterate over each value of the table and then have a custom function handle each value.
Why? Say I have a container filled with a bunch of items that each have a .weight value, then I want to be able to add them all together to get the total weight of the container's contents. Also, I want to do this in one line of code because I'm lazy.
The result should look something like this:
Sum(contents, function (i, item) return i, item.weight end)
Then to make my iterator (actually, a wrapper that returns an iterator function, like pairs):
function IterMap(table, function_)
if not function_ then
return pairs(table)
end
return function (state, index)
local newIndex, value = next(state, index)
if value then
return function_(newIndex, value)
end
return newIndex, value
end, table, nil
end
(Blegh!) This function should behave like a canonical map function, except that it returns an iterator instead of a table of values.
Now to replace pairs() with IterMap() in my Sum() function.
function Sum(table, function_)
local result = 0
for _, value in IterMap(table, function_) do
result = result + value
end
return result
end
I dunno why this isn't built into Lua. Oh well.
Why? Say I have a container filled with a bunch of items that each have a .weight value, then I want to be able to add them all together to get the total weight of the container's contents. Also, I want to do this in one line of code because I'm lazy.
The result should look something like this:
Sum(contents, function (i, item) return i, item.weight end)
Then to make my iterator (actually, a wrapper that returns an iterator function, like pairs):
function IterMap(table, function_)
if not function_ then
return pairs(table)
end
return function (state, index)
local newIndex, value = next(state, index)
if value then
return function_(newIndex, value)
end
return newIndex, value
end, table, nil
end
(Blegh!) This function should behave like a canonical map function, except that it returns an iterator instead of a table of values.
Now to replace pairs() with IterMap() in my Sum() function.
function Sum(table, function_)
local result = 0
for _, value in IterMap(table, function_) do
result = result + value
end
return result
end
I dunno why this isn't built into Lua. Oh well.