Lua basic syntax

Lua is very easy to learn and we can create our first Lua program!

The first Lua program

Interactive programming

Lua provides an interactive programming mode. We can enter the program into the command line and see the effects immediately.

Lua interactive programming mode can be enabled by command lua -i or lua:

$ lua -i 
$ Lua 5.3.0  Copyright (C) 1994-2015, PUC-Rio

In the command line, enter the following command:

> print("Hello World!")

Then we press return Press the car key, the output result is as follows:

> print("Hello World!")
Hello World!

Scripted programming

We can save the Lua program code to a file ending with lua and execute it. This mode is called scripted Programming, for example, we store the following code in a script file named hello.lua:

print("Hello World!")

Use the lua name to execute the above script, and the output result is:

$ lua test.lua
Hello World!

We can also modify the code Execute the script in the following form (add: #!/usr/local/bin/lua at the beginning):


print("Hello World!")

In the above code, we specify the Lua interpreter /usr/local/bin directory. Marking it with a # sign will cause the interpreter to ignore it. Next we add executable permissions to the script and execute it:

Hello World!


Single-line comments

Two minus signs are single-line comments:


Multi-line comments



Lua identifier is used to define a variable, and the function obtains other user-defined items. The identifier starts with a letter A to Z or a to z or an underscore _ followed by 0 or more letters, underscores, and numbers (0 to 9).

It is best not to use underscores and capital letters as identifiers, because Lua's reserved words are like this too.

Lua does not allow the use of special characters such as @, $, and % to define identifiers. Lua is a case-sensitive programming language. Therefore, W3c and w3c are two different identifiers in Lua. Some of the correct identifiers are listed below:

mohd         zara      abc     move_name    a_123
myname50     _temp     j       a23b9        retVal


The following are Lua’s reserved keywords. Reserved keywords cannot be used as constants or variables or other user-defined identifiers:

function ifinlocal

General convention, names starting with an underscore followed by a string of uppercase letters (such as _VERSION) are reserved for Lua internal global variables.

Global variables

By default, variables are always considered global.

Global variables do not need to be declared. After assigning a value to a variable, the global variable is created. There is no error when accessing an uninitialized global variable, but the result is: nil.

> print(b)
> b=10
> print(b)

If you want to delete a global variable, just assign the variable to nil.

b = nil
print(b)      --> nil

This way variable b is as if it has never been used. In other words, a variable exists if and only if it is not equal to nil.