lua-users home
lua-l archive

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



On Thu, Jun 11, 2009 at 10:46 AM, David Given <dg@cowlark.com> wrote:
Robert Raschke wrote:
[...]

If I remember correctly, Lua optimises tail calls. In my experience, using tail calls for state transitions is way easier to understand and code than using goto's. But YMMV, I guess.

Tail calls don't let you easily share state using local variables --- you either have to pass all your state in using parameters, or else put the whole thing inside a bigger function and use upvalues. Either way, it's significantly more heavyweight. Still fast (I posted some benchmarks a little while ago), but considerably less so than a simple jump from one bytecode location to another.

I find using a "machine state" Lua table that you can pass around to be pretty ideal. That's just one parameter to pass around, and it neatly encapsulates your machine state and keeps it separate from the general program state that you may need during processing.



Or is your problem, that you've already got lots of machine generated goto-state machines that you'd like to "translate" to Lua?

This is my major use case, yes, but it'd also be useful in other places. Consider this --- most languages provide some sanitised goto to handle doing this sort of thing:

while a do
 while b do
   while c do
     while d do
       if abort() then
         goto exitloopc
       endif
     end
   end
   exitloopc:
 end
end

Hmmm, I know this is probably generated code, but when I see stuff like that, I think some refactoring is in order.

If you've already got the state machines (in C or whatever), would it not be easier to keep them there and add Lua interaction into the state actions or to provide control?

Robby