lua-users home
lua-l archive

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

Since the last time the local/global discussion came up, I've been
thinking about it alot as well. I sometimes feel that the "implicit"
globals can cause trouble, however, I _like_ the more structured idea of
"declaring" local variables. 

I agree that doing "global varname = <stuff>" would make using Lua very
troublesome. One might decide to make global variables work without a
preface at the "top" level, but yet require a global declaration in
functions. However, this introduces two different syntax for the same
operation (IMHO bad).

I've come to the following conclusions:

  - The current style for implicit globals and declared locals is
    simple, and achieves the goal of making Lua an easy to use,
    and powerful configuration and extension language. 

  - It would be useful, _at times_, to require that global variable
    access within functions be declared specifically. By this, I 
    mean that NO undeclared variable access from within a 
    function would be valid. One would do:

       function boo()
                 local a,b,c;
                 global p,q,r;

                 a = p; b = q; c = r;  -- valid
                 z = 2; -- parse level error

    I also realize that this would only be desirable for advanced
    programmers working on the supoprting code of their system.
  - I think the introduction of the keyword "method" (as suggested)
    would be a BAD idea. There is already some confusion in 
    beginning users about the "exposed" method syntax. (i.e. how
    function a_name(self,a,b)   ==   function tbl:a_name(a,b) )
    I think that adding a keyword method which had the same properties
    would confuse things, primarily because of the connotations
    that "method" is going to hold for programmers familiar with
    class based programming.

So my solution would be to add another directive like "$debug$" which
would tell the parser to turn on strict variable declaration syntax. I
would have to decide if this strict syntax would be required for the
"main()" body of code (i.e. top level code in a lua file) while this
directive was on.

** run-time solution

An acceptable run-time solution for me would be to prevent accidental
global variable creation or destruction. All global variables would be
created or destroyed through functions, and access to them would remain
the same as it is now. However, this would prevent any existing code
relying on the old behavior from working.


  a = 3; -- valid
  b = a; -- valid

  a = nil; -- valid,  the name is still valid, even if the variable is nil
  a = 4;   -- valid

  c = 5; -- invalid (run-time error)


  a = 3; -- invalid (run-time error)

end ex.

I believe this should be easy to achieve using tag methods similar to
those described to implement the previous solution.

David Jeske (N9LCA) + +