Lua Semicolon公约

问题描述 投票:19回答:2

我想知道在Lua中是否存在使用分号的一般惯例,如果是,我应该在哪里/为什么使用它们?我来自编程背景,因此用分号结束语句似乎直观正确。然而,当它普遍接受其他编程语言中的分号结束时,我担心为什么它们是"optional"。也许有一些好处?

例如:从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社区普遍接受,还是有其他方式被大多数人所青睐?或者它是否像我个人的偏好一样简单?

lua conventions
2个回答
26
投票

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')

-1
投票

因为在一条线上有多个东西,例如:

c=5
a=1+c
print(a) -- 6

可缩短为:

c=5; a=1+c; print(a) -- 6

另外值得注意的是,如果你已经习惯了Javascript,或类似的东西,你必须用分号(;)结束一行,并且你特别习惯写这个,那么这意味着你不会有删除那个分号(;),相信我,我也习惯了Javascript,我真的,真的忘了你每次写一个新行都不需要分号(;)!

© www.soinside.com 2019 - 2024. All rights reserved.