我如何遍历 Roblox.lua 中 table 中的每个其他元素

How could i loop through every OTHER element in a table in Roblox.lua

我正在尝试遍历 table 中的 每个其他 元素,但我找不到方法。

感谢任何帮助。

谢谢。

也许试试这个

local count = 0
for i = 1 , #table/2 do 
table[count + i].value = value
count = count + 1
end

往下加数

这取决于您使用的 table 类型。如果你有一个类似数组的 table,你可以使用一个简单的 for 循环:

local t = {1, 2, 3, 4, 5, 6, 7, 8}

-- start at 1, loop until i > the length of t, increment i by 2 every loop
for i = 1, #t, 2 do
    local val = t[i]
    print(val) -- will print out : 1, 3, 5, 7
end

但是如果您有类似字典的 table,您将需要一些东西来跟踪要跳过的键。您可以使用一个简单的布尔值来跟踪,但请注意,没有保证类似字典的顺序 table.

local t = {
    a = 1,
    b = 2,
    c = 3,
    d = 4,
}

local shouldPrint = true
for k, v in pairs(t) do
    -- only print the value when it's true
    if shouldPrint then
        print(k, v) -- will probably print    a, 1   and   c, 3
    end

    -- swap shouldPrint's value every loop
    shouldPrint = !shouldPrint
end