2013-05-31 29 views
12

我想知道在Lua中是否有一個使用分號的通用約定,如果是,我應該在哪裏/爲什麼要使用它們?我來自一個編程背景,所以用分號結尾的陳述似乎直觀地正確。但是我擔心它爲什麼是"optional",當它通常接受分號在其他編程語言中結束語句時。也許有一些好處?Lua分號約定

例如:從lua programming guide,這些都是可以接受的,等價的,語法準確:

a = 1 
b = a*2 

a = 1; 
b = a*2; 

a = 1 ; b = a*2 

a = 1 b = a*2 -- ugly, but valid 

筆者也提到:Usually, I use semicolons only to separate two or more statements written in the same line, but this is just a convention.

這是一般由Lua的社會所接受,或者是還有另一種更受大多數人歡迎的方式?還是像我個人的偏好一樣簡單?

回答

19

Lua中的分號一般只需要在一條線上寫多條語句。

因此,例如:

local a,b=1,2; print(a+b) 

或者寫爲:

local a,b=1,2 
print(a+b) 

關閉我的頭頂,我不記得在Lua任何其他時候,我不得不使用一個分號。

編輯:尋找在lua 5.2參考我看到一個其他常見的地方,你需要使用分號避免歧義 - 你有一個簡單的語句後跟一個函數調用或parens來組合一個複合語句。這裏是手動示例位於here

Function calls and assignments can start with an open parenthesis. This 
possibility leads to an ambiguity in the Lua grammar. Consider the 
following fragment: 

a = b + c 
(print or io.write)('done') 

The grammar could see it in two ways: 

a = b + c(print or io.write)('done') 

a = b + c; (print or io.write)('done') 
+0

非常豐富。謝謝! – MrHappyAsthma

+12

實際上,'本地a,b = 1,2打印(a + b)'是有效的Lua,並且做你期望的。你只需要分號來防止模糊。順便一提。所以這也適用於'print(1)print(2)' – dualed