Declaring Global Variables

  • They do not need to be declared, declared when used
  • Can cause errors (a typo will cause a global variable)

Setting a metatable on _G to give errors when globals are nil

setmetatable(_G, { __newindex = function (t, n, v) local w = debug.getinfo(2, "S").what if w ~= "main" and w ~= "C" then error ("attempt to write to undeclared variable " .. n, 2) end rawset(t, n, v) end, __index = function(_, n) error("attempt to read undeclared variable " .. n, 2) end }) -- a = 9 print(a)

  • The problem with the above is that a new variable that is initialize to nil cannot be set
    • Without using rawset(table, key, value)
  • This metatable also effects the entire program including standard libraries