lua-users home
lua-l archive

RE: Mapping values from one table to another

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


Greg Bakker wrote:
> { 1, 2, 3 } => { {name="something1", value=1},
> {name="something2", value=2}, {name="something3", value=3} }
> 
> Currently I'm using
> 
> function map(f, v, ...)
> if v then
> return f(v), map(f, ...)
> end
> end
> 
> function func(v) return {name="something"..v, value=v} end 
> 
> a = { 1, 2, 3 }
> b = { map(func, unpack(a)) }
> 
> which is probable stack abuse. Is there a canonical approach; maybe a
> better way is to use a loop and insert-at-end?
You can use a simple loop:
function map(f, a)
 local b = {}
 for k,v in pairs(a) do
 b[k] = f(v)
 end
 return unpack(b)
end

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