lua-users home
lua-l archive

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



I wouldn't mind getting a warning about the dual-localling of variables (within the same scope level).

There is one case, where this can get rather nasty:

local f	-- pre-name for early reference

local function g()
	...
	f()
end

local function f()	-- WRONG!  (must be: f= function())
	...
end

Here the intention is that 'g' and 'f' are mutually calling routines, or for some other reason need to be introduced in this order. If the code is like above, the upper 'f' is always nil, and there's NO warning about this until one hits it at runtime.

Funny I don't remember this being discussed before -- has it? Any solution ideas?

-asko


Jerome Vuarand kirjoitti 12.12.2006 kello 22.47:

Leo Razoumov wrote:
This behaviour means that all earlier local declarations of
the variable become completely shadowed by later local
declarations at the same scope. I am afraid it makes code
less readable.

local x="first declaration"
local x="second declaration" -- the same scope

The first line is now completely irrelevant, because its
version of 'x' is not accessible by regular Lua means (except
for debug library).

Is there any particular reason to design Lua local scope
rules this way??

I can't explain the initial choice for such a decision, but I personally
think this is a good thing. This gives a lot of flexibility to the
programmer, with the only drawback being some confusion for programmers
too used to C-like scopes. You can do what you want to do with the
syntax, but the syntax that you expected prevents me from doing some
things I want to do (like having multiple variables with the same name
in the same block). So that solution is the best since it allows all
features, at the cost of *some* readability for *some* readers not used to Lua syntax (I think that in any experienced Lua programmer mind, the
local keyword is instantly spotted as a variable creation).