lua-users home
lua-l archive

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



On 26-Sep-05, at 10:38 AM, Roberto Ierusalimschy wrote:


The compiler could detect such cases and signal an error ("jumping
across local declaration"), but that would make the mechanism more
complex (to implement, to explain, etc.).

Indeed, but that would arbitrarily prohibit "valid" code, since the problem isn't jumping over a local declaration but rather *using* an uninitialised value.

To be more precise, the first two of the following are presumably correct whereas the third is incorrect, but unless the compiler actually did use analysis, all three would be rejected as "jumping across local declaration":

Example 1:

repeat
  local done = false
  local w = f()
  if w == "skip" then continue end
  local ok, msg = handle(w)
  if msg then print(msg) end
  done = not ok
until done

Example 2:

repeat
  local w = f()
  if w == "skip" then continue end
  local ok, msg = handle(w)
  if msg then print(msg) end
  if not ok then break end
until false

Example 3: (The error)

repeat
  local w = f()
  if w == "skip" then continue end
  local ok, err = handle(w)
  if not ok and err then print(err) end
until not ok

----------------------

As I've said, I have no particular object to "continue" but the above seems to indicate that it does not work with the new semantics of repeat...until. It could, of course, be restricted to "for" and "while" loops, or it could be allowed in "repeat" loops with the proviso that the "repeat" loop is syntactic sugar for a while loop:

  repeat <body> until <expr>
===>
  while true do <body>; if <expr> then break end end

in which case, the "continue" statement would effectively skip the termination test.

However, both of these possibilities increase the "cognitive load", and that needs to be balanced against the utility of the construct.

As a postscript, in a private mail to Glenn Maynard (which he suggested I could have posted publicly), I mentioned that his example of continue:

if (cond1) {
  action1;
  continue;
}
if (cond2) {
  action2;
  continue;
}
if (cond3) {
  action3;
  continue;
}
// repeated many more times

could be more "naturally" (to me) expressed in either C or Lua by using else if/elseif:

if (cond1) {
  action1;
}
else if (cond2) {
  action2;
}
else if (cond3) {
  action3;
}

-- in Lua:
if cond1 then
  action1
elseif cond2 then
  action2
elseif cond3 then
  action3
end

This idiom is independent of inclusion in a looping construct.