lua-users home
lua-l archive

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


>I think people don't generally appreciate how serious
>of a problem the current semantics are.  Accidental
>use of global variables is a sleeper: it may be
>present in your code for a long time and not show up 
>until you make completely unrelated changes to your 
>code.

If you're willing to use a "global" declaration, then something very similar
can be done right now: Instead of a "global" keyword, use a "global" function,
with the syntax
	global "myvar"	-- one name only
or
	global{"a","b"}	-- several names

Here is the "global" function:

do
	local G={}
	function global(x)
		if type(x)=="string" then
			%G[x]=1
		else
			for i,v in x do
				%G[v]=1
			end
		end
	end
end

You can now implement the semantics you want by setting tag methods for
"setglobal" and/or "getglobal" that checks the name against G.

Thus to implement the need-declaration-to-write-to-globals semantics,
set the "setglobal" tag method and raise an error if the given variable
is not in G. The error will be show as soon as it happens; ie no sleeper!

For details, see the FAQ on uninitialized and read-only variables.

The problem with this approach is that declarations last for ever, not only for
the current block.
--lhf