top | item 46355610

(no title)

cturtle | 2 months ago

One of the new features I found interesting, declarations for global variables, is buried in the reference manual. Here's a link to the section that discusses it: https://www.lua.org/manual/5.5/manual.html#2.2

discuss

order

HellsMaddy|2 months 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|2 months ago

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.

kanbankaren|2 months ago

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).

rhelz|2 months ago

Why did you find this interesting?

kevin_thibedeau|2 months ago

It indicates paving the path for local scoping in a future release where Lua 5 code is upgraded with global declarations to keep it working.

embedding-shape|2 months ago

For me it's interesting because global variable declarations haven't been needed before, so why now? Also, I'm not sure `global` was reserved before, but now it seems to be.