Comments in Lua Programming

LuaServer Side ProgrammingProgramming

Comments are a set of commands that are ignored by the compiler. They are used in a scenario where you want to attach a note to your code or a section of code so that when you visit it later, you can recall it easily. The comment statements are usually ignored during the execution of the program.

There are two types of comments in Lua −

  • Single-line comments

  • Multi-line comments

Multi-line comments are also known as block comments in Lua.

Single-Line Comment

A single-line comment in Lua starts with a double hyphen (--) and runs until the end of the line.

Syntax

-- this is a comment

Let’s consider an example where we write multiple single-line comments and then deliberately write invalid codes inside them and see what happens.

Example

Consider the example shown below −

-- z = 10
print(z)

x = 11
-- print(x)

-- ans

Notice that on the last line, we are declaring a global variable without an assignment which is illegal according to Lua, but since we are doing it inside a comment, it will be ignored by Lua.

Output

nil

Multi-Line Comments

Multi-Line comments, also known as block comments in Lua, make use of a special syntax.

Syntax

--[[
this
is
a
comment
--]]

Let’s create an example where we write two block comments, one of them is a valid comment and the other one is not a valid block comment.

Example

Consider the example shown below −

--[[
print(110)
--]]

---[[
print("str")
--]]

In the above example, the second section of code looks like a valid block level comment, but if we look closely, then we will notice that it isn’t.

Output

str
raja
Published on 01-Dec-2021 10:10:29
Advertisements