Lua Introduction

by "Blag" - Senior Developer Evangelist

Return to Geeky Thursday

What is Lua?


Lua is a lightweight multi-paradigm programming language designed as a scripting language with extensible semantics.


It's cross-platform since it's written in ANSI C.


Lua is free and Open Source.


It's extensively used in the Gaming Industry due to it's easiness to embed, fast execution and short learning curve.

How to install Lua?


On Linux it can be as easy as this...


sudo apt-get install lua5.2


For other systems...you can simply grab a binary from Lua Binaries

Who uses Lua?


  • Adobe -> Photoshop Lightroom, uses Lua for its user interface.
  • Artweaver -> Scripting filters.
  • Cisco -> Dynamic Access Policies within the Adaptive Security Appliance.
  • MySQL -> MySQL Workbench extensions and add-ons.
  • Blizzard -> Extensions for World of Warcraft.
  • Mercedes-Benz -> Not specified.

Starting out...


Once Lua is installed, we can simply call it from the terminal


Package Management


We can easily get new packages on Lua using Lua Rocks


For Windows...follow the instructions

For Linux do this...

wget http://luarocks.org/releases/luarocks-2.2.2.tar.gz

tar zxpf luarocks-2.2.2; cd luarocks-2.2.2

./configure; sudo make bootstrap


Once installed...do this to install a package

sudo luarocks install luasocket

Basic Concepts


One line comments are -- and multiple lines comments are --[[ and --]].


Precedence must be enforced by parenthesis


				
print(2*3+5)

11


print(2*(3+5))

16
				

Basic Concepts


Printing on the screen is easy...


				
text = "This is Lua!"



print(text) 



This is Lua!
				

Variables can have multi-assignments...


				
a, b, c = 1, 2, 3

print(a,b,c)

1     2     3
				

Data Structures


The only data structure in Lua is called "Table"...

				
tab = {}

table.insert(tab, {Name="Blag", Age=37})



for _,tab in pairs(tab) do

    print (tab.Name .. " ==> " .. tab.Age)

end



Blag ==> 37
				

				
tab = {3,1,4,2,5}



table.sort(t)



for _,t in pairs(tab) do

    print(t)

end


1

2

3

4

5
				

Tables are flexible enough to represent other data structures...

				
intArray = {1, 2, 3}				



intArray = {}

for i=1,3 do

    intArray[i] = i

end



stringArray = {"This","is","Lua!"}
				

By convention...arrays start from index 1...

Multidimension Arrays are easy too...


				
multiArray = {}

for i=1,2 do
  
  multiArray[i] = {}  --Creates a new row
  
  for j=1,3 do
  
      multiArray[i][j] = 0
  
  end    

end
				

Another way...


				
multiArray = {}

for i=1,2 do
  
  for j=1,3 do
  
      multiArray[i * 3 + j] = 0
  
  end    

end
				

Dictionary

				
myDict = {one = 1, two = 2}


print(myDict.one)


1


myDict.three = 3


myDict.two = nil


for x in pairs(myDict) do

    print (myDict[x])

end


3

1
				

Functions

Functions must always return a value...


				
function Hello(name)

    return ("Hello " .. name)

end



print(Hello("Blag"))



Hello Blag

				

But they can return more than one value...


				
function Hello(name)

    return ("Hello " .. name), 
    
           ("and Goodbye " .. name)

end



a, b = Hello("Blag")



print(a, b)



Hello Blag     and Goodbye Blag
				

Fibonacci List


Finally...we're going to make our first application...


So grab your favorite text editor and get ready...


Name your file "Fibonacci.lua"


				
function fib(num,a,b)

    local result = ""

    if a > 0 and num > 1 then

        result = result .. (a+b) .. " " .. 
        
                 fib(num-1,a+b,a)

    elseif a == 0 then

        result = a .. " " .. b .. " " .. 
        
                 (a+b) .. " " .. fib(num-1,a+b,b)

    end

    return result

end
				
				
io.write("Enter a number: ")

num = tonumber(io.read())

print(fib(num,0,1))
				

Open the Terminal and go to your source code folder...

lua "Name_of_File.lua"


When we run it we're going to see...

Making an LED Number App


This is one of my favorite codes of all time...


Name your file "LED_Numbers.lua"


				
local function split(s,delim)

    local result = {}

    for match in (s..delim):gmatch("(.-)"..delim) do

        table.insert(result,match)

    end

    return result

