你如何在 Lua 中检查 row/Column 明智的迭代

How do you check row/Column wise iteration in Lua

我一直在写代码来在 Column wise 迭代中执行循环,这让我一直很困惑,我无法区分 Column 和 Row Wise Iteration。

我在下面编写了这些代码来执行按列迭代,但我不确定它是否以正确的方式执行。还可以帮助我理解 Row/Column 迭代

的更多示例
r = {}

for x = 1, 5 do
    table.insert(r, {})
end

for x = 1, 5 do
    for y = 1, 5 do
        table.insert(r[y], y)
        -- table.insert(r[x], 'A')
    end
end

for x = 1, 5 do
    for y = 1, 5 do
        io.write(r[x][y], ' : ')        
        -- io.write(r[y][x], ' :: ')
    end
    print()
end

输出:

1 : 1 : 1 : 1 : 1 : 
2 : 2 : 2 : 2 : 2 :
3 : 3 : 3 : 3 : 3 :
4 : 4 : 4 : 4 : 4 :
5 : 5 : 5 : 5 : 5 :

下面这个是针对行智能迭代的。我觉得!

L = {}

for i = 1, 5 do
    table.insert(L, {})
    for j = 1, 5 do
        L[i][j] = " # "
    end
end

for i = 1, 5 do
    for j = 1, 5 do
        io.write(L[i][j])
    end
    print()
end

输出:

 #  #  #  #  # 
 #  #  #  #  #
 #  #  #  #  #
 #  #  #  #  #
 #  #  #  #  # 

当更形象化并关注@LMD 时,您会看到更多。
我有一些时间所以可以随意玩...

Lua 5.4.4  Copyright (C) 1994-2022 Lua.org, PUC-Rio
> L = require('rowcol')
> L:ij()
    A   B   C   D   E
    F   G   H   I   J
    K   L   M   N   O
    P   Q   R   S   T
    U   V   W   X   Y
> L:ji()
    A   F   K   P   U
    B   G   L   Q   V
    C   H   M   R   W
    D   I   N   S   X
    E   J   O   T   Y
> io.open('rowcol.lua'):read('a')
-- rowcol.lua

local L = setmetatable({ -- Data Part
[0x1] = {[0x1] = '', [0x2] = '', [0x3] = '', [0x4] = '', [0x5] = ''},
[0x2] = {[0x1] = '', [0x2] = '', [0x3] = '', [0x4] = '', [0x5] = ''},
[0x3] = {[0x1] = '', [0x2] = '', [0x3] = '', [0x4] = '', [0x5] = ''},
[0x4] = {[0x1] = '', [0x2] = '', [0x3] = '', [0x4] = '', [0x5] = ''},
[0x5] = {[0x1] = '', [0x2] = '', [0x3] = '', [0x4] = '', [0x5] = ''}
},{__index = { -- Methods Part
ij = function(self, i, ie, j, je)
for i = i or 0x1, ie or 0x5 do
    for j = j or 0x1, je or 0x5 do
        io.write('\t', self[i][j])
    end
    print()
end
end,
ji = function(self, i, ie, j, je)
for i = i or 0x1, ie or 0x5 do
    for j = j or 0x1, je or 0x5 do
        io.write('\t', self[j][i])
    end
    print()
end
end
}
})

return L

两种方法都可以处理 for 范围参数...

> L:ji(5,5)
    E   J   O   T   Y
> L:ij(5,5)
    U   V   W   X   Y
> L:ij(5,5,5,5)
    Y
> L:ij(3,5,3,5)
    M   N   O
    R   S   T
    W   X   Y
> L:ji(3,5,3,5)
    M   R   W
    N   S   X
    O   T   Y
> L:ji(1,5,1,5)
    A   F   K   P   U
    B   G   L   Q   V
    C   H   M   R   W
    D   I   N   S   X
    E   J   O   T   Y
> L:ji(1,5,1,4)
    A   F   K   P
    B   G   L   Q
    C   H   M   R
    D   I   N   S
    E   J   O   T
> L:ji(1,5,1,3)
    A   F   K
    B   G   L
    C   H   M
    D   I   N
    E   J   O