lua-users home
lua-l archive

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


Metalua has internal gotos and labels, for which you can easily create macros to use them in the language (untested code):

-- Adding goto and label macros: --
-{ mlp.lexer.register{ "goto", "label" }
   mlp.stat.add { "goto", mlp.id, builder = |x| `Goto{ x } }
   mlp.stat.add { "label", mlp.id, builder = |x| `Label{ x } } }

-- Now you can use them: --
label toto
print "Hello"
goto five_steps_down
print "This statement won't be executed"
label five_steps_down
print "It's been a long time"

Limitations:
- labels are local to a function, you can't jump from a function to another
- It's safe to jump out of a loop/block. If you jump into a loop/block, some local variable will probably be uninitialized.

The second idea would be adding script lines to a
coroutine in runtime. Imagine the author wants to
change #3 to turn away from NPC2 instead of turning
to.

Put these statements into functions, these functions into a table, and execute all elements of the table:

my_routine =
{ function() print "stat 1" end,
  function() print "stat 2" end,
  function() print "stat 3" end }

-- Add a 4th statement:
table.insert (my_routine, function() print "stat 4" end)

-- Put the calling code into the metatable, so that you can call your table as a regular function: --
mt = { }
function mt.__call(x)
  for _, stat in ipairs(x) do stat() end
end
setmetatable (my_routine, mt)

-- This will execute all statements in the table, in order: --
my_routine()

Limitations:
- you'll have troubles sharing local variables across independent statements
- the syntax is heavy. Metalua offers a lighter syntax for anonymous functions returning a value: "function(x) some_expr(x) end" can be written "|x| some_expr(x)"; therefore the first statement addition above can be written " table.insert(my_routine, || print('stat 4'))"

If you feel like you need some deeper syntactical or semantic changes in the language, I encourage you to have a look at metalua, which allows you to do so with as little pain as possible: http://metalua.luaforge.net
 
Fabien.