Latest web development tutorials

Lua basic grammar

Lua learning is very simple, we can first create a Lua program!

First Lua program

Interactive Programming

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

Lua interactive programming mode by command or lua lua -i to enable it:

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

At the command line, enter the following command:

> print("Hello World!")

Then we press the Enter key, the output results are as follows:

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

Scripted Programming

We can keep the Lua code to a lua files ending, and execute the script programming mode is called, as we have the following code is stored in a script file named hello.lua in:

print("Hello World!")

Use lua executive script above, the output is:

$ lua test.lua
Hello World!

We can also change the code to the following form to execute the script (add at the beginning: # / usr / local / bin / lua!):


print("Hello World!")

The above code, we specify the Lua interpreter / usr / local / bin directory. With the # mark interpreter ignores it. Next we add executable permission to the script, and execute:

Hello World!


Single-line comments

Minus two is a single line comment:


Multi-line comments



Lua represents character is used to define a variable, user-defined function to get other items. Identifier with a letter from A to Z or a to z or an underscore _ after adding zero or more letters, underscores, numbers (0-9).

Best not to use underscores to increase letters identifier, because Lua reserved words is the same.

Lua is not allowed to use special characters such as @, $, and% defined identifier. Lua is a case-sensitive programming language. Thus Lua in W3c with w3c are two different identifiers. Here are some correct identifier:

mohd         zara      abc     move_name    a_123
myname50     _temp     j       a23b9        retVal

Key words

Following is a list of reserved keywords Lua. Keywords can not be reserved as a constant or variable or other user-defined identifier:

and break do else
elseif end false for
function if in local
nil not or repeat
return then true until

The general convention, begins with an underscore the connection string of uppercase letters the names (such as _VERSION) is reserved for internal Lua global variables.

Global Variables

By default, variables are always considered to be global.

Global variables need not be declared, after assignment to a variable created this global variable to access a non-initialized global variables are not wrong, just the results obtained are: nil.

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

If you want to delete a global variable, simply assign values ​​to variables is nil.

b = nil
print(b)      --> nil

So that the variable b as if never been used before. In other words, if and only if a variable is not equal to nil, this variable that is present.