如何在 Lua 中跳过一部分代码?

这是我的第一个Lua项目,我遇到了跳过代码的问题。我希望在“Cool”部分之后停止代码。因此,如果我输入good,它会回答cool,我想停止代码的其余部分,因为在那之后下一个问题就不相关了。

工作原理: 代码说:你好 你说:任何事情 代码说:你好吗? 你说:好 在你说好之后它会说"cool"。 如果你说其他任何东西,它会问:“为什么?”例如,你说:坏 代码说:“一切都会好起来的。” 我希望在“cool”之后停止,跳过代码的进一步部分。

os.execute(" cls ")
print("Hello")
    odp = io.read()
        if odp == string then
        end
        tof = true or false

print("How are you?")
    odp2 = io.read()
        if odp2 == "good" then print("Cool") tof = true
            else print("Why?") tof = false
            if tof == true then os.execute(" pause ")
        end
            end
            
    if tof == true then
        odp3 = io.read()
            if odp3 ~= math then print("It will be alright")
                print("Okay, I have to go see you.")
            end
    end
os.execute(" pause ")
点赞
用户2226988
用户2226988

当您编译代码时,它将成为一个函数的主体。默认退出函数的方式是使用 return 语句。一个函数可以有零个或多个 return 语句。

但是,如果您想退出程序,您可以调用 os.exit()

2014-05-30 23:34:46
用户3266171
用户3266171

你只需要改变嵌套的“if”语句。你只需要将代码的剩余部分放在“if”语句的“else”部分,像这样:

os.execute(" cls ")
print("Hello")
odp = io.read()
if odp == string then
end
tof = true or false

print("How are you?")
odp2 = io.read()
if odp2 == "good" then
    print("Cool")
    tof = true
else
    print("Why?")
    tof = false
    if tof == true then
        os.execute(" pause ")
    end

    odp3 = io.read()
    if odp3 ~= math then
        print("It will be alright")
        print("Okay, I have to go see you.")
    end
    os.execute(" pause ")
end

这样,只在它要求并且用户没有回答“好”的“你好吗?”问题后才从用户获取输入。

请注意,我重新缩进了代码,但它仍然是相同的代码,相同的顺序。我只是让它看起来更标准,更容易直观地看到程序的结构。

2014-06-08 03:28:47