Lua Basics

Are you new to Lua? The following sections provide a brief overview of the elements most frequently used in Translator.

For more information, we recommend Programming in Lua and the Lua online reference manual.

Already comfortable with these concepts? More advanced programmers should start with Eliot’s Tips and Tricks. This section provides more in-depth information about the nuances of the language. We recommend reviewing this information to avoid some common pitfalls.

Prefer to learn by example? Check out the Lua Tutorial wiki!

Values and Variables [top]

In Lua, the commonly used types of values are specified in the table below.

Type Description Example
nil Represents the undefined value. nil is not equal to 0 or “” (the empty string). If a variable has not had a value assigned to it, its value is assumed to be nil. nil
Boolean Can be either true or false. true
Number Any number (either containing or not containing a decimal point). In Lua, by default, all numbers are stored as 64-bit floating-point values. 1198.6
String A string of text characters. See Working With Strings for more details. “Dr. John Smith”
Table A collection of values. See Working With Tables for more details. {1, 2, 3, 4, 5}
Function In Lua, functions can be treated like any other values. function hello()print(“hello”)end
Userdata These are user defined data types from the external application – i.e. node trees in Iguana are userdata objects which internally are implemented in C++.

Note: There are other value types in Lua, but you are not likely to use them. See the Values and Types section of the Lua reference manual and the online programming book for more details.

Lua is a dynamic language. So a variable can point to any type of value. Variable names consist of letters, digits and underscores. The first character of a variable name must not be a digit. The following are examples of legal variable names:

x
text1
myvar
MYVAR

In Lua, variable names are case-sensitive: capitalized letters and non-capitalized letters are not treated the same. This means that myvar, Myvar and MYVAR refer to different variables, not the same variable.

In Lua, any variable can contain a value of any type. For example, the following are all legal:

myvar = 98.6
myvar = "Dr. John Smith"
myvar = {98.6, "Dr. John Smith", "Radiology"}

For details on how values are assigned to variables, see Assignment and Expressions.

For more detail see: the Values and Types in the online reference manual, the online programming book and the Lua Tutorial wiki.

Strings [top]

In Lua, a string is any collection of characters. It can be enclosed in single quote characters, double quote characters, or pairs of square brackets:

"Dr. John Smith"
'Radiology'
[[Downtown Hospital]]

You can use square brackets to enclose multiple lines:

[[The results of the lab tests are in.
No abnormalities have been detected.]]

If you want to include brackets in a multi-line string, you can use an open bracket [ followed by one or more = characters and then another open bracket to indicate the start of a string. The string is ended by a close bracket ], the same number of = characters, and another close bracket:

[==[This string contains [] bracket
characters, but is ended by a ], two = and another ].]==]

[=[This string also contains [] brackets]=]

Lua uses the ‘..’ operator to join strings. There is also a library for standard string manipulation, like finding and extracting substrings, and pattern matching.

For more about strings see: the Values and Types in the Lua reference manual, strings in the online programming book and the Lua Tutorial wiki.

For more about string concatenation see: the Concatenation section in the Lua reference manual, the online programming book also concatenation is covered in the strings tutorial of the Lua Tutorial wiki.

For more about the string library see: the string library section in the Lua reference manual, the online programming book and the Lua Tutorial wiki.

Tables [top]

The more you know Lua the more you realize how core to the language tables are. Lua tables have a dual nature of being both an array and an associative hash table. They are the basis of objects in the language. They can be used to make other data structures like linked lists and so on.

The simplest way to use and access a table is as a collection of values indexed by an integer:

myvar = {98.6, "Dr. John Smith", "Radiology"}
trace(myvar[1])         -- displays 98.6
trace(myvar[3])         -- displays "Radiology"
myvar[4] = "ABC Health" -- new entry, key 4, value "ABC Health"

Note: The first element of this table has index the 1, not 0. The values in a table can be of any type, including strings, numbers, booleans, nil, functions or other tables.

You can also specify keys to identify the values in a table:

myvar = {temperature=98.6, doctor="Dr. John Smith", department="Radiology"}
trace(myvar["temperature"])      -- displays 98.6
myvar["works_at"] = "ABC Health" -- new entry, key "works_at", value "ABC Health"

In Lua, a[“b”] and a.b are identical:

