Lua有类似于Scala的map或C#的Select功能的等效函数吗?

我正在寻找一种好的方法来对 Lua 表格进行映射 / 选择。

例如,我有一个表格:

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

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

即应用该函数到表格中的所有元素。

点赞
用户1516484
用户1516484

如果您正在使用 Lua 5.1,那么可以使用 table.foreach()

a = { 1, 2, 3 }
table.foreach(a, function(k,v) a[k] = v + 2 end)
table.foreach(a, print)
-- 1    3
-- 2    4
-- 3    5

然而,这种方法已经被弃用,在 5.2 中已不再支持。

2012-07-26 13:25:25
用户1208078
用户1208078
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)

输出结果为:

pig pig
sheep   white sheep
cow big cow
pig PIG
cow BIG COW
sheep   WHITE SHEEP
2012-07-26 14:41:59
用户2349885
用户2349885

一种使用元表的优雅解决方案:

map = function (old_t, f)
    return setmetatable({}, {
        __index = function (new_t, k)
            new_t[k] = f(old_t[k])
            return new_t[k]
        end
    })
end

结果表仅在需要时才计算每个条目,本质上是一个惰性表。

这意味着它也可以在无限惰性列表和表上工作,但有一个警告 - 即如果 f 对于相同的输入不总是返回相同的结果,那么由于函数调用被延迟,所以当创建表时和每个键第一次索引时,结果表的行为可能会有所不同,这需要注意。

2018-05-01 22:14:25
用户11111710
用户11111710

以下是 Lua 中的 map 函数示例 -

function(f, t)
    local o = {}
    for i = 1, #t do
        o[#o + 1] = f(t[i])
    end
    return o
end

请注意:上述实现未经优化。它应该可以满足您的要求。但是,如果您想要 Lua 中最快的 map() 函数之一的实现,可以查看此网址 - Lua Map Function 其中包含代码和说明。

2019-02-25 04:43:08
用户6551181
用户6551181

好吧,所有其他答案都提供了一个缓慢的 map 函数。当您在表中有超过几个元素时,您将能够看到性能差异。

这是最快的纯 Lua map() 函数 -

function map(f, t)
    local t1 = {}
    local t_len = #t
    for i = 1, t_len do
        t1[i] = f(t[i])
    end
    return t1
end

它不使用循环中的 # 运算符进行比较,也不执行 t1[#t1+1],这两个都很慢。

PS:这段代码来自于这篇文章

2019-07-18 12:48:19