Also, it’s possible to force global variables to be explicitly declared.
function declare(name)
rawset(_G,name,false)
end
function exists(name)
if rawget(_G,name) ~= nil then
return true
else return false end
end
setmetatable(_G, {
__newindex = function(self,x) error("Undeclared global " .. x) end,
__index = function(self,x) error("Undeclared global " .. x) end
})
And now declare("foo")
foo = 1
-- Create name if it hasn’t
-- been declared yet
if not exists("name") then
declare("name")
name = 1
end
More discussion: https://lua.org/pil/14.2.html
That is neat how that's possible to do! It would be nice if it would just do local by default as well. Basically swap the defaults: everything is local and only what's explicitly global is global? I realize it's not an easy thing to change at this point in the game. Maybe some compile pragma or another extension could help? But it should be a new default in a modern language.