[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: A question on the definition of a chunk
- From: Sean Conner <sean@...>
- Date: Wed, 27 Jun 2012 15:52:47 -0400
It was thus said that the Great Gavin Wraith once stated:
> In message <20120627184905.GA7463@inf.puc-rio.br> you wrote:
>
> > > Is this making any sense?
> >
> > I do not think so. It is the same problem: blocks are lists of
> > statements, but that does not mean that any list of statements is a
> > block. If you draw the syntax tree of the above piece of code, it
> > becomes clear that "x = a()" (in that particular place) is not a
> > block. So, that occurence of "x = a()" cannot be a subblock.
>
> OK. Reduction is not symmetric :). So, for checking that I have
> it right, am I correct in saying that a local variable's scope
> consists of the statements or blocks that follow its declaration
> that also lie within the smallest block that contains its
> declaration?
Here's two examples of Lua chunks (sans error checking, which would cloud
the issue), compiled via loadstring() (which returns a function that when
run, will execute the code in the given chunk):
c1 = loadstring [[
-- this is chunk # 1
local a -- this is local to this chunk
a = 15
-- this function will be loaded into the default
-- environment. In most cases, this will end up
-- in the global name space.
function f(x)
return 3 * x + a
end
]]
c1() -- run the loaded chunk
c2 = loadstring [[
-- this is chunk #2
-- this function is local only to this chunk
local function y(i)
return i * a
end
-- the 'a' above does not refer to the 'a' defined in the
-- previous chunk, as that was local to that chunk. In this
-- case, y() will default to an 'a' in the global name
-- space. If it exists, this will run, otherwise it will
-- generate an error.
y(3)
]]
-- at this point, c2 is defined, but what happens next ..
c2()
If 'a' doesn't exist, then running c2() will result in:
[string " -- this is chunk #2..."]:5: attempt to perform
arithmetic on global 'a' (a nil value)
stack traceback:
[string " -- this is chunk #2..."]:5: in function 'y'
[string " -- this is chunk #2..."]:14: in function
'c2'
stdin:1: in main chunk
[C]: ?
But doing this:
a = 3
c2()
yields no errors.
-spc (Does that help clarify the issue?)
- References:
- A question on the definition of a chunk, Alexander R.
- Re: A question on the definition of a chunk, TNHarris
- Re: A question on the definition of a chunk, Gavin Wraith
- Re: A question on the definition of a chunk, Dirk Laurie
- Re: A question on the definition of a chunk, Gavin Wraith
- Re: A question on the definition of a chunk, liam mail
- Re: A question on the definition of a chunk, Roberto Ierusalimschy
- Re: A question on the definition of a chunk, Gavin Wraith
- Re: A question on the definition of a chunk, Roberto Ierusalimschy
- Re: A question on the definition of a chunk, Gavin Wraith