A Comprehensive Guide to Lua Syntax

In this article, we will explore Lua syntax with examples, including its control structures, functions, and modules.

Like most programming languages, Lua programs are composed of statements that execute sequentially.

Each statement in Lua ends with a semicolon ; , although this is optional for the last statement in a block.

Now, we will take a look at the basic structure of a Lua program to help you understand the fundamental building blocks of the Lua programming language.



Lua Tokens

In Lua, tokens are the smallest individual units of a program that are meaningful to the language. There are several types of tokens in Lua, such as:

TokensOverview
KeywordsReserved words in Lua such as “if”, “else”, “while”, and “end”.
IdentifiersNames given to variables, functions, and other entities by the user.
OperatorsLua uses these symbols for arithmetic, comparison, and other operations e.g ‘+’, ‘-’, ‘*’, ‘/’, ‘==’, etc.
DelimitersThese are symbols used to group or separate code in Lua. E.g “{“, “}”, “(“, “)”, “[“, “]”, “,” and “.” .
LiteralsIn Lua, literal values are strings, numbers, and booleans written directly into a program. Examples of literals in Lua include “Hello World”, 36, and true.

Lua Syntax – Comments

In Lua, comments can be used to add notes and explanations to the code without affecting its execution. During execution, they are ignored by the interpreter.

In Lua, there are two kinds of comments:

CommentsOverview
Single-line commentsThese begin with a double hyphen () and continue to the end of the line.
Multi-line commentsThey begin with a double hyphen followed by an opening square bracket (–[[) and end with a closing square bracket (–]]).

Lua Identifiers

An identifier in Lua refers to a variable, function, table, or other data structure. Lua programs use identifiers to reference and manipulate data.

The rules for creating identifiers in Lua are as follows:

  • Letters, digits, and underscores can be used within identifiers.
  • An identifier must begin with a letter or underscore.
  • Identifiers in Lua are case sensitive. For example, “x” and “X” are different identifiers.
  • There are several reserved keywords in Lua that cannot be used as identifiers, such as “if“, “else“, “while“, and “function“.
  • Symbols like @, $, and % are not allowed in Lua identifiers.

In Lua, valid identifiers include “newVar”, “_counter”, “zb36”, and “my_score”.


Lua Keywords

There are a number of reserved words in Lua that have a special meaning and cannot be used as identifiers.

Lua’s keywords define the structure and flow of the program, and they are essential to its operation.

Note: It is important to note that these keywords are case-sensitive, which means that using them with different cases will result in an error.

Here are the keywords in Lua:

KeywordsOverview
andA logical operator in Lua that returns true if both of its operands are true, otherwise false.
breakA keyword that is used to exit a loop, such as a for or while loop, prematurely.
doA keyword that is used to start a block of code in Lua, often used in conjunction with the end keyword.
elseA keyword used to specify the alternative block of code to execute if the if condition is not true.
elseifA keyword used to specify a new condition to test if the preceding if statement is not true.
endA keyword used to mark the end of a block of code, such as an if or for loop.
falseA boolean value in Lua that represents false.
forA keyword used to create a loop that iterates over a range of values.
functionA keyword used to define a function in Lua.
ifA keyword used to start a conditional statement in Lua.
inA keyword used to specify the range of values to iterate over in a for loop.
localA keyword used to define a local variable in Lua.
nilA value in Lua that represents the absence of a value.
notA logical operator in Lua that returns the opposite of its operand.
orA logical operator in Lua that returns true if either of its operands are true, otherwise false.
repeatA keyword used to start a repeat-until loop in Lua.
returnA keyword used to exit a function and return a value.
thenA keyword used to separate the conditional statement from the block of code to execute in an if statement.
trueA boolean value in Lua that represents true.
untilA keyword used to mark the end of a repeat-until loop in Lua.
whileA keyword used to create a loop that continues as long as a condition is true.

Whitespaces

Whitespace in Lua refers to any sequence of spaces, tabs, and newlines.

The purpose of this is to make the code more readable and to separate tokens. The whitespace between elements in a statement allows the interpreter to distinguish where one element ends and the next element begins.

When defining variables or functions, Lua ignores whitespace except when it is necessary to separate tokens.

For example, the following lines of code are equivalent:

x=5
x = 5

The first line has no whitespace between the variable name x, the assignment operator =, and the value 10. There is whitespace between y, the assignment operator =, and 20 on the second line.

In Lua, whitespace is not allowed inside variable names, function names, keywords, or other tokens.


Second Lua Program

It’s time to create our second Lua program, so let’s get started!

Interactive Mode Programming

Lua interactive mode programming is a method of writing, executing, and testing Lua code in an interactive environment, also called the Lua interpreter.

When programming in this mode, you can input Lua code directly into the interpreter prompt and see the output instantly.

To start programming in the interactive mode, open a terminal or command prompt and type “lua” to start the Lua interpreter.

After the interpreter starts, you can begin typing Lua code directly at the prompt, which is identified by the “>symbol.

The following code can be entered at the prompt, as an example:

> print("Hello, Developers!")

By pressing Enter on the keyboard, the interpreter will run the code and output the result as follows:

Hello, Developers!

You can define variables, functions, and test your code while programming in interactive mode.

You can define a variable such as “mrx,” assign it a value, and then print its value to the console.

> mrx = 786
> print(mrx)

The output is as follows:

786

It is also possible to use control structures such as if/else statements, loops, and functions in interactive mode.

Interactive mode programming can be a useful way to quickly test and experiment with Lua code, as well as to learn the language and its features.


Default Mode Programming

Although interactive mode programming can be a helpful way to experiment with and test Lua code, it is not suitable for larger projects. For more extensive programs, it is recommended to use a text editor or integrated development environment (IDE) to write Lua code and execute it as a standalone program.

This is achieved using the default mode of programming, which involves writing Lua code in a text editor and saving it as a Lua file with the “.lua” extension.

This file can then be executed as a standalone program by running the Lua interpreter followed by the name of the file. An interpreter is no longer active when the script has been completed.

To create a basic Lua program, you can start by writing the source code in a file with the .lua extension. For example, create a file named second.lua and enter the following code:

print(“Hello Developers”)

This program simply prints the message “Hello Developers!” to the console when run.

You can run the program by typing “lua second.lua” in the terminal, assuming you are in the same directory as the second.lua file.

Now let’s try executing Lua programs in another way. Here is the modified second.lua file:

#!/usr/local/bin/lua

print("Hello Developers")

The first line of this code, “#!/usr/local/bin/lua”, is called a “shebang” or “hashbang“.

It is a special Lua syntax used in Unix-like operating systems to specify the interpreter for the script that follows.

In this case, it tells the system to use the Lua interpreter located at “/usr/local/bin/lua” to execute the script.

Type the following instructions to execute the program:

chmod a+rx second.lua
./second.lua

When the program is executed, the first line is ignored because it starts with the ‘#‘ character, and then the interpreter moves on to the next line which prints out the string “Hello Developers”.

We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *