Shop OBEX P1 Docs P2 Docs Learn Events
Rotating/Looping/Cycling Through Variable Values — Parallax Forums

Rotating/Looping/Cycling Through Variable Values

coryco2coryco2 Posts: 107
edited 2014-03-04 10:22 in Propeller 1
I am looking for the most code-efficient way to allow a variable value to be cycled through a given set of consecutive whole values in a continual loop. For example, given the set {5, 6, 7, 8, 9, 10}, I want the variable to start with a value of 5, advance through each value until it reaches 10; then return to 5 and repeat.

This is one way do that:
CyclingValue:=5

REPEAT
   CyclingValue++
      if CyclingValue==10
        CyclingValue:=5

Can anyone figure out a more compact way to do this?

Comments

  • Phil Pilgrim (PhiPi)Phil Pilgrim (PhiPi) Posts: 23,514
    edited 2014-03-04 08:44
    repeat
      repeat i from 5 to 10
        'do stuff with i
    

    -Phil
  • coryco2coryco2 Posts: 107
    edited 2014-03-04 08:58
    Thanks Phil. What if I want to be able to cycle CyclingValue through the same repeating set of values one step at a time in response to repeated ConditionX's?:
    IF ConditionX
               CyclingValue++
                 if CyclingValue==10
                       CyclingValue:=5
    
  • Phil Pilgrim (PhiPi)Phil Pilgrim (PhiPi) Posts: 23,514
    edited 2014-03-04 09:11
    If you don't have anything else to do while waiting for ConditionX,
    repeat
      repeat i from 5 to 10
        repeat until ConditionX
        'do stuff with new i value
    

    Otherwise, your way is better.

    -Phil
  • lonesocklonesock Posts: 917
    edited 2014-03-04 10:22
    VAR
      long var_i { 15 bytes }
    
    DAT
      dat_i long 0 { 13 bytes }
      
    PRI just_4_test : local_i { 11 bytes }
          
      if ++local_i => 10
        local_i := 5
    
    Incorporating the prefix increment saves one byte. Also, using local variables rather than globals is faster / fewer byte-codes.

    Jonathan
Sign In or Register to comment.