我割我的牙齿和Lua,并试图执行一些列表的处理逻辑。我不确定我是否真的掌握了协程和匿名函数的功能,但我正在尝试。我知道这些东西在Ruby/Groovy/Javascript等其他脚本语言中是如何工作的,我想要在Lua中做一些同样聪明的事情。下面是我想出为例:Lua DSL还是聪明的关闭?
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,因为总有做的东西更巧妙的方式...)
“男孩,我怀念在Groovy编码,因为总有做的东西更巧妙的办法......”如果你在打算在Lua编程,再编程* *的Lua。不要希望语言是别的东西,并学会用Lua的方式做事。 – 2012-02-09 18:42:11
放松!我喜欢Lua,这就是为什么我花时间学习它。 :)我只是做了常规的参考,因为这是浮现在脑海,当我贴出第一件事,“有一定有做这一个更巧妙的办法......” – Cliff 2012-02-09 21:39:55