trace(myvar["temperature"]) -- displays 98.6
trace(myvar.temperature)    -- also displays 98.6

This makes it easy to implement structures or records.

Tables can contain other tables as values:

-- new entry, key "temperatures", value is a table of 3 temperatures 
myvar["temperatures"] = {morning=98.6, afternoon=100.3, evening=99.4}
trace(myvar["temperatures"]["morning"]) -- displays 98.6
trace(myvar.temperatures.morning)       -- displays 98.6

A very useful technique with tables is to be able to iterate through their keys using pairs which gives all key value pairs and ipairs which gives integer keys only:

for Key,Value in pairs(T) do
   trace(Key.." = "..Value)
end

-- or for just integer keys:

for Key,Value in ipairs(T) do
   trace(Key.." = "..Value)
end

Tables are powerful, for more detail refer to the tables section in the Lua online programming book or search for “table” and “metatable” in the online reference manual.

Comments [top]

In Lua, the characters indicate that the rest of the line is a comment:

myvar = 98.6 -- this is a normal temperature
-- this line consists of nothing but a comment --

To create a multi-line comment, use followed by [[ and ]]:

--[[ this comment
is a multi-line comment ]]

As in strings, you can put one or more = characters between the two open bracket [ characters and the two close bracket ] characters:

--[==[ this comment
contains some bracket characters [] [[]]
but does not end until here ]==]

--[=[ this comment also contains
some [] bracket characters ]=]

Assignment and Expressions [top]

In Lua, like in most programming languages, you can assign a value to a variable. In Lua, the = operator indicates an assignment:

myvar = 98.6

Here, the value 98.6 is assigned to the variable myvar.

In Lua, any value can be assigned to any variable, as variables are not restricted to containing a specific type of value. For example, all of the following are legal:

myvar = 98.6
myvar = nil
myvar = "Dr. John Smith"
myvar = {98.6, "Dr. John Smith", "Radiology"}
myvar = true

You can also assign to multiple variables at once:

myvar = myvar2 = 98.6

Here, both myvar and myvar2 are assigned the value 98.6. You can also assign multiple values to multiple variables:

myvar, myvar2 = 98.6, "Dr. John Smith"

This assigns 98.6 to myvar and “Dr. John Smith” to myvar2. You can use this to swap the values of two variables. For example, the following statement assigns the value of myvar to myvar2 and the (old) value of myvar2 to myvar:

myvar, myvar2 = myvar2, myvar

In Lua, you can also use expressions to perform arithmetic and compare one value to another. The following tables list the operations that can be performed in Lua expressions.

Arithmetic operations

Operation Description Example
+ Addition myvar2 = myvar + 1
Subtraction myvar2 = myvar – 1
Negation myvar2 = -myvar
* Multiplication myvar2 = myvar * 10
/ Division myvar2 = myvar / 10
% Modulo (remainder from division) myvar2 = 47 % 10(this assigns 7 to myvar2)
^ Exponentiation myvar2 = 2^5(this is 2 to the power 5, or 32)

Comparison operations

Operation Description Example
== Equal to myvar1 == myvar2(this is true if myvar1 is equal to myvar2)
~= Not equal to myvar1 ~= myvar2(this is false if myvar1 is equal to myvar2)
< Less than myvar1 < myvar2(this is true if myvar1 is less than myvar2)
> Greater than myvar1 > myvar2(this is true if myvar1 is greater than myvar2)
<= Less than or equal to myvar1 <= myvar2(this is true if myvar1 is less than or equal to myvar2)
>= Greater than or equal to myvar1 >= myvar2(this is true if myvar1 is greater than or equal to myvar2)

Logical operations

Operation Description Example
not Logical not !myvar1(This is true if myvar1 contains nil or false, and is false otherwise)
and Logical and myvar1 and myvar2(This is true if both myvar1 and myvar2 are true)
or Logical or myvar1 or myvar2(This is true if either of myvar1 or myvar2 is true)

For more about assignment see: assignments in the online programming book, the Lua Tutorial wiki, or search for “assignment” in the online reference manual

For more about expressions see: expressions in the online programming book, the online reference manual or the Lua Tutorial wiki.

If Statements [top]

This is the syntax of an if statement:

