lua-users home
lua-l archive

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


On 12/12/06, Jerome Vuarand <jerome.vuarand@ubisoft.com> wrote:
Leo Razoumov wrote:
> I am surprised to see that there are three different local 'x'
> variables. All of them belong to the same "block" which is foo()
> function body and, thus, should have the same scope. Why does not Lua
> collapses them into just one local x variable??

It's a feature of lua that the local keyword create a *new* local
variable, unconditionally. The end keyword closes a lexical scope, but
the beginning of the scope is not defined by the beginning of the block
but instead by the variable creation, which can happen after the
beginning of the block as in your examples (to be precise, the scope
starts just after variable initialisation, so a statement like "local
data = data.subdata" makes sense).

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??

--Leo--