Remix.run Logo
HellsMaddy a day ago

Global-by-default scoping was one of Lua's largest mistakes. I wish they'd fix it, but of course it would break backwards compat.

drcxd 20 hours ago | parent | next [-]

Strictly speaking, Lua is not global by default. All free names, that is, all names unqualified with `local`, is actually indexed from a table `_ENV`, which is set to `_G`, the global environment. So, all free names are effectively global by default, but you can change this behavior by put this line at the top of your file `local _G = _G; _ENV = {};`. This way, all free names are indexed from this new table, and all access to the global names must explicitly be accessed through `_G`, which is a local variable now. However, I have never seen such practice. Maybe it is just too complicated to accept that all free names are global variables and you have to explicitly make it local.

Fwirt 17 hours ago | parent [-]

Thanks to Lua’s great metaprogramming facilities, and the fact that _G is just a table, another workaround is to add a metamethod to _G that throws an error if you try to declare a global. That way you can still declare globals using rawset if you really want them, but it prevents you from declaring them accidentally in a function body.

kanbankaren 8 hours ago | parent | prev [-]

yeah. I hate typing `local` for every variable. I would prefer they introduce some syntactic sugar like `let`(to mean local variable) and `const`(to mean local and constant).

otikik 8 hours ago | parent [-]

“local” is the same as the “let” that you are describing, isn’t it? Just 2 chars longer.