Skip to content
Image with logo, providing a link to the home page
  • United Stated of America flag, representing the option for the English language.
  • Bandeira do Brasil, simbolizando a opção pelo idioma Português do Brasil.

Development Environments: Lua Programming Setup

An image of ZeroBrane Studio, an IDE for programming in Lua, with examples of the source code snippets presented in the article written in the text editor and their results on the shell.

Image credits: Image created by the author using the program Spectacle.

Requirements

The requirements to start programming activities with Lua are similar to those described for JavaScript and Python: a text editor and an interpreter, or an Integrated Development Environment (IDE).

If you wish to avoid an initial set up, you can use the Lua code editor and interpreter provided in this website to be used in your browser. However, eventually you will need to configure a programming environment in your machine.

To avoid repeating the discussions from JavaScript and Python:

  1. If you already have a text editor, the set up for the Lua interpreter is simple. Unlike in other languages, Lua interpreter can be as simple as a self-containted, single executable file.
  2. If you would rather use an IDE, the simplest option is choosing ZeroBrane Studio, which includes a text editor, interpreter and debugger among other features;
  3. If you do now know how to install program, what is PATH or how to configure it, you can refer the topic regarding how to install programs.

Part of the contents of this page will be identical to the Python's page. Therefore, if certain paragraphs seem familiar, it will not an impression, but déjà vu. As a matter of fact, this will also occur in new entries about development environments for other programming languages. After all, the setup procedures are similar.

Video Version

This entry has a video version available on the YouTube channel. Although this text version is more complete, you can follow the video first, if you prefer it.

About Lua

Python and Lua lead my list of recommended programming languages for beginners, as previously commented in introduction about development environments; the third option is JavaScript, due to the Internet.

Lua is a programming language from Brazil (created and maintained by PUC-Rio). The word lua means moon in Portuguese. As Python, Lua is a language with concise and elegant syntax. In fact, Lua primes for its simplicity.

The grammar of a programming language defines the rules that determine how to write code that is valid for the language. Lua's grammar is compact and clean; its formal definition requires a little more than one A4 paper page on version 5.1 and about one and a half page in version 5.4.

In my opinion, Python's code resembles more an pseudocode than one written in Lua, although Lua's syntax is also similar to that of an algorithm. While Python defines blocks and scopes using spacing, Lua uses written keywords, something that can be interesting for people who use a screen reader while programming. In fact, there are systems (such as BlindOS) that use Lua to provide programmable environment for blind people. Although I do not recommend it, words for blocks can also be suitable for people who want to program using mobile devices, as the access to symbols such as curly brackets in those devices require additional touches in many virtual keyboards.

In a way, Lua is an antithesis of Python for standard libraries: instead of Python's batteries included approach, Lua provides a minimalist environment for programming. This makes the language an excellent choice for use inside other programs, potentially written in other programming languages. Besides, Lua (particularly LuaJIT) is a fast scripting language, as another differential.

The combination of the two factors results in many high performance programs embedding Lua as part of the project. Parts of the program for which performance is essential can be written in languages such as C and C++. The other parts can be written in Lua. For instance, there are many digital games that allow creation content in Lua (a practice called modding), while the game engine is written in a language such as C++.

Although Lua's standard library is lean, there exists external libraries to extend it. For instance, the project Lua Rocks gathers ready to use libraries. The Lua for Windows environment lists and assembles useful libraries in a single distribution, as an attempt to provide a "batteries included" version of Lua.

Lua's documentation is available online. Although older versions are translated to some languages, the most recent ones only are available in English.

Versions

One can find Lua's most recent version at the official website of the project. However, many applications embedding Lua use version 5.1, as it is used by LuaJIT.

In general, the versions 5.1 or newer are suitable to learn the language. Although Lua 5.1 is similar to the more recent versions, there are some differences. More recent versions provide additional resources (such as Unicode support, integer numbers as a type and constants).

Due to the similarities, the links provided in this page will refer the version 5.1 when a feature is available, or later versions when required.

Interpreter and Text Editor

You should use root or administrator accounts only to install the interpreter. After the installation, use a regular user account, with lower privileges, to run the interpreter and program using it.

