Lua is a scripting language used for procedural programming, functional programming, and even object-oriented programming. It uses a C-like syntax, but is dynamically typed, features automatic memory management and garbage collection, and runs by interpreting bytecode with a register-based virtual machine. This makes it a great language for beginners, but also a powerful tool for experienced programmers.
Lua has been somewhat eclipsed from the public view by languages like Python and JavaScript, but Lua has several advantages that make it popular in some major software projects. Lua is easily embedded within other languages, meaning that you can include Lua files in the code base of something written in (for instance) Java and it runs as if it were native Java code. It sounds like magic, but of course there are projects like luaj working to make it possible, and it's only possible because Lua is designed for it. It's partly because of this flexibility that you're likely to find Lua as the scripting language for video games, graphic applications, and more.
As with anything, it takes time to perfect, but Lua is easy (and fun) to learn. It's a consistent language, a friendly language with useful error messages, and there's lots of great support online. Ready to get started?
Installing Lua
On Linux, you can install Lua using your distribution's package manager. For instance, on Fedora, CentOS, Mageia, OpenMandriva, and similar distributions:
$ sudo dnf install lua
On Debian and Debian-based systems:
$ sudo apt install lua
For Mac, you can use MacPorts or Homebrew.
$ sudo port install lua
For Windows, install Lua using Chocolatey.
To test Lua in an interactive interpreter, type lua
in a terminal.
Functions
As with many programming languages, Lua syntax generally involves a built-in function or keyword, followed by an argument. For instance, the print
function displays any argument you provide to it.
$ lua
Lua 5.4.2 Copyright (C) 1994-2020 Lua.org, PUC-Rio
> print('hello')
hello
Lua's string
library can manipulate words (called "strings" in programming.) For instance, to count the letters in a string, you use the len
function of the string
library:
> string.len('hello')
5
Variables
A variable allows you to create a special place in your computer's memory for temporary data. You can create variables in Lua by inventing a name for your variable, and then putting some data into it.
> foo = "hello world"
> print(foo)
hello world
> bar = 1+2
> print(bar)
3
Tables
Second only to the popularity of variables in programming is the popularity of arrays. The word "array" literally means an arrangement, and that's all a programming array is. It's a specific arrangement of data, and because there is an arrangement, an array has the advantage of being structured. An array is often used to perform essentially the same purpose as a variable, except that an array can enforce an order to its data. In Lua, an array is called a table
.
Creating a table is like creating a variable, except that you set its initial content to two braces ({}
):
> mytable = {}
When you add data to a table, it's also a lot like creating a variable, except that your variable name always begins with the name of the table, and is separated with a dot:
> mytable.foo = "hello world"
> mytable.bar = 1+2
> print(mytable.foo)
hello world
> print(mytable.bar)
3
Scripting with Lua
Running Lua in the terminal is great for getting instant feedback, but it's more useful to run Lua as a script. A Lua script is just a text file containing Lua code, which the Lua command can interpret and execute.
The eternal question, when just starting to learn a programming language, is how you're supposed to know what to write. This article has provided a good start, but so far you only know two or three Lua functions. The key, of course, is in documentation. The Lua language isn't that complex, and it's very reasonable to refer to the Lua documentation site for a list of keywords and functions.
Here's a practice problem.
Suppose you want to write a Lua script that counts words in a sentence. As with many programming challenges, there are many ways to go about this, but say the first relevant function you find in the Lua docs is string.gmatch
, which can search for a specific character in a string. Words are usually separated by an empty space, so you decide that counting spaces + 1 ought to render a reasonably accurate count of the words they're separating.
Here's the code for that function:
function wc(words,delimiter)
count=1
for w in string.gmatch(words, delimiter) do
count = count + 1
end
return count
end
These are the components of that sample code:
-
function
: A keyword declaring the start of a function. A custom function works basically the same way as built-in functions (likeprint
andstring.len
.) -
words
anddelimiter
: Arguments required for the function to run. In the statementprint('hello')
, the wordhello
is an argument. -
counter
: A variable set to 1. -
for
: A loop using thestring.gmatch
function as it iterates over thewords
you've input into the function, and searches for thedelimiter
you've input. -
count = count +1
: For eachdelimiter
found, the value ofcount
is re-set to its current value plus 1. -
end
: A keyword ending thefor
loop. -
return count
: This function outputs (or returns) the contents of thecount
variable. -
end
: A keyword ending the function.
Now that you've created a function all your own, you can use it. That's an important thing to remember about a function. It doesn't run on its own. It waits for you to call it in your code.
Type this sample code into a text file and save it as words.lua
:
function wc(words,delimiter)
count=1
for w in string.gmatch(words, delimiter) do
count = count + 1
end
return count
end
result = wc('zombie apocalypse', ' ')
print(result)
result = wc('ice cream sandwich', ' ')
print(result)
result = wc('can you find the bug? ', ' ')
print(result)
You've just created a Lua script. You can run it with Lua. Can you find the problem with this method of counting words?
$ lua ./words.lua
2
3
6
You might notice that the count is incorrect for the final phrase because there's a trailing space in the argument. Lua correctly detected the space and tallied it into count
, but the word count is incorrect because that particular space happens not to delimit a word. I leave it to you to solve that problem, or to find other ways in which this method isn't ideal. There's a lot of rumination in programming. Sometimes it's purely academic, and other times it's a question of whether an application works at all.
Learning Lua
Lua is a fun and robust language, with progressive improvements made with each release, and an ever-growing developer base. You can use Lua as a utilitarian language for personal scripts, or to advance your career, or just as an experiment in learning a new language. Give it a try, and see what Lua brings to the table.
1 Comment