Lua中的if else和while语句有什么限制?

我正在尝试为游戏中基于Lua的计算机制作程序。然而,当它运行时表现很奇怪。

--Tablet

    oldpullEvent = os.pullEvent
    os.pullEvent = os.pullEventRaw
    while true do
        term.clear()
        term.setTextColor( colors.white )
        term.setCursorPos(1, 1)
        print("Please Enter Password:")
        input = read("*")
        incorrect = 0
        while incorrect < 3 do
            if input == "qwerty" then
                print("Password Correct, Unlocking")

            else
                if incorrect < 3 then
                    incorrect = incorrect + 1
                    print("Password incorrect")
                    print(3 - incorrect, " tries remaining")
                else
                    print(3 - incorrect, "tries remaining, locking phone for 1m")
                    local num = 0
                    while num < 60 do
                        if num < 60 then
                            term.clear()
                            term.setTextColor( colors.red )
                            term.setCursorPos(1, 1)
                            num = num + 1
                            print(60 - num, "s remaining")
                            sleep(1)
                        else
                            incorrect = 0
                        end
                    end
                end
            end
        end
    end
    os.pullEvent = oldpullEvent

当它运行时,它开始显示“Please enter password:”,输入正确密码“qwerty”后,它会无限循环地重复显示“Password Correct, Unlocking”。当我输入错误密码时,它不运行else语句中的代码,而只是返回输入密码的屏幕。没有错误代码或崩溃。是否有了解Lua的人知道我是否在while / if / elseif函数中写错了,或是否有解决方法。

谢谢!

点赞
用户1442917
用户1442917

你输入正确密码后没有将 incorrect 值重置。你需要使用 break 来中止循环或将 incorrect 设置为 3 或更大的值。

2015-12-12 23:12:46
用户4021682
用户4021682

当输入正确密码时,该循环没有被告知停止。在输入正确密码后,应该在print("Password Correct, Unlocking")之后添加break

这是因为input在循环外部,更好的方法是像下面这样:

local incorrect = 0
while true do
    term.clear()
    term.setTextColor( colors.white )
    term.setCursorPos(1, 1)
    print("Please Enter Password:")
    local input = read("*")

    if input == "qwerty" then
        print("Password Correct, Unlocking")
        break
    else
        if incorrect < 2 then
            incorrect = incorrect + 1
            print("Password incorrect")
            print(3 - incorrect, " tries remaining")
            sleep(1) -- let them read the print.
        else
            print("out of attempts, locking phone for 1m")
            for i = 10, 1, -1 do
                term.clear()
                term.setTextColor( colors.red )
                term.setCursorPos(1, 1)
                print(i, "s remaining")
                sleep(1)
            end
            incorrect = 0
        end
    end
end

上面的代码将允许用户尝试3次密码,如果都用完了,他们将被锁定60秒并获得另外3次尝试机会。直到输入正确密码为止,这个过程会不断重复。

我已经删除了内部的while循环,因为它不是必需的。 incorrect已被设为local并移到while循环外部,因此每次用户输入密码时不会被重置。

read("*")已移动到while循环内部,以便每次提示用户输入密码,而不是询问一次然后无限循环。

该代码已经经过测试,似乎没有任何问题。

如果有任何代码不清楚的地方,请随时问我。

2016-01-10 06:44:21