lua,迭代并调用n=3层表的所有同名函数
lua, iterating and calling all same-named-functions of n=3 tiers of tables
假设我在 {game} 中有多个 table,例如 {bullets},其中 {bullets} 有多个 table,如下所示。我将如何遍历并调用 {game} 中包含的所有更新函数?
--下面是一个简化的例子,假设每个 table in {bullets} 有多个条目而不仅仅是更新。并且最终代码必须适用于 game={bullets,coins,whatever} 这样的情况,每个条目的性质都与子弹相似。
game={}
game.bullets={{update=function(self) end,...}, {update=function(self) end,...},...}
for obj in all(game) do
for things in all(obj) do
things:update() end end
--我不确定自己做错了什么,也不确定是否需要双 for 循环。
--如果子弹没有嵌入{game}中,它只会是:
for obj in all(bullets) do
obj:update()
end
我也试过:
for obj in all(game.bullets) do
obj:update()
end
*更正:这是有效的,但我想解决的问题是,如果我有多个 tables,比如 {game} 中的 {bullets},那么这个问题就可以解决。因此,第一次尝试两次迭代失败了。因此,与其在 {game} 中有物品时多次重复上述内容,我想输入一个语句。
all()
不是 Lua 中的标准函数。这是你在某处找到的辅助函数吗?
如果没有更多示例或说明其使用方式的文档以及预期的 return 值,很难说清楚。好像是一个迭代器,性质类似于pairs()
。可能是这样的:
for key, value in pairs( game ) do
for obj in all( value ) do
obj :update()
end
end
假设我在 {game} 中有多个 table,例如 {bullets},其中 {bullets} 有多个 table,如下所示。我将如何遍历并调用 {game} 中包含的所有更新函数?
--下面是一个简化的例子,假设每个 table in {bullets} 有多个条目而不仅仅是更新。并且最终代码必须适用于 game={bullets,coins,whatever} 这样的情况,每个条目的性质都与子弹相似。
game={}
game.bullets={{update=function(self) end,...}, {update=function(self) end,...},...}
for obj in all(game) do
for things in all(obj) do
things:update() end end
--我不确定自己做错了什么,也不确定是否需要双 for 循环。
--如果子弹没有嵌入{game}中,它只会是:
for obj in all(bullets) do
obj:update()
end
我也试过:
for obj in all(game.bullets) do
obj:update()
end
*更正:这是有效的,但我想解决的问题是,如果我有多个 tables,比如 {game} 中的 {bullets},那么这个问题就可以解决。因此,第一次尝试两次迭代失败了。因此,与其在 {game} 中有物品时多次重复上述内容,我想输入一个语句。
all()
不是 Lua 中的标准函数。这是你在某处找到的辅助函数吗?
如果没有更多示例或说明其使用方式的文档以及预期的 return 值,很难说清楚。好像是一个迭代器,性质类似于pairs()
。可能是这样的:
for key, value in pairs( game ) do
for obj in all( value ) do
obj :update()
end
end