lua-users home
lua-l archive

Re: Embedded 'nil' values - a suggestion

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


>> It is possible. See also recent posts about this on this list:
>>
>> http://lua-users.org/lists/lua-l/2006-02/msg00537.html
>>
>> Specifically the "select("#", ...)" construct.
> Why thank you! Odd, but workable.
As another fun example, define the following functions:
local unpack, select = unpack, select
function pack(...)
 local v = {...}
 local n = select("#", ...)
 return function(f, from, to)
 from = from == nil and 1 or
 from < 0 and n + 1 + from or
 from
 to = to == nil and n or
 to < 0 and n + 1 + to or
 to
 return f(v, from, to)
 end
end
function upairs(v, from, to)
 return function(v, i)
 i = i and i + 1 or from
 if i <= to then
 return i, v[i]
 end
 end, v
end
Examples:
> p = pack("aap", "noot", nil)
> =p(unpack)
aap noot nil
> =p(unpack, 1, -2)
aap noot
> =p(unpack, -2)
noot nil
> for i, v in p(upairs) do print(i, v) end
1 aap
2 noot
3 nil
> for i, v in p(upairs, -2) do print(i, v) end
2 noot
3 nil
--
Wim

AltStyle によって変換されたページ (->オリジナル) /