Search code examples
luaconventions

Lua Semicolon Conventions


I was wondering if there is a general convention for the usage of semicolons in Lua, and if so, where/why should I use them? I come from a programming background, so ending statements with a semicolon seems intuitively correct. However I was concerned as to why they are "optional" when its generally accepted that semicolons end statements in other programming languages. Perhaps there is some benefit?

For example: From the lua programming guide, these are all acceptable, equivalent, and syntactically accurate:

a = 1
b = a*2

a = 1;
b = a*2;

a = 1 ; b = a*2

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

The author also mentions: Usually, I use semicolons only to separate two or more statements written in the same line, but this is just a convention.

Is this generally accepted by the Lua community, or is there another way that is preferred by most? Or is it as simple as my personal preference?


Solution

  • Semi-colons in Lua are generally only required when writing multiple statements on a line.

    So for example:

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

    Alternatively written as:

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

    Off the top of my head, I can't remember any other time in Lua where I had to use a semi-colon.

    Edit: looking in the lua 5.2 reference I see one other common place where you'd need to use semi-colons to avoid ambiguity - where you have a simple statement followed by a function call or parens to group a compound statement. here is the manual example located 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')