lua - 如何使大嵌套 'for loops'循环更紧凑?有什么解决办法吗?

标签 lua

我想知道是否有一种方法可以使大型嵌套“for 循环”更加紧凑,从而减少代码。

for a = 1, 10 do
  for b = 1, 10 do
    for c = 1, 10 do
      ...
        if a == 1 and b == 2 and c == 3 ... y == 4 and z == 5 then
          print("test")
        end
      ...
    end
  end
end

最佳答案

你可以用Lua编写你自己的迭代器,它可以让你表达这一点。 manual解释了如何调用它们。

例如,这里有一个 grid 迭代器生成器,可让您按字典顺序迭代“网格”:

-- Lua 5.1's "unpack" was renamed to "table.unpack" in Lua 5.2
table.unpack = table.unpack or unpack

function iterator(t, i)
    local n = i + 1
    local r = {}
    local p = 1
    for k = #t, 1, -1 do
        p = p * t[k]

        -- or, "c = i % t[k] // 1" in Lua 5.3
        local c = i % t[k]
        r[k] = 1 + c

        -- or, "i = i // t[k]" in Lua 5.3
        i = (i - c) // t[k]
    end
    if n > p then
        return nil, table.unpack(r)
    end
    return n, table.unpack(r)
end

function grid(...)
    return iterator, {...}, 0
end

你可以像这样使用它

for i, a, b, c in grid(10, 10, 10) do
    if a ^ 2 + b ^ 2 == c ^ 2 then
        print(string.format("%d^2 + %d^2 = %d^2", a, b, c))
    end
end

--> 3^2 + 4^2 = 5^2
--> 4^2 + 3^2 = 5^2
--> 6^2 + 8^2 = 10^2
--> 8^2 + 6^2 = 10^2

因为 Lua 本身提供了一个简单的 for i = 1, 10 do 循环,所以循环计数将比使用这样的迭代器快得多。然而,这造成的差异会减少每次迭代发生的更多工作。如果您在每次迭代中只执行几行简单的代码,则重复调用迭代器(它还构造表!)的性能开销将远远超过循环中实际完成的工作。但如果您只迭代几次,并且每次迭代都做了很多工作,那么它最终就不重要了。

关于lua - 如何使大嵌套 'for loops'循环更紧凑?有什么解决办法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57440941/

相关文章:

c++ - Lua,游戏状态和游戏循环

lua - 如何使用 Clink lua api?

redis - Geo.Lua函数GEOMETRYFILTER和Redis

c++ - 使用 Lua 在 C++ 中创建定时器

lua - 如何向 lua 程序传递和读取参数?

lua - io.popen() :lines() ignores first non-empty line

lua - 元表错误

regex - 纯 Lua 中功能齐全的正则表达式库

encryption - lua aes加密

android - AndroLua有办法处理资源文件中的lua脚本吗?