[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: Sun, 4 Apr 2010 14:00:10 +0200
On Fri, Apr 2, 2010 at 5:13 AM, King, Mike <MKing@klmicrowave.com> wrote:
> I'm sure you are right. I don't think it can get any worse.
Here is one approach of using an STL-like approach, but with run-time
polymorphism not compile-time, of course.
Take the copy algorithm
t = {}
copy(ipairs(t1),t)
copy(ipairs(t),back_inserter(ls))
The Lua equivalent of *p++ which is happening in std:copy would be t[k] = v, so
function back_inserter(ls)
return setmetatable({},{
__newindex = function(t,k,v)
table.insert(ls,v)
end
} end
And so on for front_inserter, etc.
Combining two tables (the 'union') would be:
res = {}
copy(pairs(t1),res)
copy(pairs(t2),res)
This gets a bit simpler with a sequence concatenation operation pairs2():
copy(pairs2(t1,t2),res)
By default, all sequences are treated as key-value pair values, so
copy(enum(io.lines()),t)
where enum works like Python's enumerate.
Of course, the proxy trick for back_inserter can be extended to I/O streams:
copy(ipairs(t),writer(io.stdout,'\n'))
And so on for copy_if, filter, etc. An actual implementation can be
provided if people are interested, although it can always be an
exercise for the student ;)
steve d.