Lua

Lua is a minimalist, dynamically typed, interpreted language. Like Python but way more portable and easy to inspect.

Basics

fib.lua

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

print("Enter a number:")
num = io.read("*number")
print(fib(num))
$ lua fib.lua
Enter a number:
5 # User input
8 # Lua's output

Types

There are 8 types in Lua:

Tables

Tables are very versatile, but in their way, a bit annoying. Tables are arrays, stacks, sets, bags, enums, dictionaries, and kind of everything all in one. Anything can be a key or value, except for nil.

Tables are natively 1 indexed.

-- Array / Stack
arr = { 1, 2, 3 }
-- Push / Insert
table.insert(arr, 2000) -- arr = { 1, 2, 3, 2000 }
table.insert(arr, #arr + 1, 10) -- arr = { 1, 2, 3, 2000, 10 }
table.insert(arr, 1, 5) -- arr = { 5, 1, 2, 3, 2000, 10 }
-- Pop / Remove
val = table.remove(arr) -- arr = { 5, 1, 2, 3, 2000 }; val = 10
val = table.remove(arr, 1) -- arr = { 1, 2, 3, 2000 }; val = 5

-- Set/Bag (Note the value at each index does not matter, as long as it is not `nil`)
set = { 1, 2, 3 }
-- Add
set[4] = true -- set = { 1, 2, 3, 4 }
set[4] = true -- Same result, is idempotent
-- Remove
set[1] = nil -- set = { 2, 3, 4 }
set[1] = nil -- Same result

-- Enums
enum = {
    "todo",
    "doing",
    "done"
}
task_progress = enum[1] -- "todo"

-- Dictionaries
dic = {
    TODO: 1,
    DOING: 2,
    DONE: 3
}
task_progress = dic.TODO -- "todo"
-- Anything can be a key or value
another_table = { 1, 2, 3 }
dic = {
    "key": "value",
    1: 2,
    another_table: "yeah"
}
print(dic[another_table]) -- "yeah"

References

  1. Programming In Lua

Last modified: 202401040446