Skip to content

Instantly share code, notes, and snippets.

@coderofsalvation
Last active October 21, 2022 06:26
Show Gist options
  • Save coderofsalvation/b41ae138700e4f31c63e05d61b550a09 to your computer and use it in GitHub Desktop.
Save coderofsalvation/b41ae138700e4f31c63e05d61b550a09 to your computer and use it in GitHub Desktop.
My favorite lua patterns

Useful Lua Patterns/Functions

NOTE: for JS patterns see my JS patterns-page

Simple javascript-like template function

-- print( tpl("${name} is ${value}", {name = "foo", value = "bar"}) )
-- "foo is bar"
function tpl(s,tab)
  return (s:gsub('($%b{})', function(w) return tab[w:sub(3, -2)] or w end))
end

Hierarchical log

print("doFoo()")
print(" └☑ doBar()")
print("   ├☑ doBar()")
print("   └☒ doBaz(): foo happened")

Random hash

function randomHash()
  return os.tmpname():gsub("^/tmp/lua_", "") 
end

foreach

--- foreach( {"a","b"}, function(v) print(v) end )
function foreach(table, f)
  if table ~= nil then 
    for k, v in pairs(table) do f(k, v) end 
  end
end

count items in (object) table

function count(table) local i = 0 ; for k, v in pairs(table) do i = i + 1 end ; return i end

require_if_exist

function require_if_exist(file)
  local f = io.open( file .. ".lua","r")
  if f ~= nil then 
    f:close()
    return require(file)
  else return false end
end 

expose functions to global (evil but useful for 'foreach' e.g.)

-- a special syntax sugar to export all functions to the global table
local util = { foreach=foreach }

setmetatable(util, {
    __call = function(t, override)
        for k, v in pairs(t) do
            if rawget(_G, k) ~= nil then
                local msg = 'function ' .. k .. ' already exists in global scope.'
                if override then
                    rawset(_G, k, v)
                    print('WARNING: ' .. msg .. ' Overwritten.')
                else
                    print('NOTICE: ' .. msg .. ' Skipped.')
                end
            else
                rawset(_G, k, v)
            end
        end
    end,
})

collections

require 'collection'

data = {
    {name = 'Liam', language = 'Lua'},
    {name = 'Jeffrey', language = 'PHP'}
}
collect(data):pluck('name'):all()

see https://github.com/ImLiam/Lua-Collections

string functions

require "stringlib"
s = "   hello world  "
s = s:trim():replace('h', 'y')
--- "yello world"

see https://github.com/Badgerati/StringLib

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment