[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: STL like algorithms for Lua
- From: steve donovan <steve.j.donovan@...>
- Date: Mon, 5 Apr 2010 14:43:21 +0200
On Sun, Apr 4, 2010 at 2:00 PM, steve donovan <steve.j.donovan@gmail.com> wrote:
> Take the copy algorithm
>
> t = {}
> copy(ipairs(t1),t)
The problem, of course, is that functions like pairs & ipairs do not
return a single value. So it has to be backwards:
t = copy({},ipairs{10,20,30})
copy(inserter(t),ipairs{40,50})
copy(writer(io.stdout,' '),ipairs(t))
t = {}
copy(t,pairs{a=1,b=2})
copy(t,pairs{c=2,d=3})
--> t is {a=1,b=2,c=2,d=3}
Here's what the code looks like - very straightforward. Anyone wishing
to add the others can find them here:
http://www.cplusplus.com/reference/algorithm/
steve d.
-----------------
function copy (t,...)
for k,v in ... do
t[k] = v
end
return t
end
function copy_if (t,pred,...)
for k,v in ... do
if pred(v) then
t[k] = v
end
end
return t
end
local function _newindex_handler (handler)
return setmetatable({},{
__newindex = handler
})
end
function inserter (ls)
local append = table.insert
return _newindex_handler(function(t,k,v)
append(ls,v)
end)
end
function writer (f,delim)
return _newindex_handler(function(t,k,v)
f:write(v)
if delim then f:write(delim) end
end)
end
----------------------