是否存在与Scala的地图或C#的Select函数相当的lua?

ACy*_*lic 3 lua select map

我正在寻找一种在Lua桌上进行地图/选择的好方法.

例如.我有一张桌子:

myTable = {
  pig = farmyard.pig,
  cow = farmyard.bigCow,
  sheep = farmyard.whiteSheep,
}
Run Code Online (Sandbox Code Playgroud)

如何编写myTable.map(function(f)f.getName)?[假设所有农场动物都有名字]

即.将该函数应用于表中的所有元素.

Mik*_*ran 5

写自己的版本?在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)
Run Code Online (Sandbox Code Playgroud)

生产:

pig pig
sheep   white sheep
cow big cow
pig PIG
cow BIG COW
sheep   WHITE SHEEP
Run Code Online (Sandbox Code Playgroud)