lua-users home
lua-l archive

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


On 7 July 2010 22:44, RJ Russell <russellsprouts2@gmail.com> wrote:
> Here's one way to avoid the issue in code like this and get rid of the
> globals problem.
> a=1 --auto local
> do
>   a=2
>   --is this a new global?
> end
> print(a) --what is it?
>
> add one new keyword, global, and keep the local keyword.
> Everything is local by default, not overriding any already existing locals,
> but the global keyword makes a global, and the local keyword creates a new
> one.

'Local by default' has problems, though. If you prevent implicit
locals from shadowing outer ones, as you suggested, it becomes easy to
introduce certain types of bugs:

function f()
  ... lots of code here ...
  ... and more ...

  local function g()
    a = 1
    ... do some stuff with a ...
  end
end

Now you have the problem that if, during maintenance, you declare a
variable that happens to be called 'a' in f, or outside f even, scopes
change and g breaks subtly.

Another alternative, making inner locals implicitly shadow outer ones,
as python does it, has other problems which make closures unable to
mutate captured variables.

IMO explicit declarations are a good thing because they clarify
scopes. I would love for all variables would be statically and
lexically scoped, so that the compiler could generate compile-time
error messages for undeclared variables. That requires that you be
able to statically determine module imports, though. (maybe it could
be done with metalua)

    henk