Basics of Lua

Posted on May 30, 2016

Lua, lua basics

My motivation for writting this post is to give a quick introduction of Lua programming language which would help people in getting started with Torch quickly.

Introduction

Lua is a lightweight multi-paradigm programming language designed primarily for embedded systems and clients. It is cross-platform since it is written in ANSI C and has a relatively simple C API.

Concepts


Comments in Lua

one line comment is written in Lua by preffixing -- to the comment. While multiline comment is enclosed in [[ ]].

-- one line comment in Lua
[[ multiple line comment
in Lua ]]

Data structures in Lua

Lua has only two data structure doubles and tables. Table is a structure that allows us to store multiple values and can be used as a dictionary as well as a list. It’s also used for creating new type of objects in Lua.

-- doubles
var = 5 -- variables are global by default
local var2 = 5 -- this is a local variable

-- tables
dict = {a = 1, b = 2, c = 3, d = 4} -- a simple dictionary
list = {1,2,3} -- a simple list

-- two ways to display the same value
print(dict.a)
print(list[1]) -- IMPORTANT: note that the lists are 1-indexed!

Control flow statements in Lua

-- use of for loop and control statements
for i=1,10 do
  if i == 1 then
    print("uno")
  elseif i == 2 then
    print("dos")
  else
    print("something else")
  end
end

val = 1
while val < 10 do
  val = val * 2
end

Functions in Lua

function add(a, b)
  return a + b
end

print(add(7, 3)) -- prints 10

There is an interesting thing. In Lua we can define functions within tables.

tab = {1, 2, 3}
function tab.sum ()
  c = 0
  for i=1,#tab do
    c = c + tab[i]
  end
  return c
end

print(tab:sum()) -- displays 6 (the colon is used for calling methods)

Input/Output in Lua

I/O on file:

myfile = io.open("doc.txt", "w")
for line in io.lines("~/input.txt") do
  myfile:write(line + "\n") -- write on file
end

I/O on stdin and stdout:

input_val = io.read()
io.write("You entered: " .. input_val + "\n")
-- alternatively: print ("You entered: " .. input_val)

Hope this provides a good base for using torch.