User Tools

Site Tools


4rpl:commands:switch

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
4rpl:commands:switch [2022/08/31 14:28] – created Karsten754rpl:commands:switch [2024/03/30 17:05] (current) – Change title to lowercase for consistency between flow control Up-Level
Line 6: Line 6:
  
 :!: Available in version 2.4.4 and later. :!: Available in version 2.4.4 and later.
-====== Switch ======+====== switch ======
 switch switch
  
Line 12: Line 12:
 Allow for multiple selection control in a single, more compact form that multiple if/else if/endif endif format. This is intended to improve clarity by reducing otherwise repetitive coding.  Allow for multiple selection control in a single, more compact form that multiple if/else if/endif endif format. This is intended to improve clarity by reducing otherwise repetitive coding. 
  
 +All code between ''switch'' and ''endswitch'' is evaluated in order, including code written outside of ''case''..''endcase'' statements. Each ''case'' expects an argument that evaluates to True or False at the time of being encountered. If True, the case is executed, and the execution of the switch is ended at the next ''endcase''. If False, the case is skipped and the execution of the code inside the switch continues as normal.
 +
 +=== Programming note ===
 +The ''case'' in a RPL language differs from ''case'' in say, C. The logic before a case statement ultimately can do whatever it wants. In the end it should put something on the stack that the case evaluates as true or false. But there can be any amount of code that does anything before a case statement. This could lead to, for instance, the code in the second example that will not execute either of the two `case` statements.
 ===== Examples ===== ===== Examples =====
 <code 4rpl> <code 4rpl>
 switch switch
-    case(<-currentState 0 ==)  +   case(<-currentState 0 ==)  
-        @HandleIdle +      @HandleIdle 
-    endcase+   endcase
  
-    case(<-currentState 1 ==)  +   case(<-currentState 1 ==)  
-        @HandleMove+      @HandleMove
     endcase     endcase
  
-    case(<-currentState 2 ==)  +   case(<-currentState 2 ==)  
-        @HandleFire+      @HandleFire
     endcase     endcase
 +    @HandleException # no case statement evaluated to TRUE
 endswitch endswitch
 +</code>
 +Second example
 +<code 4RPL>
 +true ->init 
 +Switch
 +   Case (NOT (<-init) )
 +      Trace ("Case 1 is valid"
 +   endCase 
 +   False ->init
 +   Case (<-init )
 +      Trace ("Case 2 is valid"
 +   endCase
 +   Trace("There is no case to be made")  
 +endSwitch
 +
 </code> </code>
  
4rpl/commands/switch.txt · Last modified: 2024/03/30 17:05 by Up-Level