lua-users home
lua-l archive

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


> Is there any Lua programming idiom that could be used to emulate goto
> behaviour (as there are for emulating if elseif elseif ... chains and
> switch statements)? Did anyone else face similar problems?

The "goto" issue came up a while back, but from a different perspective.
(State switching without recursion.)  I think it depens on how you use your
goto statements.  Some may be emulated by a "break" (like Luiz pointed out
already.)  For example the following pattern:

    ... some code ...
    if ...some condition... then goto label end
    ... some more code ...
    if ...some other condition... then goto label end
    ... still some more code...
label: ...

Could be replaced by

    repeat    -- a break out loop
        ... some code ...
        if ...some condition... then break end
        ... some more code ...
        if ...some other condition... then break end
        ... still some more code...
    until true
    ...

Though breaking out of nested loops may need some special care.

Another way is to use (local) functions.  Then the above could also be
transformed into something like:

    local function label() ... end

    ... some code ...
    if ...some condition... then return label() end
    ... some more code ...
    if ...some other condition... then return label() end
    ... still some more code...
    label()

As the example shows, it may need some rearrangement of your code.  Here I
moved the code of entrypoint "label" up.  This means that any locals it
refers should at least be known ("declared") before the definition of the
local label function.  Lua's upvalue system may come to the rescue here.
The downside of this solution is that it creates a temporary closure for
"label" every time you invoke this code.  Even this could be avoided (using
blocks) but it takes still more rearrangment of your code (assuming that our
code example defined a global function "f"):

do
    ... shared locals go here ...
    local label

    function f()
        ... some code ...
        if ...some condition... then return label() end
        ... some more code ...
        if ...some other condition... then return label() end
        ... still some more code...
        label()
    end

    label = function() ... end
end

Probably there is no uniform way to translate goto's, but maybe variations
on tricks like these could help you out.

--
Wim