Lua Semicolon公约

MrH*_*hma 22 lua conventions

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

例如:从lua编程指南中,这些都是可接受的,等效的,语法准确的:

a = 1
b = a*2

a = 1;
b = a*2;

a = 1 ; b = a*2

a = 1   b = a*2    -- ugly, but valid
Run Code Online (Sandbox Code Playgroud)

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

这是否被Lua社区普遍接受,还是有其他方式被大多数人所青睐?或者它是否像我个人的偏好一样简单?

Mik*_*ran 28

Lua中的分号通常仅在一行上写多个语句时才需要.

例如:

local a,b=1,2; print(a+b)
Run Code Online (Sandbox Code Playgroud)

或者写成:

local a,b=1,2
print(a+b)
Run Code Online (Sandbox Code Playgroud)

在我的头顶,我记不起在Lua的任何其他时间,我不得不使用分号.

编辑:看在LUA 5.2参考我看到你需要使用分号以避免歧义另一个共同的地方-那就是你有一个简单的语句,后跟函数调用或括号以组复合语句.这是位于此处的手动示例:

--[[ 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')
Run Code Online (Sandbox Code Playgroud)

  • 实际上,`本地a,b = 1,2打印(a + b)`是有效的Lua并且做你想要的.您只需要分号就可以防止出现歧义.顺便说一句,空间也是如此.所以这也是'print(1)print(2)` (17认同)