Learning Lua: The Basics

First of all, what is Lua? Lua in Portufuese means moon. According to the official website, Lua is a powerful, efficient, lightweight, embeddable scripting language. It supports procedural programming, object-oriented programming, functional programming, data-driven programming, and data description.

For me the first reason to learn Lua, was to make games in LÖVE. And in fact it is a very streamlined and a lightweight programming language.

It was primarily for embedded use (not to be confused with embedded systems) in host applications. But over the years it became really popular in game industry as a language to glue things together.

I was inspired by a similar article written for python by TK.

The Basics


Variable


Variable, imagine them as buckets that hold some value in them. Lua has to two types of variables, global and local:

    x = 55         -- global variable
    local y = 1    -- local variable

The local variables exist only within a scope.

You don't have to specify the data type of the variable. Lua will figure it out on it's own.

    a = 10                      -- number
    b = 9.0                     -- number
    c = "Hello, World"          -- string
    d = false                   -- boolean
    e = {1,2,3}                 -- table
    f = nil                     -- nil

Control flow: conditional statements


If statements check whether a condition is True or False. If true, the instructions under will be performed.

    if true then
        print("Hello Lua if")
    end

    if 5 > 2 then
        print("5 is greater than 2")
    end

Since the 5 is greater than 2, the print statement will be executed.

The else statement will be executed if the if condition is false.

    if 3 > 5 then
        print("3 is greater than 5")
    else
        print("3 is smaller than 5")
    end

Sometimes a choice has to be made. Sometiems we need to make a choice more than once. that's where we need elseif.

    if 5 < 2 then
        print(""5 is smaller than 2)
    elseif 5 < 7 then
        print("5 is smaller than 7")
    else
        print("5 is neither smaller than 2 nor greater than 7")
    end

Looping


Here I'll discuss the for and while loop implementations in Lua.

In the "While" loop, if the condition inside the while statement is true then the code will be executed.

    local i = 1
    while a[i] > 50 do
        print(a[i])
        i = i + 1
    end

While loops need a condition, here the condition is a[i] > 50 as long as that is True, it'll keep running.

We have two types of For loops. A Numeric one, and a generic one.

First, the Numeric For loop. They need a starting range, and ending range and optionally a step. When step is not provided Lua automatically assumes an increment of 1.

    for var=starting_point,ending_point,step do
        something
    end

Let's see an example of this.

    for i=10, 0, -2 do
        print(i)
    end

Output

    10
    8
    6
    4
    2
    0

The Generic For loop.

    -- print all element of an array
    array_name = {1,2,3,55,66,77}
    for key,value in ipairs(array_name) do
        print(value)
    end

Output

    1
    2
    3
    55
    66
    77

Tables


Tables in Lua are not a data structure. They are the data structure. With Tables you can implement arrays, lists, dictionery etc.

So, let's try to implement these data structures using Tables.

Arrays


In Lua you don't have to specify the size of the array at the moment of initialisation.

    array = {}
    for i=1, 100 do
        array[i] = 0
    end

If you try to access anything out of the range of 1-100, it will return nil.

Create arrays srtarting from -10 to 10.

    array = {}
    for i=-10, 10 do
        array[i] = 0
    end

We can also use constructors to create arrays in single statement.

    array = {1, 2, 3, 55, 43, 67, 99}

Multi-Dimension Array


Now we'll create a MxN array using Tables.

    array = {}          -- create the matrix
    for i=1,M do
      array[i] = {}     -- create a new row
      for j=1,N do
        array[i][j] = 0
      end
    end

Dictionery


Python users will recognise this word easily. Time to implement dictionery in Lua.

    a = {}     -- create a table and store its reference in `a'
    k = "x"
    a[k] = 10        -- new entry, with key="x" and value=10
    a[20] = "great"  -- new entry, with key=20 and value="great"
    print(a["x"])    --> 10
    k = 20
    print(a[k])      --> "great"
    a["x"] = a["x"] + 1     -- increments entry "x"
    print(a["x"])    --> 11

Now let's look at how we'll print the key values pairs..

-- setting up our dictionery
    dict = {}
    dict["a"] = 111
    dict[20] = "Hello, Lua"
    dict[6.0] = 66.66
    dict["Why tho"] = "Another string"

    -- printing our dictionery
    for key, value in pairs(dict) do
        print(key, value)
    end

That's it

Congratulations you have learnt the basics of the Lua.

Keep on learning.

My Instagram, Twitter and GitHub.

AUTHOR

READ NEXT

Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?