Conditional Switches
Aus EnigmaWiki
Available languages: Deutsch, English, Русский
Inhaltsverzeichnis |
Conditional Switches
Problem definition
You have several switches and something is to be switched if e.g. first, second and third switches are on and the fourth and fifth off. In all other cases nothing is to happen.
Solution
We record the states of all switches in a table (Array). Each switch manages therein its state. After anyone operates a switch, you call an evaluation function, which can make arbitrary inquiries to the table.
Solution example
switch_pos = {{1,1},{2,3},{4,6},{5,7},{8,9}} num_switches = table.getn(switch_pos) bool_tab = {} -- Object: for i=1, num_switches do bool_tab[i] = 0 set_stone("st-switch", 2+i,2,{name="switch"..tostring(i), action="callback", target="change_state", _senderid=i }) end set_stone("st-oneway-e", 5, 10, {name="one-way"}) -- Action: function evaluate() local one-way=enigma.GetNamedObject("one-way") if bool_tab[1] == 1 and bool_tab[2] == 1 and bool_tab[3]==1 and bool_tab[4]==0 and bool_tab[5]==0 then SendMessage(one-way,"flip") end end function change_state(onoff, sender) local id = enigma.GetAttrib(sender, "_senderid") bool_tab[id] = 1 - bool_tab[id] evaluate() end
Analysis
First the necessary variables are defined.
-
switch_posis an array, which stores the positions of the switches.
-
num_switchesis the number of switches. It is computed directly fromswitch_pos.
-
bool_tabis the table (array) that stores those the conditions of all switches.
Then the objects are set and initialized equal to bool_tab. The switches will provide senderid with an additional attribute. It is a unique, whole number, which is used as an index for bool_tab.
Every time, if a switch is now operated, the function change_state is called. It manages the status of the switches in bool_tab. It inverts it in each case. Afterwards it calls the function evaluate.
Evaluate now examines whether all conditions is fulfilled, and the target may be implemented. It places all inquiries to the bool_tab and evaluates it. In the example, if the 1st, 2nd and 3rd switches are on (bool_tab[id]==1) and the 4th and 5th are off (bool_tab[id]==0), then the direction of the Oneway is changed.
If now another switch is toggled - the condition is no longer fulfilled - the direction does not return to the original state. This only happens, if a player sets the correct state again.
If however you want the direction to changes again, as soon as the condition is no longer fulfilled, you must add into the evaluate function a second branch (else). That could look something like this:
function evaluate() local one-way=enigma.GetNamedObject("one-way") if bool_tab[1] == 1 and bool_tab[2] == 1 and bool_tab[3]==1 and bool_tab[4]==0 and bool_tab[5]==0 then SendMessage(one-way,"flip") else SendMessage(one-way,"direction", EAST) end end
You cannot simply send a flip message again, since the direction would otherwise change with each switching.

