local i = 0 if(i==1) then print(1) --> will not print end注意,if後面需要接著一個then,
事實上,很多程式語言也是需要那個then,
只是它們可以接受不寫,但在Lua一定要
多一個else呢:
local i = 0 if(i==1) then print(1) --> will not print else print(0) --> will print end
二層if呢:
local i = 0 if(i==1) then print(1) --> will not print elseif (i==0) then print(0) --> will print else print(123) --> will not print end
elseif可以寫成 else if嗎?
local i = 0 if(i==1) then print(1) --> will not print else if (i==0) then print(0) --> will print else print(123) --> will not print end end結果是一樣的,怎麼好像多了一個end而已,why??
再多一層:
local i = 0 if(i==1) then print(1) --> will not print elseif (i==2) then print(2) --> will not print elseif (i==0) then print(0)--> will print else print(123) --> will not print end
一樣把elseif 改成 else if看看:
local i = 0 if(i==1) then print(1) --> will not print else if (i==2) then print(2) --> will not print else if (i==0) then print(0)--> will print else print(123) --> will not print end end end哇,怎麼後面要3個end啊?
因為else表示是前面所有判斷式都不成立時就會進來它裡面,
不管前面有幾個elseif,
elseif表示要先判斷成不成立再執行,
如果是else if,那表示已經進到else了,只是我們再多了一個if的去判斷,
將上面的程式增加二行:
local i = 0 if(i==1) then print(1) --> will not print else print("enter 1") --> will print if (i==2) then print(2) --> will not print else print("enter 2") --> will print if (i==0) then print(0)--> will print else print(123) --> will not print end end end如果還不夠清楚,程式不改,我們重新排版看看:
local i = 0 if(i==1) then print(1) --> will not print else print("enter 1") --> will print if (i==2) then print(2) --> will not print else print("enter 2") --> will print if (i==0) then print(0)--> will print else print(123) --> will not print end end end所以,標準的用法就是
if(condition 1) then --do some things elseif (condition 2) then --do some things . . elseif (condition n) then --do some things else --do some things end
沒有留言:
張貼留言