temperature = 98.6
if temperature == 98.6 then
    trace("temperature is 98.6") -- this statement is executed
end

The condition in the if statement is considered true if its value is anything other than false or nil. The value 0 is not equivalent to false. For example:

myvar = 0
if myvar then
    -- anything in here is executed, as 0 is treated as true
end

In Lua, the only values that are not evaluated as true are false and nil.

In the if statement, you can use elseif and else to define additional conditions to check for:

if temperature == 98.6 then
    trace("temperature is 98.6")
elseif temperature > 98.6 and temperature < 100 then
    trace("temperature is slightly above normal")
elseif temperature >= 100 then
    trace("patient has a fever")
else
    trace("temperature is below normal")
end

For more detailsee: control structures in the online reference manual, the Lua Tutorial wiki, or if then else in the online programming book.

Loops [top]

Lua supports repeat and while loops:

myvar = 1
while myvar <= 10 do
    trace(myvar)
    myvar = myvar + 1
end

The statements between do and end are executed while myvar <= 10 is true, which means that this code prints out the numbers from 1 to 10.

You can also use break to exit a loop:

myvar = 1
while true do
    trace(myvar)
    myvar = myvar + 1
    if myvar > 10 then break end
end

This code also prints the numbers between 1 and 10.

Another way to write a loop is with the repeat statement:

myvar = 1
repeat
    trace(myvar)
    myvar = myvar + 1
until myvar > 10

For more detail see: control structures in the online reference manual and the Lua Tutorial wiki, or repeat and while in the Lua online programming book.

Additional Resources [top]

For more information on the Lua programming language I recommend the online Programming in Lua book. That is the best one to start with since it introduces Lua concepts in more of a tutorial manner.

I like the quality of the Lua documentation. One of the advantages of Lua is the succinct nature of the documentation. I found I understood Javascript better after reading the programming in Lua book. By comparison is hard to find good documentation for javascript – because there is so much low quality material written on the language.

Some sections to skip in the book would be the information on co-routines. Meta tables are probably not a useful concept unless you are going to get heavily into writing library code. I did find a use for it in the codemap example from our code samples.

After you have learned the language then the Lua 5.1 Reference Manual is useful. Especially the sections covering the standard libraries.

Our technical writer found the Lua Tutorial Directory a useful resource. I have not delved much into this although I am told it is good.

For the Enthusiast [top]

If you really get enthusiastic about Lua then the following resources might be interesting. Although you probably should do it on your own time rather than work time since this material is unlikely to make you more efficient at doing integration work.
The main academic paper about Lua discusses the philosophy behind its design:

R. Ierusalimschy, L. H. de Figueiredo, W. Celes,
Lua – an extensible extension language,
Software: Practice & Experience 26 #6 (1996) 635–652. [doi]

Brazilian Academy of Sciences, and the Brazilian Ministry of Science and Technology this paper was awarded the first prize (technological category) in the II Compaq Award for Research and Development in Computer Science in 1997. This award was a joint venture with Compaq Computer in Brazil.

For details on the implementation of Lua, see:

R. Ierusalimschy, L. H. de Figueiredo, W. Celes,
The implementation of Lua 5.0,
Journal of Universal Computer Science 11 #7 (2005) 1159–1176. [jucs · slides]

For a complete history of Lua till 2006, see:

R. Ierusalimschy, L. H. de Figueiredo, W. Celes,
The evolution of Lua,

Proceedings of ACM HOPL III (2007) 2-1–2-26. [doi · slides]

For a history of Lua till 2001, see:

R. Ierusalimschy, L. H. de Figueiredo, W. Celes,
The evolution of an extension language: a history of Lua,
Proceedings of V Brazilian Symposium on Programming Languages (2001) B-14–B-28. [ps]

The first paper describing Lua still has some historical interest:

L. H. de Figueiredo, R. Ierusalimschy, W. Celes,
The design and implementation of a language for extending applications,
Proceedings of XXI Brazilian Seminar on Software and Hardware (1994) 273–283. [ps]

For an early expository article, see:

L. H. de Figueiredo, R. Ierusalimschy, W. Celes,
Lua: an extensible embedded language,
Dr. Dobb’s Journal 21 #12 (Dec 1996) 26–33. [DDJ]

Leave a Reply