2 ms·
While you're right that "global by default" is usually a problem, it isn't in Lua, because Lua also lets you restrict the global scope (with i.e. setfenv). Gene
by silentbicycle 17y ago
While you're right that "global by default" is usually a problem, it isn't in Lua, because Lua also lets you restrict the global scope (with i.e. setfenv). Generally, the "global" scope you get by default is "global to the current module", i.e., publicly exported from a module.
It's still not a problem if your whole program is in one file, though. Since the global environment is just another table, you can set its metamethods to warn about any accidentally global vars. This is an example in PiL, and strict.lua is included in the standard Lua distribution. require "strict", problem solved.
The Lua designers know that unrestricted global-by-default vars cause a lot of pain in Awk, but defaulting to local scope for everything instead can make using closures awkward (as in Python), since it's difficult to know automatically where variables are local to. In the other languages you mention, C doesn't have proper lexical scoping, Scheme and Common Lisp have fully parenthesized syntax (and thus no scoping ambiguity), Python's closures are awkward, and Haskell (and ML) use let blocks and other explicit scope markers. This is a semantic issue in any language where you can nest blocks and the default is a series of statements, not individual statements (i.e., "begin" / "progn" is the default).
See also: http://lua-users.org/wiki/LocalByDefault http://lua-users.org/wiki/LocalByDefault