lua-users home
lua-l archive

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


"global in nil" means no accidental globals: every variable needs a declaration,
either local or global. However, "global in nil" is very restrictive. For
instance, to use the sine function you'd have to write "global math" so that
you can then write "math.sin(x)". Or write "global math; global sin in math",
so that you can then write "sin(x)".

"global in {}" means all undeclared variables are stored in an anonymous table;
there can be accidental reading or writting of "real" globals. So, they are
(almost) local variables in this sense, except that access to them is still
via indexing a table (not a fast array, as locals are).

In general, the syntax is "global a,b,c in T" where a,b,c are names and T is
an expression that is evaluated at runtime. Access to a,b,c is translated to
TT.a, TT.b, TT.c, where TT is the value of T.

If the "in T" part is omitted, then the current global table (at runtime)
is used. If the name list is omitted, then all undeclared variables are routed
to T.

Several "global" declarations can be active at any moment. The latest one
that fits an undeclared name is used. For instance, the code

 global a,print
 local T={b=2}
 local S={c=3}
 a=10 b=20 c=30 d=40
 do
  global in T
  global c in S
  a=1
  d=4
  print(a,b,c,d)
 end
 print(a,b,c,d,T.d)

outputs

 1	2	3	4
 1	20	30	40	4

that is, in the first print statement, a is a "real" global, because it has been
declared global; b and d are got from T, because that's the default in the
do-end block; c is got from S, because it has been explicitly declared so. Note
that none of this affects the values of b,c,d, which are global outside the
do-end block, but a 'd' has been added to T.

Finally, note that there are subtle details here: S must be declared explicitly
as local (or global); otherwise, since it's used after "global in T", S would
be got from T, where it does not exist.

The global declaration is a powerful thing (specially when the routing tables 
have get/set methods) but is not to be used lightly.

I hope this helps.
--lhf