Linux

As it was the case for Python, it is simple to install Lua in Linux distributions that provide a package manager. A few examples for popular distributions:

  1. Arch Linux:
    pacman -S lua

    The lua parameter installs the latest version. There are other versions of the language available (such as lua51 for version 5.1), as well as luajit.

  2. Debian, Ubuntu or distributions based on the former ones:
    apt-get install lua5.4
  3. Fedora:
    dnf install lua
  4. Gentoo:
    emerge --ask dev-lang/lua

macOS

On macOS environments, you can use brew to install Lua.

Windows

On Windows environments, the usual approach is downloading the interpreter from the official website. The downloads page of LuaBinaries provides pre-compiled and ready to use binary files.

You can choose the latest release (or any previous version that you wish). The resulting files are, taking the version 5.4.2 as an example:

  • lua-5.4.2_Win32_bin.zip for 32-bit systems;
  • lua-5.4.2_Win64_bin.zip for 64-bit systems.

After choosing a file, wait a few seconds and the download should start. After it finishes, you have to extract the contents of the downloaded file. The extraction directory will be the one to use the file.

Unlike other programming languages, Lua's interpreter is self-contained. After you extract the file into a directory of your choice, use the program lua54.exe (the number can vary according to the version). Lua's interpreter will be ready to use.

Should you wish to add the interpreter to the PATH, refer to how to install programs.

Alternatives to install the interpreter on Windows include:

Environment Test

You can start to program in Lua after installing the interpreter. To start the interpreter, with use the downloaded executable or type lua followed by enter in a command line interpreter (this requires PATH configuration for files manually downloaded).

luaLua 5.4.3  Copyright (C) 1994-2021 Lua.org, PUC-Rio
>

This section presents the same examples used in JavaScript and Python for purposes of testing and comparing the languages.

As in Python, you will type your code after the greater than symbol (>).

For instance, you can write on the console with print() (documentation). To write a message, type something like print("Hello! My name is Franco.") after the greater than symbol and press enter. The interpreter will write Hello! My name is Franco and will wait your next command.

luaLua 5.4.3  Copyright (C) 1994-2021 Lua.org, PUC-Rio
> print("Hello! My name is Franco.")Olá! Meu nome é Franco.
>

The text in the images are from the Portuguese version of this page.

An example of starting and using the Lua interpreter in the command line. Use `lua` to start the interpreter; inside it, you can write code. The image presents examples of running code presented on this section.

If you use a character with accents and it does not show, you are probably using an older version of Lua, without Unicode support.

From now on, you should follow the previous steps whenever you read a Lua source code block in this page and wish to manually run in the interpreter.

To exit the interpreter, type os.exit() followed by enter or press Ctrl d. On Windows, the shortcut can be Ctrl z followed by enter.

Like Python, Lua can be used in a Read, Eval, Print, Loop (REPL) mode. IN REPL, current versions of Lua can interpret mathematical expressions and variable inspections directly by typing the expression. In older versions of Lua, you should prefix the expression with an equal (=) symbol. For instance, = 1 + 1.

1 + 1
= 1 + 1

You can also type a string directly:

"Hello! My name is Franco."

However, you should note that, as in Python, those direct uses are only possible for interactive use, that is, in REPL style. They are convenient ways to inspect values and variables, though they are not permitted in programs. If you wish to perform the same operations in a source code file (a script), you should use print() to write the results.

print(1 + 1)
print("Hello! My name is Franco.")

Thus, it can be convenient to create the habit of using print() when you want to write in the console. For instance, create a file called script.lua (you can choose any name that you want) with the following contents:

print("My First Lua Script")
print("Hello! My name is Franco.")
print("The interpreter can do Math.")
print("Check it out: ", 1 + 1)
print("Bye!")

To run the script, open a command line interpreter (shell) in the directory that you have created the file and type lua script.lua . The Lua interpreter will run the file provided as a parameter (the value script.lua after lua) and will show results from print() calls.

lua script.luaMy First Lua Script
Hello! My name is Franco.
The interpreter can do Math.
Check it out:   2
Bye!

