ipairs 循环总是只返回 lua 中的一个值?

ipairs loop always returning just one of the values in lua?

快速编辑:_G.i 是我设置的 1 - 24 table 创建 24 小时时间范围。它全局存储在一个三级脚本中并像这样实现:

_G.i = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}

所以我试图让这个循环与我创建的 day/night 循环一起工作。我希望循环不断检查现在几点,并根据我设置的一些参数将该时间打印到控制台。

light = script.Parent.lightPart.lightCone
timeofday = ""
wait(1)

function checkTime()
    for i, v in ipairs(_G.i) do
        wait(1)
        print(v)
        print(timeofday)
        if v > 20 and v < 6 then
            timeofday = "night"
        else
            timeofday = "day"
        end 
    end
end  

while true do
    checkTime()
    wait(1)
end

出于某种原因,这只是控制台中的打印日,即使我已经正确循环了它。时间与昼夜脚本中的时间相同。我也会 post 在这里。

function changeTime()
    for i, v in ipairs(_G.i) do
        game.Lighting:SetMinutesAfterMidnight(v * 60)
        wait(1)
    end
end

while true do
    changeTime()
end

抱歉,如果此 post 草率或代码草率,我对两者都不熟悉。一直在尝试自己解决这个问题,并且在这方面做得很好,最初我不知道 ipairs 循环是什么,但我设法让它在昼夜循环中工作,而不是无限等待(1)循环。

您的问题所在行:

if v > 20 and v < 6 then

v 永远不能 两者 大于 20 且小于 6。您需要 or 逻辑运算符。

除此之外,我不确定您为什么使用全局 i 来保存数字 1 到 24 的列表?您可以使用 ranging for loop 实现相同的效果。此外,如果您试图检查您的较低代码设置的当前时间,那么您应该将时间值存储在全局变量中。像这样:

light = script.Parent.lightPart.lightCone
current_time = 0

function checkTime()
    print(current_time)
    if current_time > 20 or current_time < 6 then
        timeofday = "night"
    else
        timeofday = "day"
    end 
    print(timeofday)
end  

while true do
    checkTime()
    wait(0.1)
end


function changeTime()
    for v = 1, 24 do
        game.Lighting:SetMinutesAfterMidnight(v * 60)
        current_time = v
    end
end

while true do
    changeTime()
    wait(1)
end

你这样做的问题是你假设 checkTime() 函数总是 运行 在 changeTime() 函数之后,但事实并非如此。