[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Shorthand for appending to a table (was Re: 5.2 feature list?)
- From: Andreas Stenius <kaos@...>
- Date: Tue, 12 Sep 2006 09:54:16 +0200
Luiz Henrique de Figueiredo skrev:
"t[] = value" as sugar for "t[#t+1]" can be easily done with token filters.
at least if t is a single name, not a full expression. --lhf
Very true.
Wrote this in 5 minutes.
Example (from a live session, meaning I've actually tested this, at
least once ;) :
> t = { "foo", "bar" }
> t[]="foobar"
> for k, v in ipairs(t) do print(k, v) end
1 foo
2 bar
3 foobar
>
t can be any *single* <name> token. Source is attached.
Requires dsilvers token filter patch.
//Andreas
-- syntactic sugar for LongTableName[] = value => LongTableName[#LongTableName + 1] = value
local function table_append_sugar(src)
return function(get,put)
put("table_append init") -- Eaten during the pipe setup
local name
while true do
local line, tok, val = get()
put( line, tok, val )
if tok == "<name>" then
name = val
elseif tok == "[" then
local line2, tok2, val2 = get()
if line == line2 and tok2 == "]" then
put( line, "#", nil )
put( line, "<name>", name )
put( line, "+", nil )
put( line, "<number>", 1 )
end
put( line2, tok2, val2 )
end
end
end
end
local function pipe(f,get,put)
put = put or coroutine.yield
local F=coroutine.wrap(f)
F(get,put)
return F
end
local pipeline
local getter
function _TOKEN_PUMP(_getter, source)
if _getter then
getter = _getter
pipeline = pipe(table_append_sugar(source), getter)
else
return pipeline()
end
end