# [LUA]Function-Table Map

Page 1 of 1

## 0 Replies - 1682 Views - Last Post: 06 July 2010 - 08:04 PM

### #1 athlon32

• D.I.C Regular

Reputation: 117
• Posts: 363
• Joined: 20-August 08

# [LUA]Function-Table Map

Posted 06 July 2010 - 08:04 PM

Description: Tested on Lua 5.1.3A nifty map function that given a table and function, will return a new table where each key is mapped to the result of the function with the key's value passed as its parameter.
```-- To explain this simply, given a function 'f', and a table 't',
-- that is equal to something such as {h=3, k=4, ...}, the result
-- of this function would be: {h=f(3), k=f(4), ...}.
function map(f, t)
for k,v in pairs(t) do
t[k] = f(v);
end

return t;
end

-- Example usage. Get rid of when needed.
local p   = {3,5,6,4,7,3};
local sqr = function(x) return x*x; end

local y = map(sqr, p);
for k,v in pairs(p) do print(v); end
```

Is This A Good Question/Topic? 0

## Replies To: [LUA]Function-Table Map

### #2 athlon32

• D.I.C Regular

Reputation: 117
• Posts: 363
• Joined: 20-August 08

## Re: [LUA]Function-Table Map

Posted 06 July 2010 - 08:04 PM

Description: Tested on Lua 5.1.3A nifty map function that given a table and function, will return a new table where each key is mapped to the result of the function with the key's value passed as its parameter.
```-- To explain this simply, given a function 'f', and a table 't',
-- that is equal to something such as {h=3, k=4, ...}, the result
-- of this function would be: {h=f(3), k=f(4), ...}.
function map(f, t)
local _map = {};

for k,v in pairs(t) do
_map[k] = f(v);
end

return _map;
end

-- the same as 'map', except that the changes are reflected
-- in the original table.
function appliedmap(f, t)
for k,v in pairs(t) do
t[k] = f(v);
end
end

-- Example usage. Get rid of when needed.
local p   = {3,5,6,4,7,3};
local sqr = function(x) return x*x; end

local y = map(sqr, p);
for k,v in pairs(y) do print(v); end
```