Thrive
Lua Primer

The following is a very brief and incomplete overview of Lua's syntax and some of its quirks. This is mostly meant for programmers already familiar with at least one other programming language, but unfamiliar with Lua.

If you want to know more about Lua, any of the following links is a good start:

Variables

1 -- Easy as pie
2 variable = 3.1415
3 
4 -- Local variables are preferred. They keep the global scope clean
5 -- and are a bit faster for access.
6 local localVariable = 42
7 
8 -- Undefined variables are nil by default
9 assert(idontexist == nil)

Tables

1 local myTable = {
2  1 = "number",
3  key = "value",
4  ["Key with spaces"] = "anotherValue", -- Note the (optional) trailing comma
5 }
6 
7 -- The following two lines are equivalent
8 myTable.a = "Thrive"
9 myTable["a"] = "Thrive"
10 
11 -- To remove an item, assign nil:
12 myTable.key = nil
13 
14 -- Arrays are just tables with numeric keys
15 local myArray = {
16  "first",
17  "second",
18  "third",
19  4,
20  5,
21  6
22 }
23 
24 -- Indices start at 1, not 0
25 assert(myArray[1] == "first")
26 
27 -- Accessing non-existant keys gives back nil
28 assert(myArray[0] == nil)
29 assert(myTable.nosuchkey == nil)

Functions and Classes

1 function myFunction(x, y)
2  return x + y
3 end
4 
5 -- Functions, just like variables, should be declared local where possible
6 local function myLocalFunction(x, y)
7  return x - y
8 end
9 
10 -- Functions without a return implicitly return nil
11 local function returnsNil()
12 end
13 assert(returnsNil() == nil)
14 
15 -- Classes are not a standard Lua feature, but the luabind library
16 -- enables them for us
17 class 'MyClass'
18 
19 -- Note the colon
20 function MyClass:__init(x)
21  self.x = x
22 end
23 
24 function MyClass:doSomething()
25  print("My x is " .. tostring(self.x))
26 end
27 
28 local myObject = MyClass(5)
29 assert(myObject.x == 5)
30 
31 -- A word about this strange colon: The following three lines are equivalent
32 myObject:doSomething()
33 myObject.doSomething(myObject)
34 MyClass.doSomething(myObject)
35 
36 -- As are these two definitions
37 function MyClass:doMore()
38  return 5
39 end
40 
41 function MyClass.doMore(self)
42  return 5
43 end

Control Structures

1 if condition then
2  doSomething()
3 end
4 
5 -- Loop over numbers
6 for i=min,max,step do
7  doSomething(i)
8 end
9 
10 -- Iterate over all entries in a table
11 for key, value in pairs(table) do
12  doSomething(key, value)
13 end
14 
15 -- Iterate over the consecutive numeric entries in a table
16 for i, value in ipairs(table) do
17  doSomething(i, value)
18 end