[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: function with program counter
- From: Steve Litt <slitt@...>
- Date: Sun, 15 Sep 2013 21:23:34 -0400
On Sat, 14 Sep 2013 17:29:41 -0700
Tim Hill <drtimhill@gmail.com> wrote:
> I think what you are really talking about is a state machine, which
> is often handled by a switch statement. Since Lua lacks these, you
> end up resorting to a bunch of "if" statements doing one-by-one
> checks of your program counter, as you note.
>
> The classic alternative to a switch statement for a state machine is
> a jump table, which is Lua terms is an array of functions. If you
> re-write each of your steps as a small function:
>
> function first_call(…)
> end
>
> function some_print(…)
> end
>
> -- etc.
>
> -- You can then create an array of these:
>
> call_table = { first_call, some_print, … }
>
> -- Now, you can re-write "test" to just call the appropriate function
> in the array:
>
> function test(…)
> return call_table[program_counter](…)
> end
>
> -- And call it like this…
>
> program_counter = 1
> test(…)
> program_counter = program_counter + 1
> test(…)
>
> -- Of course you can increment the program counter inside each call
> to test() if that suits your purpose, or even make it an upvalue.
>
> --Tim
This is *such* a cool idea, I should have thought of it myself. And
doing it Lua makes it even cooler because states can have meaningful
names like "close_bracket_encountered" as keys for the functions. And
even better, the array of functions could have an element called "data"
that would house data being passed between the various states, for
those times when you care more about coding ease than about modularity,
but still don't want to use global variables.
SteveT
Steve Litt * http://www.troubleshooters.com/
Troubleshooting Training * Human Performance