如何在Lua中重复代码?

时间:2016-04-28 09:32:02

标签: lua repeat

这是我的第一个编写的代码,因为我刚刚开始,所以我不确定是否有任何正确的缩进。但我想要一种能够重复文本的方法,但我不知道该怎么做。

 print("Hey there. I want to play a game.")
    print("Tell me your name")
    print("Type your name")
    name = io.read()
    print("Oh, what a nice name. I was gonna call my kid the same")
    print("Ok. So as you can see, there are no ligths here. It's all dark. You have three choices. Go west, go east, go north.")
    print("To go North, type 'n'. To go East, type 'e'. to go West, type 'w'.")
    repeat
    direction = io.read() 
if direction == "w" then
    print(" You see a light switch.")
    print(" type 'switch'to turn on the switch.")
    print(" type 'go_back' to turn around")

    best = io.read() -- This is where i want it to be able to repeat
    end
    if best == "switch" then
            print(" The light goes on.")
                print(" As the light glows stronger, you see someone standing infront of you")
                print("Before you know it, he slits your throat. Want to try again?")
                print("Press enter to try again")
                try_again = io.read()
    best = io.read()


        direction = io.read()

elseif best == "switch" then
        print(" The light goes on.")
                print(" As the light glows stronger, you see someone standing infront of you")
                print("Before you know it, he slits your throat. Want to try again?")
                print("Press enter to try again")
                try_again = io.read()
                end
                end
                until best ~= "go_back" -- to repeat the code up above

1 个答案:

答案 0 :(得分:1)

要多次执行一大块代码,您可以使用所谓的控制结构。

while exp do阻止end

repeat阻止until exp

for exp do阻止end

goto标签声明。

请阅读有关如何使用它们的参考资料。 http://www.lua.org/manual/5.3/manual.html#3.3.4

您可以将代码块放入其中一个控制语句中,也可以将其放入一个函数中,然后将其放入其中一个控制语句中。或者您只需手动多次调用该功能。

您打算重复的代码最好放在函数中。

我建议你做简单的Lua教程,并阅读Lua语言参考手册和Lua编程。两者都可以在www.lua.org上找到。

缩进阅读http://lua-users.org/wiki/LuaStyleGuide