gpt4 book ai didi

list - Lua DSL 还是聪明的闭包?

转载 作者:行者123 更新时间:2023-12-05 01:03:09 25 4
gpt4 key购买 nike

我正在尝试使用 Lua 并尝试实现一些列表处理逻辑。我不确定我是否真正掌握了协程和匿名函数的力量,但我正在尝试。我知道这些东西在 Ruby/Groovy/Javascript 等其他脚本语言中是如何工作的,我想在 Lua 中做一些同样聪明的事情。这是我提出的一个例子:

model = { { player = "Cliff", age = 35, gender = "male" }, { player = "Ally", age = 36, gender = "female" }, { player = "Jasmine", age = 13, gender = "female" }, { player = "Lauren", age = 6.5, gender = "female" } }

function allplayers()
return coroutine.create(function()
for idx, each in ipairs(model) do
coroutine.yield(idx, each)
end
end)
end

function handlePlayers(source)
local status, idx, each = coroutine.resume(source)
while each do
print(idx, each.player)
status, idx, each = coroutine.resume(source)
end
end

function having(source, predicate)
return coroutine.create(function()
local status, idx, each = coroutine.resume(source)
while each do
if predicate(each) then
coroutine.yield(idx, each)
end
status, idx, each = coroutine.resume(source)
end
end)
end

handlePlayers(having(allplayers(), function(each) return each.age < 30 end))

理想情况下,我希望能够编写如下代码:
allplayers(having(function(each) return each.age < 30 end))

甚至更好:
allplayers(having({each.age < 30 }))

产生相同的输出,但我无法完全理解如何或什至可以做到这一点。我上面的所有迭代和循环以及所有内容似乎都过于多余。有没有更好的方法来做到这一点? (男孩,我想念在 Groovy 中编码,因为总有一种更时髦的方式来做某事......)

最佳答案

如果您不需要重用过滤后的结果,请考虑使用迭代器:

model = {
{ player = "Cliff", age = 35, gender = "male" },
{ player = "Ally", age = 36, gender = "female" },
{ player = "Jasmine", age = 13, gender = "female" },
{ player = "Lauren", age = 6.5, gender = "female" }
}

function model:having(predicate)
local index = 0
return function()
while true do
index = index + 1
if index > #self then break end
if predicate(self[index]) then return self[index] end
end
end
end

for item in model:having(function(m) return m.age < 30 end) do
print(item.player)
end

关于list - Lua DSL 还是聪明的闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9215256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com