[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: State machines and goto (Was: Next Version of Lua?)
- From: Robert Raschke <rtrlists@...>
- Date: Thu, 11 Jun 2009 11:12:33 +0100
On Thu, Jun 11, 2009 at 10:46 AM, David Given <firstname.lastname@example.org>
Robert Raschke wrote:
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.
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.
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.
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:
Or is your problem, that you've already got lots of machine generated goto-state machines that you'd like to "translate" to Lua?
while a do
while b do
while c do
while d do
if abort() then
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?