Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a lua equivalent of Scala's map or C#'s Select function?

Tags:

select

map

lua

I'm looking for a nice way to do a map / select on a Lua table.

eg. I have a table :

myTable = {
  pig = farmyard.pig,
  cow = farmyard.bigCow,
  sheep = farmyard.whiteSheep,
}

How do I write myTable.map(function(f) f.getName)? [Assuming all farmyard animals have names]

ie. apply the function to all elements in the table.

like image 804
ACyclic Avatar asked Jul 26 '12 13:07

ACyclic


1 Answers

write your own version? there isn't a built-in function to do this in lua.

function map(tbl, f)
    local t = {}
    for k,v in pairs(tbl) do
        t[k] = f(v)
    end
    return t
end

t = { pig = "pig", cow = "big cow", sheep = "white sheep" }
local newt = map(t, function(item) return string.upper(item) end)

table.foreach(t, print)
table.foreach(newt, print)

produces:

pig pig
sheep   white sheep
cow big cow
pig PIG
cow BIG COW
sheep   WHITE SHEEP
like image 140
Mike Corcoran Avatar answered Oct 19 '22 11:10

Mike Corcoran