Clarification of goto scope

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Clarification of goto scope

Patrick Rapin
>From another current thread, we can see that some people like the
introduction of goto in Lua 5.2 while some others hate it !
Still, I wanted to use that keyword to simulate the missing
"continue", and was surprised that this type of code actually works :

for i=1,10 do
  if i%3 == 0 then goto continue end
  local v = i*2
  print(v)
::continue::
end

Maybe it is clear for other people, but it was not for me.
Because in the manual, it is stated "A goto may jump to any visible
label as long as it does not enter into the scope of a local variable.
"
And it looks that the ::continue:: label is inside the scope of the
"v" variable, declared after the goto.
But right, if there is *any* instruction after the label (except empty
semicolons), the code doesn't compile anymore.
The reference manual could further explain that a label is allowed
just before a "end", even if there are local variables declared in the
block.
Also, the manual could show one or two examples for typical "continue"
or "redo" usage, as it is not trivial.

Reply | Threaded
Open this post in threaded view
|

Re: Clarification of goto scope

Dirk Laurie-2

The reference manual could further explain that a label is allowed
just before a "end", even if there are local variables declared in the
block.
Also, the manual could show one or two examples for typical "continue"
or "redo" usage, as it is not trivial.

The promised PiL3 should have such elucidations, yes.  But the manual? No. 

The F in RTFM does not really stand for "friendly".


Reply | Threaded
Open this post in threaded view
|

Re: Clarification of goto scope

Xavier Wang
2012/2/1 Dirk Laurie <[hidden email]>:

>
>> The reference manual could further explain that a label is allowed
>> just before a "end", even if there are local variables declared in the
>> block.
>> Also, the manual could show one or two examples for typical "continue"
>> or "redo" usage, as it is not trivial.
>>
> The promised PiL3 should have such elucidations, yes.  But the manual? No.
>
> The F in RTFM does not really stand for "friendly".
>
>

I think the manual just imply it, see 3.5 in
manual(http://www.lua.org/manual/5.2/manual.html#3.5):

Lua is a lexically scoped language. The scope of a local variable
begins at the first statement after its declaration and lasts until
the last non-void statement of the innermost block that includes the
declaration.

and 3.3.4:

For syntactical reasons, labels in Lua are considered statements too

so we know:

- local variable's scope ends after the last non-void statement of block.
- the label statement *is* a void statement.
- so the local variable's scope is end *before* the label statement.
- so, you don't jump into the local's scope :-)

So.... maybe the manual is not that "friendly", but just enough :-)