Lua - 如何避免重复执行函数的错误?

我正在制作一个“不可能”的游戏,你基本上会被问一堆鬼畜问题。

第一次运行脚本时,一切都正常。如果用户想再玩一次并输入“y”,它将重新运行mainScript函数。然而,在第二次完成脚本后,脚本会自动重新运行mainScript,而不考虑用户输入。我可能犯了一个简单的错误,我不确定。这是脚本:(抱歉,我知道它有点长)

点赞
用户869951
用户869951

你应该将“startover”逻辑提取到循环中,这样会更好。然后你会注意到在checkWin的if块中有公共代码,也要提取出来:

function checkWin()
    if mainScript() then
        print("You won!")
    else
        print("You lose!")
    end

    print("Points: " .. points .. "\n")

    if not checkForReplay() then
        return false
    else
        Questions = {}
        loadTable()
        return true
    end
end

while true do
    if not checkWin() then
        break
    end
end

还要注意最好让脚本返回而不是调用os.exit()(假设exit()是你代码中的函数--参见例如 How to terminate Lua script?):

function checkWin()
    if mainScript() then
        print("You won!")
    else
        print("You lose!")
    end

    print("Points: " .. points .. "\n")

    return checkForReplay()
end

local playAgain = checkWin()
while playAgain do
    Questions = {}
    loadTable()
    playAgain = checkWin()
end
2014-02-16 18:03:33