2016-04-28 92 views
-1

這是我第一次編寫的代碼,因爲我剛剛開始,所以我不確定是否有任何內容正確縮進。但我想要一種能夠重複文本的方式,但我不知道如何去做。如何在Lua中重複代碼?

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

類型'如何重複代碼lua'到谷歌 – zeromus

+0

如果您縮進代碼正確它會顯示有一個額外的'end'之前' until'。關於重複代碼,請將要重複的字符串放入函數中並根據需要調用它們。在Lua中搜索「多重字符串」,它可以很方便。 –

回答

1

要多次執行一段代碼,您可以使用所謂的控制結構。

while EXP doend

repeatuntil EXP

for EXP doend

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