PeMt

Lua journey

ASCII art of Lua logo @ @@ @@ @ Lua @@

it has now occurred to me that using Lua along with Gemini is a great combo

Misc

What i find neat is that functions for each data type are grouped under global “table” of sorts. something akin to static class, providing static methods in traditional OOP languages.

Libraries

Making a library and including it is as easy as it is in Python, you just return the library table and then require the filename. When defining a non-local table inside a library, it is imported into global namespace.

Consider the following snippet inside foo.lua file:

bar = {}
local baz = {}

FOO = {
    bar = bar
    baz = baz,
}

return FOO

Later, when importing FOO:

local FOO = import("foo")

FOO.bar   -- table: 0x...
bar       -- table: 0x...
FOO.baz   -- table: 0x...
baz       -- nil

Thus the internal tables/variables of a libary can be made private or public to a global namespace

Multiple return

Lua has multiple return values and destructuring syntax (similiar to the one found in Golang and JS):

function square(a)
    return 4*a, a*a
end

local circum, area = square(3) --> 12, 9

Global table

Apparently you can alias stuff in lua just like that:

_G.echo = _G.print

echo "foo" -- will print "foo"

A peek inside the table

There is no way to check if an element is inside the table, so just for convenience I’ll put this here:

function table.has(t, v)
    for _, e in pairs(t) do
        if e == v then
            return true
        end
    end
    return false
end

function table.hask(t, k)
    for i in pairs(t) do
        if i == k then
            return true
        end
    end
    return false
end

local tab = {1, 2, 3, ["x"] = "foo"}
table.has(tab, 1)    --> true
table.hask(tab, "x") --> true
table.hask(tab, 4)   --> false

Templates

I kinda missed the templates from Golang, so here’s something really darn simple:

function render(str, t)
    str = string.gsub(str, "%(%( .(%w+) %)%)", function (a)
        if t[a] ~= nil then
            return t[a]
        end
        return ""
    end)
    return str
end

local s = "Hello (( .name ))"
render(s, { name = "Fred", age = 21 }) --> "Hello Fred"