explicit typosafe globals

133 views
Skip to first unread message

Rett Berg

unread,
Sep 19, 2024, 9:19:02 AM9/19/24
to lu...@googlegroups.com
I just wanted to let everyone know that IMO the biggest wart of Lua (implicit globals) is actually trivial to solve via below or using pkglib[1] which just does what is below.

local M = {} -- some module

-- create a type for NOT throwing errors when G.foo is used explicitly
M.G = setmetatable({}, {
  __name='G(init globals)',
  __index    = function(_, k)    return rawget(_G, k)    end,
  __newindex = function(g, k, v) return rawset(_G, k, v) end,
})

-- error function
local noG = function(_, k)
  error(sfmt(
    'global %s is nil/unset. Initialize with G.%s = non_nil_value', k, k
  ))
end

-- define method for explicit access
G = G or M.G
-- override _G (globals table) to throw error on undefined access
setmetatable(_G, {__name='_G(globals)', __index=noG, __newindex=noG})

Best,
Rett

Rett Berg

unread,
Sep 19, 2024, 9:24:09 AM9/19/24
to lua-l
agh smt is just "string.format" -- sorry about that!
Reply all
Reply to author
Forward
0 new messages