end
				
				
leds = {[0] = " _  ,| | ,|_| ",
	
        [1] = "  ,| ,| ",
        
        [2] = " _  , _| ,|_  ",
        
        [3] = "_  ,_| ,_| ",
        
        [4] = "    ,|_| ,  | ",
        
        [5] = " _  ,|_  , _| ",
        
        [6] = " _  ,|_  ,|_| ",
        
        [7] = "_   , |  , |  ",
        
        [8] = " _  ,|_| ,|_| ",
        
        [9] = " _  ,|_| , _| "}
				
				
io.write("Enter a number: ")

num = io.read()

for i = 1, 3 do

    for j = 1, #num do

        line=split(leds[tonumber(string.sub(num,j,j))]
        
                   , ",")

        io.write(line[i])

    end

	print("")

end

print("\n")
				

When we run it we're going to see...


Random Names


This App will generate 100,000 random names using two 16 elements arrays


We will measure the runtime


Name your file "Random_Names.lua"


				
nClock = os.clock()



local names={"Anne","Gigi","Blag","Juergen","Marek",
	
             "Ingo","Lars","Julia", "Danielle",
             
             "Rocky","Julien","Uwe","Myles","Mike",
             
             "Steven","Fanny"}



local last_names={"Hardy","Read","Tejada","Schmerder",

                  "Kowalkiewicz","Sauerzapf","Karg",

                  "Satsuta","Keene","Ongkowidjojo",

                  "Vayssiere","Kylau","Fenlon",

                  "Flynn","Taylor","Tan"}
                  

                  
local full_names={}                  
				
				
for i = 1, 100000 do

    table.insert(full_names,names[math.random(16)] .. 
    
                 " " .. last_names[math.random(16)])

end



print("Time: " .. os.clock() - nClock)
			

When we run it we're going to see...

How this behaves in Python?

And in Julia?

Decimal to Romans


This App will create a Roman Numeral based on a decimal number


This will include some nice commands...


Name your file "Decimal_to_Roman.lua"


				
local Roman_Table = {[1000] = "M", [900] = "CM", 
	
                     [500] = "D", [400] = "CD", 
                     
                     [100] = "C", [90] = "XC", 
                     
                     [50] = "L", [40] = "XL", 
                     
                     [10] = "X", [9] = "IX", 
                     
                     [5] = "V", [4] = "IV", 
                     
                     [1] = "I"}
			
				
local function Sort_Romans(Table)

local tab = {}

    for k, v in pairs(Table) do

        table.insert(tab,{key=k,value=v})

    end

table.sort(tab, function(A, B) 

           return A.key > B.key end)

return tab

end
			
				
local function Roman_Number(number, Sorted_Table)

local result = ""

    while number > 0 do

        for _,tab in pairs(Sorted_Table) do

            if number >= tab.key then

                result = result .. tab.value

                number = number - tab.key

                break

            end

         end

    end

    return result

end
				
				
io.write("Enter a number: ")

num = io.read()

Sorted_Table = Sort_Romans(Roman_Table)

result = Roman_Number(tonumber(num), Sorted_Table)

print(result)
				

When we run it we're going to see...


Count Letters


In this example we're going to read a file and count how many time a letter appears...


Call your file "countletters.lua" (all in lowercase).


Create a file called "readme.txt" with the following text...


"This is a text file that we're going to read it using Lua"


				
file = io.open("readme.txt", "r")

line = file:read()

local counter = {}

for letter in string.gmatch(line,"%w") do

    counter[letter] = (counter[letter] or 0) + 1

end

for key,value in pairs(counter) do

    print(key,value)

end

file:close()
			

When we run it we're going to see...


Giving Lua some LOVE


LOVE is framework to create 2D games in Lua...


You can get it from here...Download LOVE

Once installed, we can create our example...


We're going to need to files...one called main.lua and the other config.lua

				
function love.load()

    local myfont = love.graphics.newFont(45)
    
    love.graphics.setFont(myfont)
    
    love.graphics.setColor(0,0,0,225)
    
    love.graphics.setBackgroundColor(255,153,0)
    
end



function love.update()

end



function love.draw()

    love.graphics.print('Hello World!', 70, 150)

end
				
				
function love.conf(w)

    w.window.width = 400
    
    w.window.height = 400
    
    w.window.title = "Lua's Love"
    
end
				

We need to zip both files and then change the extension to .love


That's it for now


Lua is a nice and interesting language


But there's not really much to say about it...it's simplicity makes it easy enough to learn...


Contact Information


Blag --> blag@blagarts.com

@Blag on Twitter

Go back home...