selectdictionarylua

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


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.


Solution

  • 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