If the current directory of command line interpreter (shell) is not the directory of the file, you can change directory to the file's folder, or you can write the absolute path of the file. Examples for absolute file paths can include C:\Users\Franco\Desktop\script.lua on Windows for a file in the desktop of a user account named Franco or ~/Desktop/script.lua for a file in the desktop of a Linux machine.

Example of running the `script.lua` in the command line. The image shows the performed command (`lua script.lua`) and the results its execution.

It is enough to know how to use the REPL and run a Lua source code file for learning activities. In general, these two operations are also enough for most daily or professional uses of the programming language.

IDEs

The same considerations about the use of IDEs in Python apply to Lua. The convenience, especially for beginners, continues to be a benefit from using IDEs.

The option to run code with a single click also applies to Lua. In particular, search for the option to run a project with a single click (normally on a triangle icon (🢒) commonly used to play content eletroelectronics) or with a key press (usually F5). Furthermore, remember shortcuts for text editors, such as Ctrl n (or File / New) to create new files and Ctrl o (or File / Open) to open existing files.

Although there exists fewer IDEs for Lua than for Python, ZeroBrane Studio is an excellent option (although with the resources for beginners that Thonny provides for Python).

ZeroBrane Studio

ZeroBrane Studio is a complete IDE and by recommendation for beginners. You can get the program from the project's GitHub page or from the download section at the official website.

The official website requests a donation before starting the download. If you do want to make one, you can skip to the download with the option Take me to the download page this time.

Unless you change the installation directory, the IDE files will be stored in the same directory of the installer. If you want to change it, choose the option Browse... and, in the new panel, the directory to install the program.

Customizing the install directory of `ZeroBrane Studio`. After running the installer, select `Browse...` if you want to change the directory to save the IDE.

ZeroBrane Studio also provides some choices for (human) language. To change it, you should choose the option Edit / Preferences / Settings: User, which will open a file called user.lua. ZeroBrane Studio uses a Lua file to customize the IDE (you can check other options in the manual).

To access the settings in `ZeroBrane Studio`: choose the option `Edit`, browse the options down to `Preferences` and choose `Settings: User`.

For instance, to translate the IDE to Brazilian Portuguese, you can add after the last line of the file:

language="pt-br"

This way, the resulting file should resemble something like:

