【问题标题】:use for loop to call multiple functions in lualua中使用for循环调用多个函数
【发布时间】:2014-11-26 18:51:34
【问题描述】:

我想在 lua 中调用多个非常相似的方法,除了它们的参数改变一个字符。我现在这样做的方式有效,但效率极高。

function scene:createScene(event)

screenGroup = self.view

level1= display.newRoundedRect( 50, 110, 50, 50, 5 )
level1:setFillColor( 100,0,200 )
level2= display.newRoundedRect( 105, 110, 50, 50, 5 )
level2:setFillColor (100,200,0)
--and so on so forth

screenGroup:insert (level1)
screenGroup:insert (level2)
screenGroup:insert (level3)
screenGroup:insert (level4)

end 

我计划将 screenGroop:insert 方法扩展到数百个级别,可能达到 (level300)。如您所见,我现在这样做的方式效率低下。我试过做

for i=1, 4, 1 do 
screenGroup:insert(level..i)
end

但我收到错误“预期的表格”。

【问题讨论】:

标签: for-loop lua coronasdk lua-table scene


【解决方案1】:

在这种情况下,最好的方法可能是使用表格:

local levels = {}
levels[1] = display.newRoundedRect( 50, 110, 50, 50, 5 )
levels[1]:setFillColor( 100,0,200 )
levels[2] = display.newRoundedRect( 105, 110, 50, 50, 5 )
levels[2]:setFillColor (100,200,0)
--and so on so forth

for _, level in ipairs(levels) do
  screenGroup:insert(level)
end

对于其他替代方案,请查看@EtanReisner 评论中的SO answer

【讨论】:

    【解决方案2】:

    如果您的“级别”表是全局的(看起来它们是全局的),您可以使用 getfenv 为它们编制索引。

    for i = 1, number_of_levels do
        screenGroup:insert(getfenv()["level" .. i])
    end
    

    getfenv 以字典的形式返回包含所有全局变量的环境。因此,您可以像getfenv()["key"]这样的普通表一样对其进行索引

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-01
      • 1970-01-01
      • 2020-03-13
      • 2012-11-06
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      相关资源
      最近更新 更多