如何从 lua 中的关键位置开始迭代表?

Sil*_*olf 3 lua loops lua-table

我正在尝试迭代表,但使用键从表中的位置开始。

list = {
  "one",
  "two",
  "four",
  "five",
  "six"
}

for k = 3, v in pairs(list) do
  print("Key:" .. k .. " " .. "Value:" .. v)
end
Run Code Online (Sandbox Code Playgroud)

Compilation error on line 10: ...\ZeroBraneStudio\myprograms\untitled.lua:10: 'do' expected near 'in'

Oka*_*Oka 6

对于类似数组的表(带有序列),您可以使用数字for,上限是表的长度。

local list = {
    "one",
    "two",
    "four",
    "five",
    "six"
}

for i = 3, #list do
    print(i, list[i])
end
Run Code Online (Sandbox Code Playgroud)
3   four
4   five
5   six
Run Code Online (Sandbox Code Playgroud)

请注意,从某个键(索引)开始通常仅在给定一个类似数组的表的情况下才有意义 - 这list就是您的表。表中的键值对就/next而言没有稳定的顺序pairs(注意ipairs是针对序列进行操作)。

如果类似关联数组的表中的任意键遵循特定的生成顺序(即它们是确定性的),则可以以稳定的方式迭代它们,但这是一个特定的用例。


您还可以编写一个类似于形式的函数ipairs- 返回泛型使用的迭代器函数(以及初始状态控制) ,但从给定索引开始。for

这是一个粗略的示例,其中迭代器返回索引,即要分配给循环变量的值。

local function ipairsfrom(tab, n)
    return function (t, i)
        i = i + 1
        return t[i] ~= nil and i or nil, t[i]
    end, tab, n and n - 1 or 0
end

local list = { 'a', 'b', 'c', 'd', 'e' }

for index, value in ipairsfrom(list, 3) do
    print(index, value)
end
Run Code Online (Sandbox Code Playgroud)
3   c
4   d
5   e
Run Code Online (Sandbox Code Playgroud)

很多方法可以编写这样的迭代器和创建它的函数。例如,返回值,索引可能是首选,因为该通常更有趣,并且允许我们省略第二个变量(而不是使用for _, value in)。

local function ipairsfrom(t, i)
    i = i and i - 1 or 0
    return function ()
        i = i + 1
        return t[i], i
    end
end

for value, index in ipairsfrom({ 'a', 'b', 'c' }, 2) do
    print(index, value)
end
Run Code Online (Sandbox Code Playgroud)
2   b
3   c
Run Code Online (Sandbox Code Playgroud)