Lately, several international companies are offering a vacancy on Stack Overflow, remote or in person, for C++ programmers. br/cpp) that have knowledge of the Lua programming language, in addition to various software and Games are adopting Lua very quickly. So, no let those opportunities slip away!
Here’s everything for you to start in this world of the Lua programming language!
Come on!
Note: This tutorial is suitable for anyone who basically knows any programming language.
Lua is a high-level, dynamically typed, multiparadigm, reflective, lightweight, interpreted programming language designed by Tecgraf at PUC-Rio in 1993 to expand general applications in an extensible manner (which joins parts of a program made in more than one language), for prototyping and to be embedded in complex software such as games. It resembles Python, Ruby and Icon, among others.
Lua was created by a team of Tecgraf developers from PUC-Rio, at first, to be used in a Petrobras project. Due to its efficiency, clarity and ease of learning, it started to be used in several branches of programming, such as in game development (Blizzard Entertainment, for example, used the language in the World of Warcraft game), robot control, computer processing. text, etc. It is also often used as a general purpose language.
Lua combines procedural programming with powerful data description constructs based on associative tables and extensible semantics. It is dynamically typed, interpreted from bytecodes, and has automatic memory management with garbage collection. These characteristics make Lua an ideal language for configuration, automation (scripting) and rapid prototyping.
And also:
Games that also use Lua:
Examples of companies that developed games using the Lua language: LucasArts, Croteam, BioWare, Microsoft, Relic Entertainment, Absolute Studios, Monkeystone Games, Blizzard, SNKPlaymore, Facepunch Studios, KOG.
Lua was created in 1993 by Roberto Ierusalimschy, Luiz Henrique de Figueiredo and Waldemar Celes, members of the Computer Graphics Technology Group at PUC-Rio, the Pontifical Catholic University of Rio de Janeiro, in Brazil.[5] Versions of Lua before version 5.0 were released under a license similar to the BSD license. As of version 5.0, Lua has been licensed under the MIT license.
Some of its closest relatives are Icon, for its design, and Python, for its ease of use by non-programmers. In an article published in Dr. Dobb’s Journal, the creators of Lua also claim that Lisp and Scheme were a big influence in the decision to develop the table as Lua’s main data structure. Lua has been used in various applications, both commercial and non-commercial.
The first project using the language in games was in 1997 when LucasArts used it as a scripting language in the game Grim Fandango.[3]
In 2008 one of Lua’s most famous engines was born (Corona SDK)
In 2009 Love2D was born, a 2D game engine.
Lua is usually described as a multi-paradigm language, offering a small set of general features that can be extended to fit different types of problems, rather than providing a more complex and rigid specification to match a single paradigm. Lua, for example, does not contain explicit support for inheritance, but it does allow it to be performed relatively easily with metatables. Likewise, Lua allows programmers, when implementing names, classes, and other functions, to employ powerful functional programming techniques and complete lexical scopes.
Lua is a language that only supports a small number of structures, such as atomic data, boolean values, numbers (double-precision floating point by default), and strings. Common data structures such as arrays, sets, tables, lists, and records can be represented using Lua. Lua was not built with support for object-oriented programming.
Via: https://wikipedia.org/wiki/Lua_(programming_language)
To install Lua just use your distribution’s package manager, for example:
emerge lua
sudo apt install lua
or if it doesn’t work, enter the version, example: sudo apt install lua51
You can write in Lua in any IDE, however, the most recommended one is Neovim which includes we’ll see how to create a plugin for Neovim using Lua that has native integration.
After installing run: lua --help
the output will be:
Examples:
Running only
lua
command enters a subshell, runos.exit()
inside the subshell to exit.
Parameter | Usage |
---|---|
-e |
lua -e 'print("Hello, Lua!")' |
-i |
lua -i script.lua |
-v |
lua -v |
Version |
---|
Lua 5.1.5 Copyright (C) 1994-2012 Lua.org, PUC-Rio |
The most basic program.
nvim hello-world.lua
And run: lua hello-world.lua
or:
chmod +x hello-world.lua
and run:./hello-world.lua
. You could still replace the header withwhich lua
and add, for example:#!/usr/bin/lua
Other ways to print:
No parentheses
Multiple lines
Or also with parentheses:
print([[ ]])
Single-line comments use two dashes (–) can be:
Or in multiple lines
Detail: the
--
must be pasted from the[[
at the beginning.
There are three types of variables in Lua: global variables, local variables and table fields. Every variable is assumed to be a global variable unless it is explicitly declared as a local variable.
Creating a local variable:
Table fields:
Creating an empty table and adding later:
To concatenate strings in Lua you need to use the dot twice: ..
, example:
Output:
Hello World!
.
We can declare multiple variables and print it like this:
Lua before version 5.4 didn’t support constants automatically, but you can add a table and make the table read-only using metatable (we’ll see this later). But from 5.4 on, use it like this:
Run:
lua5.4 constants.lua
If trying to reset, example:
You will get the error:
lua5.4: sandbox.lua:3: attempt to assign to const variable 'my_var'
Arrays are ordered arrays of objects, which can be a one-dimensional array containing a collection of rows or a multidimensional array containing several rows and columns.
In Lua, arrays are implemented using index tables with integers. The size of an array is not fixed and can grow based on our requirements, subject to memory constraints.
In Lua the array/matrix starts from 1, if you try to print 0(zero) the output will be
nil
A one-dimensional array can be represented using a simple table structure and can be initialized as shown below.
Data typing in Lua is dynamic, but if you want to get the data type, just, for example:
Besides that there are also types: userdata
and thread
.
Lua uses almost all the operators that other programming languages use, examples:
operator | operator | operator | operator |
---|---|---|---|
+ |
- |
* |
/ |
% |
^ |
== |
~= |
> |
< |
>= |
<= |
and |
or |
not |
# |
In addition to the
..
we’ve already seen that serves for concatenation.
Examples:
The others will be seen later!
Like other programming languages, Lua also has conditions, of course (the most used resource in any programming language).
Note the use of the words:
then
andend
To use the if
, example:
To use else
To use elseif
To perform an action at certain times we use loops, in Lua there are 3 types of loops: while
, for
and repeat until
, let’s see how to use them:
Note the use of reserved words:
do
andend
while
loop
for
loop
Miscellaneous examples.
repeat until
loop
Using break
Functions are important for code reuse, let’s see some ways to use them in Lua.
Basic function:
Passing parameters:
Using signature:
Function with variable argument:
Note the use of the native
ipairs
function which is an iterator (we’ll see more later)
In this case we pass 5 parameters to the function.
Printing all parameters passed with variable argument:
For UPPERCASE
Note that accented words do not change. We’ll see how to change this when we talk about including libraries.
To lowercase
For month with zero:
%02d
.
string.sub(STRING, POS_INI, POS_FINAL)
Or
For this example: 4 times
Tables are the only data structure available in Lua that help us create different types, such as arrays and dictionaries. Lua uses associative arrays and can be indexed not only with numbers but also with strings, except nil. Tables have no fixed size and can grow as per our need.
Lua uses tables in all representations, including the package representation. When we access a string.format method, it means that we are accessing the formatting function available in the string package.
Tables are called objects and are not values or variables. Lua uses a constructor expression {} to create an empty table. It should be noted that there is no fixed relationship between a variable that contains the table reference and the table itself.
Read the comments in the code for greater understanding:
There are also the functions: sort
, foreach
, foreachi
and getn
. Find out more here.
The module is like a library that can be loaded using require
and has a unique global name containing the code to be used.
Example: Using a function that is in the my_module.lua
file of the program.lua
program:
my_module.lua
lua program
Another way to use and instantiate the module:
my_module.lua
lua program
Let’s use the os
native library
Learn more at: https://www.lua.org/pil/22.1.html
To do this, use the reserved word: arg
. See the examples below:
A metatable is a table that helps modify the behavior of a table to which it is attached with the help of a set of related meta keys and methods. These metamethods are powerful Lua features that enable features like -
__index
in meta-table.There are two important methods that are used in handling metatables, which include -
setmetatable(table, metatable)
- This method is used to set the metatable to a table.getmetatable (table)
- This method is used to get the metatable of a table.Let’s first look at how to define one table as a metatable of another. It is shown below.
Or just:
__index
A simple example of a metatable to search the metatable when it is not available in the table is shown below.
Output:
value1 MetatableValue
Summarizing the code above:
If an index doesn’t exist and you want to add it when it’s called and it doesn’t exist you can use __newindex
and create a method/function for that.
More information here.
LuaJIT is a Just-In-Time (JIT) Compiler for the Lua programming language. Its official website is: https://luajit.org/ .
JIT is a technology that compiles a program at runtime.
The LuaJIT implementation seems to outperform all other dynamic JIT languages (V8, Tracemonkey, PLT Scheme, Erlang HIPE) by an order of magnitude.
To install LuaJIT use your system’s package manager, examples:
To use it, instead of using the lua
command, use luajit
, example:
LuaJIT provides superior performance to the Lua interpreter.
As with any high-performance system, the answer in the end comes down to two things: algorithms and engineering. LuaJIT uses advanced compilation techniques and also has a very precise engineering implementation. For example, when sophisticated compilation techniques cannot handle a piece of code, LuaJIT resorts to a very fast interpreter written in x86 assembly.
LuaJIT earns double points in the engineering aspect, because not only is LuaJIT itself well designed, but the Lua language itself has a simpler and more coherent design than Python and JavaScript. This makes it (marginally) easier for an implementation to deliver consistently good performance.
LuaRocks is a package manager for the Lua programming language, similar to package managers for other languages such as: npm(JavaScript), composer(PHP), gem(Ruby), pip(Python) and among others.
Its official website is: https://luarocks.org/
Provides a standard format for distributing Lua modules (in a standalone format called “rock”), a tool designed to easily manage the installation of rocks, and a server to distribute them. Although not included in the Lua distribution, it is called a “de facto package manager for community-contributed Lua modules”.
To install it also use your system’s package manager, examples:
To use it use the command luarocks --help
.