lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

On Mon, Jun 4, 2012 at 1:38 PM, Dirk Laurie <> wrote:
> 2012/6/4 Axel Kittenberger <>:
>> Yes, I'm convinced, implicit locals are a bad thing, but I never
>> really got why we need an implicit anything, I know one can hack _G
>> but anyway, never understood why someone thought implicit globals are
>> a good thing to begin with. It does require some deeper experience
>> into the language to hack it away again.
> I've attached a solution, slightly modified from `strict.lua`.
> Sample session:
> $ lua
> Lua 5.2.0  Copyright (C) 1994-2011, PUC-Rio
>> require"fascist"
>> a=1
> stdin:1: assign to undeclared variable 'a'
> stack traceback:
>        [C]: in function 'error'
>        ./fascist.lua:25: in function '__newindex'
>        stdin:1: in main chunk
>        [C]: in ?
>> global{a=1,b=2}
>> b=3
>> liberate()
>> x=10

I think people tend to forget about a powerful capability of Lua that
requires implicit globals: you can use metatable/_ENV magic to make
your "globals" not really global. strict.lua and fascist.lua show one
use of this (you can implement explicit globals if you like using this
kind of wizardry); another use is to be able to write simple config
files like:
doThings = true
doMoreThings = OnlyOnTuesdays
hostname = 'yuki'
ports = {27, 42, 69}

If you were using explicit globals, you'd have to either use a more
verbose syntax (options.doThings = true) or declare all of the options
as "global", when they really aren't because you loaded this chunk
with a different environment. It'd be very confusing. (You can even
add verification to e.g. prevent someone from assigning to
OnlyOnTuesdays, i.e. pseudo-constants, or validate the option values
as they're defined...)

Really, does Lua 5.2 even have "global" variables anymore? Unless I'm
misunderstanding, anything not declared "local" is looked up in _ENV,
which can be redefined at will, and may or may not be accessible from
higher scopes.

Sent from my Game Boy.