lua中ipairs循环始终只返回一个值?

快速编辑:_G.i是我设置为创建24小时时间框架的1-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}

所以我正在尝试让这个循环与我创建的昼夜周期一起工作。我希望循环不断检查现在的时间,并根据我设置的一些参数将时间打印到控制台。

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

由于某种原因,这只会在控制台中打印出白天,即使我已经循环了它。时间与 day-night 脚本中的时间相同。我也会在这里将其发布。

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

while true do
    changeTime()
end

如果这篇文章看起来很混乱,或者代码很混乱,我很抱歉,我对这两个都很新。一直在试图自己解决这个问题,最初我对 ipairs 循环完全不了解,但我设法使它与日夜周期一起工作,而不是使用无限等待(1)循环。

点赞
用户6614127
用户6614127

您的问题在于这一行:

if v > 20 and v < 6 then

v 永远不可能同时大于 20 和小于 6。您需要使用 or 逻辑运算符。

此外,我不确定为什么您在使用全局变量 i 来保存从 1 到 24 的数字列表?您可以通过 范围 for 循环 来达到相同的效果。如果您要检查下面代码设置的当前时间,则应将时间值存储在全局变量中。像这样:

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() 函数之后运行,但这并不一定是正确的。

2017-06-14 15:13:59