Search code examples
luaecmascript-3

Is there a solution for transpiling Lua labels to ECMAScript3?


I'm re-building a Lua to ES3 transpiler (a tool for converting Lua to cross-browser JavaScript). Before I start to spend my ideas on this transpiler, I want to ask if it's possible to convert Lua labels to ECMAScript 3. For example:

goto label;

:: label ::
print "skipped";

My first idea was to separate each body of statements in parts, e.g, when there's a label, its next statements must be stored as a entire next part:

some body
label (& statements)
other label (& statements)

and so on. Every statement that has a body (or the program chunk) gets a list of parts like this. Each part of a label should have its name stored in somewhere (e.g, in its own part object, inside a property).

Each part would be a function or would store a function on itself to be executed sequentially in relation to the others.

A goto statement would lookup its specific label to run its statement and invoke a ES return statement to stop the current statements execution.

The limitations of separating the body statements in this way is to access the variables and functions defined in different parts... So, is there a idea or answer for this? Is it impossible to have stable labels if converting them to ECMAScript?


Solution

  • I can't quite follow your idea, but it seems someone already solved the problem: JavaScript allows labelled continues, which, combined with dummy while loops, permit emulating goto within a function. (And unless I forgot something, that should be all you need for Lua.)

    Compare pages 72-74 of the ECMAScript spec ed. #3 of 2000-03-24 to see that it should work in ES3, or just look at e.g. this answer to a question about goto in JS. As usual on the 'net, the URLs referenced there are dead but you can get summerofgoto.com [archived] at the awesome Internet Archive. (Outgoing GitHub link is also dead, but the scripts are also archived: parseScripts.js, goto.min.js or goto.js.)

    I hope that's enough to get things running, good luck!