[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: local scope once again
- From: "Leo Razoumov" <slonik.az@...>
- Date: Tue, 12 Dec 2006 15:22:49 -0500
On 12/12/06, Jerome Vuarand <email@example.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??