Lua in a Nutshell: A Quick Tutorial for Lua

I'm reading source code written with Torch these days. Torch is a well-known deep learning framework written by Lua.

So I summarize the grammar of it and provide a quick tutorial here.

Run

As we know, Lua is a C-like language. Therefore, it is case-sensitive.

The following code outputs "Hello World" with Lua. Note that the semicolon at the end of a line is optional, like JavaScript.

print('Hello World')

You can use the interrupter of Lua in the command line:

➜  ~ lua
Lua 5.3.4  Copyright (C) 1994-2017 Lua.org, PUC-Rio
> print('Hello World')
Hello World
>

Also, you can run a Lua script with a file in the command line:

lua hello.lua

Grammar

Comment

-- This is a line comment
 
--[[
  This is a block
  comment
--]]

Variables

The numbers in Lua are all doubles with 64 bits. And you can use the following expressions:

num = 1024
num = 1.0
num = 3.1416
num = 314.16e-2
num = 0.31416E1
num = 0xff

You can use both double and single quotes for strings. For example:

str = 'Hello World'
str = "Hello World"

Also, escape characters still exist in Lua:

ch = '\a'
ch = '\t\n'

The following four lines define the same string:

a = 'abc\n123"'
a = "abc\n123\""
a = '\97bc\10\04923"'
a = [[abc
123"]]

The NULL in C is represented with nil in Lua. When you try to get values from undefined variables, it will return nil:

v = UndefinedVariable

false and nil represent false for a boolean value in Lua. Other values including 0 represent true for a boolean value.

By the way, all variables are global variables unless declared explicitly:

globalVar = 50
local localVar = 'local variable'

Control Statements

If-else Branches

if age == 40 and sex == 'Male' then
    print('40-year-old man is a flower (:')
elseif age > 60 and sex ~= 'Female' then
    print('The elder')
elseif age < 20 then
    print('Too young, too naive!')
else
    local age = io.read()
    print('Your age is '..age)
end

Besides if-else statements, we also present some other grammar of Lua:

  • The operator == tests for equality; the operator ~= is the negation of equality
  • The string concatenation operator in Lua is denoted by two dots ('..').
  • You can get stdin and stdout with read and write functions in io library

While Loop

sum = 0
num = 1
while num <= 100 do
    sum = sum + num
    num = num + 1
end
print('sum = ', sum)

For Loop

The following code calculates the sum of integers from 1 to 100:

sum = 0
for i = 1, 100 do
    sum = sum + i
end

The following code calculates the sum of odd numbers from 1 to 100:

sum = 0
for i = 1, 100, 2 do
    sum = sum + i
end


The following code calculates the sum of even numbers from 1 to 100:

sum = 0
for i = 100, 1, -2 do
    sum = sum + i
end

Repeat Loop

sum = 2
repeat
   sum = sum ^ 2 -- Equivalent to sum = sum * sum
   print(sum)
until sum >1000

Functions

Recursion

function fib(n)
  if n < 2 then return 1 end
  return fib(n - 2) + fib(n - 1)
end

Closure

function newCounter()
    local i = 0
    return function()     -- anonymous function
        i = i + 1
        return i
    end
end
  
c1 = newCounter()
print(c1())  --> 1
print(c1())  --> 2

And here's another example:

function myPower(x)
    return function(y) return y^x end
end
  
power2 = myPower(2)
power3 = myPower(3)
print(power2(4)) --> 4^2
print(power3(5)) --> 5^3

The Return Values of Functions

Like Python, you can assign multiple values in one statement, for example:

a, b, c = 1, 2, 3, 4

Please note that the fourth value will be ignored since there're only three variables.

The functions in Lua can return multiple values:

function f(x)
    print(x)
    return 1, 2, 3
end
 
a, b, c, d = f()

The output in line 2 will be nil because x is not assigned a value when f() is invoked. Also, the variable d in line 6 will also be nil.

Table

Actually, Table is a key-value data structure, as known as Map in other programming languages. We can define a new Table as following:

hzxie = {
    name = "Haozhe Xie",
    email = "cshzxie@gmail.com",
    homepage = "https://haozhexie.com"
}

And you can get or set values as follows:

print(hzxie.name)
hzxie.name = nil

You can also define a Table in following ways:

anotherTable = {
    [20] = 10,
    ['name'] = "Haozhe Xie"
}

And then, you can access values in anotherTable in a more map-like way:

local v20 = anotherTable[20];
print(anotherTable['name'])

Now, let's look at arrays.

arr = {10, 20, 30, 40, 50}

It is equivalent to:

arr = {[1] = 10, [2] = 20, [3] = 30, [4] = 40, [5] = 50}

Please note that the index starts from 1 instead of 0 in Lua.

In addition, you can put different types of variables to an array:

arr = {"Say Hello", 2, function() return "to a function." end}

And you can invoke the function in the array with arr[3]().

You can traverse values in an array as follows:

for i=1, #arr do
    print(arr[i])
end

where the #arr represents the length of the array.

As mentioned above, if you declare a variable without local, it will be a global variable. All global variables will be stored in a Table named _G. Suppose there is a global variable named globalVar, you can access this variable in following ways:

_G.globalVar
_G['globalVar']

You can traverse values in a table as follows:

for k, v in pairs(t) do
    print(k, v)
end

Meta Tables and Meta Methods

Metatables and Metamethods are one of the most important grammars in Lua. Metatables allow us to change the behavior of a table. For instance, using metatables, we can define how Lua computes the expression a + b, where a and b are tables. Whenever Lua tries to add two tables, it checks whether either of them has a metatable and whether that metatable has an __add field. If Lua finds this field, it calls the corresponding value (the so-called metamethod, which should be a function) to compute the sum.

For example, we have two fractions with values of 2/3 and 4/7:

fraction1 = {numerator=2, denominator=3}
fraction2 = {numerator=4, denominator=7}

And we are about to add them together. However, we cannot add them together with the operator +. But we can make it with metamethods:

fractionOperations={}
function fractionOperations.__add(f1, f2)
    ret = {}
    ret.numerator = f1.numerator * f2.denominator + f2.numerator * f1.denominator
    ret.denominator = f1.denominator * f2.denominator
    return ret
end
 
setmetatable(fraction1, fractionOperations)
setmetatable(fraction2, fractionOperations)

And now, you can add them together as follows:

frac = fraction1 + fraction2

The __add metamethod corresponds to the operator +. Other metamethods are listed as following:

__add(a, b)               -> Corresponds to a + b
__sub(a, b)               -> Corresponds to a - b
__mul(a, b)               -> Corresponds to a * b
__div(a, b)               -> Corresponds to a / b
__mod(a, b)               -> Corresponds to a % b
__pow(a, b)               -> Corresponds to a ^ b
__unm(a)                  -> Corresponds to -a
__concat(a, b)            -> Corresponds to a .. b
__len(a)                  -> Corresponds to #a
__eq(a, b)                -> Corresponds to a == b
__lt(a, b)                -> Corresponds to a < b
__le(a, b)                -> Corresponds to a <= b
__index(a, b)             -> Corresponds to a.b
__newindex(a, b, c)       -> Corresponds to a.b = c
__call(a, ...)            -> Corresponds to a(...)

Object-oriented Programming

There is a function named __index in metamethods. If you want to make b as a property of a, you can do as following:

setmetatable(a, {__index = b})

And here's another example:

WindowPrototype = {x=0, y=0, width=100, height=100}
MyWindow = {title="Hello"}
setmetatable(MyWindow, {__index = WindowPrototype})

When indexing a key in a table, Lua firstly finds it in the table. If the key not exists, it will invoke the __index() function.

Now, let's talk about object-oriented programming:

Person={}
  
function Person:new(p)
    local obj = p
    if (obj == nil) then
        obj = {name = "Haozhe Xie", handsome = true}
    end
    self.__index = self
    return setmetatable(obj, self)
end
  
function Person:toString()
    return self.name .." : ".. (self.handsome and "handsome" or "ugly")
end

Now we can create objects of Person class:

me = Person:new()
print(me:toString())
 
someone = Person:new{name="Someone", handsome=false}
print(someone:toString())

The following code gives an example of inherit in Lua:

Student = Person:new()
  
function Student:new()
    newObj = {stuId = "15S103172"}
    self.__index = self
    return setmetatable(newObj, self)
end
  
function Student:toString()
    return "Student : ".. self.stuId.." : " .. self.name
end

Modules

We can include other lua scripts with the function require(). Once a script is loaded, it will be executed automatically.

For example, we have a Lua script named hello.lua with following content:

print("Hello, World!")

Once we use require("hello"), you will get "Hello, World" on your screen. Please note that the script will be executed ONLY once no matter how many times you require this script.

If you want the script to be executed every time, you can use dofile function instead. And if you want to load a Lua script without being executed, you can use loadfile function.

You can use it as follows:

local hello = loadfile("hello")
-- Do something...
hello()

Here's a more standard example:

File Name: MyModel.lua

local MyModel = {}
  
local function getname()
    return "Haozhe Xie"
end
  
function MyModel.greeting()
    print("Hello, My name is "..getname())
end
  
return MyModel

And we can load the model above as follows:

local myModel = require("MyModel")
myModel.greeting()

Actually, the require() function works as follows:

local myModel = (function ()
  -- The content of MyModel.lua --
end)()

References

  • https://www.lua.org/pil/
  • https://coolshell.cn/articles/10739.html
Contact Us
  • Room 614, Zonghe Building, Harbin Institute of Technology
  • cshzxie [at] gmail.com