[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: 5.2 feature list?
- From: Nick Gammon <nick@...>
- Date: Thu, 5 Oct 2006 06:54:47 +1000
On 04/10/2006, at 6:44 PM, John Hind wrote:
However I do not really see why local-by-default is such a problem.
In the Lua cant, it just means that if "x" cannot be resolved at
any point in interpretation, "x = 1" gets treated as "syntactic
sugar" for "local x; x = 1". Of course, if you want it to be in an
outer scope, you have to pre-declare in that scope.
How do you pre-declare variables at global scope? - that is the
question.
Doing "local x" at global scope doesn't do it - x is no longer _G.x
but a local variable. Roberto's solution a while back was a small
module that checked that, when adding a variable to the current
environment, the adding function was operating at global scope.
Say you want to force everything that isn't a local (or argument) to
be declared. You would need another keyword, like "global x".
However variables which are global would have to be put somewhere,
not just in the _G (environment) table, because by definition a
variable that is nil is not in a table.
Thus: global x = nil --> x is not in _G
Given that a Lua program can have multiple environments, you would
need a separate table, per environment, containing the "declared"
variables, and then every access to a variable (including reading it)
would have to check the "declared" table, in order to raise an error,
if the variable could not be found in the environment table.
The problem is, this could slow scripts down. The checks done in C
are done at compile time, not run time. However because of the nature
of Lua, the check would have to be done at runtime. For example:
_G [x] = 42
The compile phase cannot detect an attempt to access the global
variable, of whatever the value of "x" is, here, so it has to be done
at runtime.
How about this then? Say I do this:
nick = getfenv ()
nick [x] = 42
Now this is really another way of expressing: x = 42
Should this be caught as an "undeclared variable" or not?
As Roberto suggests in the Programming in Lua book, if you want to
catch this sort of situation, Lua lets you by using metatables.
Perhaps that is where this technique should stay.
- Nick