[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: function with program counter
- From: Tim Hill <drtimhill@...>
- Date: Sat, 14 Sep 2013 17:29:41 -0700
On Sep 14, 2013, at 1:26 PM, Philipp Kraus <philipp.kraus@tu-clausthal.de> wrote:
> Hello,
>
> I would like to use a list structure for calling Lua function. So some explanation.
> I have got a function e.g.
>
> function test({…})
> do first call
> do some print
> do second call
> do some print again
> if (a)
> do A
> else
> do B
> end
> ….
> end
>
> I have got also a "program counter" which is started by 1. On 1 its should run "do first call" on 2 "do some print" and so on.
> I would like to use a Lua function, but I would like to run this function step-by-step. I can use a if construct to check the current
> "program counter value" and run the correct command, but this is not very nice.
>
> Did you have an idea for this problem?
>
> Thanks
>
> Phil
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