2021-06-15

Lua notes

To declare a local variable use the local keyword: local x = 123

TODO

Assignment

x, y = 100, 200

-- Swap:
x, y = y, x

Logical operators

AND, OR, NOT

Strings

String concat

s = "hello" .. " " .. "world"

Tables

Most things in Lua are tables.

Declaring a table: val = {}.

val = {}

val["abc"] = 123
print(val.abc)

val[1] = 5
print(val[1])

Init tables:

tab = {
    a=1,
    ["hi there"] = 123
}

List: list = { 1, 3, 5, 7 }

Loops

break will break a loop.

For:

list = {2, 3, 4}
for index,value in ipairs(list) do
    print(value)
    print(index)
end

Control flow

If:

if expr then
end

While:

while true do
end

Repeat:

repeat
    -- body
until true

For:

--  initial  target  step
for x=10,    0,      -1 do
    print(a)
end

IO

val = io.read("*number") reads user input and converts it to a number. If the number is not valid, then val is nil.

REPL

dofile("myfile.lua") will reload and run the file.

Functions

Variadic function:

function vary (...)
    local args = {...}

    for _, val in ipairs(args) do
        print(val)
    end
end

Named arguments:

```lua
function namey (args)
    print(args.a)
    print(args.b)
end

namey { a = 100, b = 101 }

Anonymous functions:

fun = function ()
    print("this is fun")
end

fun()

Non-global functions (pretend namespaces)

lib.lua

MyLib = {}

function MyLib.doThing ()
    print("I did things")
end

main.lua

require("lib")
MyLib.doThing()