--[[--
  Use this file to specify **User** preferences.
  Review [examples](+/usr/share/zbstudio/cfg/user-sample.lua) or check [online documentation](http://studio.zerobrane.com/documentation.html) for details.
--]]--

language="pt-br"

Save the file. Next, after you restart the program (that is, close and open it in sequence), the program should be in Portuguese.

Translating `ZeroBrane Studio` to Portuguese. After accessing the configurations, type the following Lua code: `language="pt-br"`. Save the file and restart the IDE to change the language.

To run a source code file in ZeroBrane Studio, you can use the triangle icon to start the program in the debugger (shortcut: F5) or the icon with two triangles (, used for fast forward em eletroeletrônicos) to run the file without using the debugger (shortcut: F6). In the debugging mode, you can press F5 again to run the program.

An example of running code in `ZeroBrane Studio` for the first time.

When you are using the debugger for the first time, Windows may trigger a security alert. If you want to use the debugger, you should allow ZeroBrane Studio to use the local network.

Windows warning about `ZeroBrane Studio` attemping to use the network in the first attempt to start its debugger.

Warning refers to the IDE's attempt to use port 8172 when debugging to enable communication between the IDE and the running program to debug.

Example of output using the `ZeroBrane Studio` IDE.

Furthermore, the IDE allows choosing among several versions of Lua. It is possible to change the Lua interpreter version used by ZeroBraneStudio in Project, then Lua Interpreter, then choosing Lua 5.3 (for instance).

Decoda

A second option for Lua IDE is Decoda. In the past, Decoda was one the few IDEs that provided a debugger for Lua. Nowadays, ZeroBrane Studio is a more modern and up to date Lua IDE.

Decoda was a paid option, though it became an open source project around 2013. The project has not been updated in the last years, though it remains a valid alternative for Lua 5.1, especially for embedded uses of Lua in other programs.

Lua Edit

Another potential IDE for Lua 5.1 is LuaEdit. Though, like Decoda, it has not been updated for a few years.

Other Options

For other IDE options, there are programs supporting extensions.

First Steps to Begin Programming in Lua

The following source code snippets illustrate some resources of the Lua programming language. At this time, it is not necessary to fully understand them; the purpose is showing resources and the syntax of the language.

There are three ways of using the code. You can:

  1. Type (or copy and paste) the code directly into the language's interpreter;
  2. Write and run the code in the IDE of your choice;
  3. Write the code using a text editor and run the created file in the interpreter.

The examples are the same adopted for JavaScript. Therefore, you can compare languages, and notice similarities and differences between them.

Getting to Know Lua Through Experimentation

Examples of use and outputs of code snippets described in this section using the `lua` interpreter on the command line.
  1. Text writing:

    print("One line.")
    print("Another line.")
    print("One line.\nAnother line.")
  2. Comments (text that is ignored by the interpreter; documentation):

    print("Interpreter processes") -- Interpreter ignores.
    --[[ <- Here the comment starts.
    It can spawn multiple lines.
    Here it ends -> ]]--
    --[[ It can also start and end in the same line. ]]--
    -- Though, for single line comments, it is easier to use this comment style.
  3. Mathematics operations:

    • Sum, subtraction, multiplication and division (documentation):

      print(1 + 1)
      print(2 - 2)
      print(3 * 3)
      print(4 / 4) -- What does happen if you try to divide by 0? Try it!
    • Math expressions:

      print(1 + 2 - 3 + (4 * 5) / 6)
    • Power (documentation):

      print(5 ^ 2)
    • Square root (documentation: math.sqrt()):

      print(math.sqrt(25))
    • Trigonometric functions, such as sin (documentation: math.sin and math.pi):

      print(math.sin(math.pi / 2.0)) -- Sin.
  4. Comparisons (result in true or false):

    • Equality (documentation):

      print(1 == 2) -- Equal: both equals are required!
      print(1 ~= 2) -- Different.
      print("Franco" == "Franco")
      print("Franco" ~= "Franco")
      print("Franco" ~= "Your name")
      -- Lua differs lower case characters from upper case ones (and vice-versa).
      print("F" == "f")
      print("F" ~= "f")
      print("Franco" == "franco")
      print("Franco" ~= "franco")
    • Other comparisons (documentation):

      print(1 < 2) -- Less than.
      print(1 > 2) -- Greater than.
      print(1 <= 2) -- Less or equal than.
      print(1 >= 2) -- Greater or equal than.
  5. Variables and assignment (documentation):

    Variables are like boxes that store values put inside them. The assignment operator (a single equal sign (=) in Lua) commits the storage.

    The use of local defines a local variable instead of a global one. If you omit local, the variable will be global.

    local x = 123
    print(x)
    local result = 123.456 + 987.654
    print(result)

    You should note that you can declare a variable with a chosen name only once. However, you can change its value as many times as you need.

    local name = "Franco"
    print(name)
    name = "Franco Garcia"
    print(name)
    local variables_can_vary = "Franco"
    print(variables_can_vary)
    variables_can_vary = "Seu Nome"
    print(variables_can_vary)
    variables_can_vary = "Outro Nome"
    print(variables_can_vary)
    local logical_value = true
    print(logical_value)
    logical_value = false
    print(logical_value)
    logical_value = (1 + 1 == 2)
  6. Constants (documentation):

    Constants are available since the version 5.4 of Lua.

    local PI <const> = 3.14159
    print(PI)
    local E <const> = 2.71828
    print(E)
    E = 0 # Error; the value of a constant cannot be changed once set.
  7. Errors:

    print(Ooops!) -- Text should be between double quotes, single quotes, or pairs of square brackets on each side.
    pri("Incorrect name for print")
    print(1 / 0)
    print(0 / 0)
  8. Strings for words and text (documentation):

    print("Ok, this is a valid string")
    print('Ok, this is another valid string')
    print([[Ok, this is also a valid string]])
    print("If you want to 'mix' quotes, you have to use those different from the external ones.")
    print("Otherwise, you will need to escape them with a backslash, like this: \". The backslash is required.")
  9. Logical operators (documentation):

    print(true and true) -- This is a logical "and".
    print(true or false) -- This is a logical "or".
    print(not true) -- This is a logical "not".
  10. Conditions (documentation):

    local browser = "Firefox"
    if (browser == "Firefox") then
        print("Mozilla Firefox.")
    end
    local my_browser = "Your Browser"
    if (my_browser == "Firefox") then
        print("You use a browser from Mozilla.")
    else
        print("You use another browser.")
    end
    local i_use = "X"
    i_use = i_use:lower()
    if (i_use == "firefox") then
        print("You use a browser from Mozilla.")
    elseif ((i_use == "chrome") or (i_use == "chromium")) then
        print("You use a browser from Google.")
    elseif (i_use == "edge") then
        print("You use a browser from Microsoft.")
    elseif (i_use == "safari") then
        print("You use a browser from Apple.")
    elseif (i_use == "internet explorer") then
        print("You should use a more modern browser...")
    else
        print("You use another browser.")
    end
  11. Loops (documentation: while and repeat), and for):

    for i = 0, 5, 1 do
        print(i)
    end
    j = 0
    while (j < 5) do
        print(j)
        j = j + 1
    end

    Lua provides the command repeat... until instead of do... while. To create an equivalent do... while command, you should negate the condition with a not.

    k = 0
    repeat
        print(k)
        k = k + 1
    until (k >= 5)
  12. Functions (documentation):

    function my_function(x, y)
        local result = x + y
        return result
    end
    
    -- A function is a block of code that performs arbitrary processing as defined
    -- by the programmer.
    -- After the definition, you can execute the function whenever wanted, using
    -- a function call.
    z = my_function(12, -34) -- This is an example of a function call.
    print(z)
    print(my_function(1, 2)) -- This is another example.
  13. Data types (documentation):

    local integer_number = 1
    local another_integer_number = -1
    local real_number = 1.23
    local logic_value = true -- or false; it only can be either true or false.
    local string_for_text = "Text here. Line breaks use\nthat is, this will be at\n the third line."
  14. Input (documentation: io.read() e io.write(), e string.format()):

    -- Once there is a request for a value, type one then press `enter`.
    io.write("What is your name? ")
    local your_name = io.read("*line")
    io.write("How old are you? ")
    local your_age = io.read("*number", "*line") -- Although only number would be enough,
    -- adding line afterwards avoid leaving characters for next read() calls.
    print(your_name)
    print(your_age)
    -- The .. operator performs an operation called concatenation,
    -- that combines the second string after the first.
    print("Hello, " .. your_name .. "!")
    print(string.format("You are %d years old.", your_age))

Congratulations! You Are Already Able to Write Any Program in Lua

Don't you believe it? You can find the explanation in the introduction to JavaScript

In short, it is not enough to learn the syntax of a language to solve problems using it. It is much more important learning programming logic and developing computational thinking skills than learning the syntax of a programming language. In fact, when you are in doubt about the syntax, you just have to consult the documentation. You do not have to memorize it.

After you learn a first programming language, it is relatively simple to learn other languages (that adopt similar programming paradigms to the first one). To verify this statement, you can open a new window in your browser and place it side by side with this one. Then, you can compare the source code blocks written in Lua (in this window) and in Python (in the second window).

If you wish to perform comparisons with other programming languages, the following options are available:

Next Steps

Once the development environment is configured, you can continue your system development journey.

To avoid repetitions, I recommend reading the page about configuring the JavaScript environment. Even if you are not interested at the language, many discussions are relevant to any programming language. Besides, you will understand a way to create Internet pages and will be able to create content for your browser.

Until GDScript (for Godot Engine), the topics describe develoment environment configurations for a few programming languages. After GDScript, the focus becomes basic concepts for learning programming.

  • Video
  • Informatics
  • Programming
  • Beginner
  • Dev Env
  • Windows
  • Linux
  • Lua