I recently had someone ask me for some sample code to make use of a loop in OptoScript.
In his application, he has several user choices (in an integer table), and wants those options to act like radio buttons. In other words, if one choice is selected, the others are de-selected. He originally solved this with multiple if statements but was looking for a loop option.
Here’s his original code and my suggested loop. I’m hoping you Clever People Out There in OptoLand will have options and/or other suggestions too. Don’t be shy!
Pre-loop before code:
if (ntSource) then ntSource=0; ntSource=0; ntSource=0: endif if (ntSource) then ntSource=0; ntSource=0; ntSource=0: endif if (ntSource) then ntSource=0; ntSource=0; ntSource=0: endif if (ntSource) then ntSource=0; ntSource=0; ntSource=0: endif
Mary’s suggestion for how to use a loop instead (using the handy and under-appreciated MoveToNumTableElements command, and assuming you have OPTION_FIRST = 38; OPTION_LAST = 41; or some such defined earlier).
// loop through and clear out all of the other options besides the first one we find set, // starting at OPTION_FIRST defined earlier // Note: if you get to OPTION_LAST, you either have none at all set, or none left to clear! nSourceIndex = OPTION_FIRST; while (nSourceIndex < OPTION_LAST) if (ntSource[nSourceIndex]) then // we’ve found our selection, first one wins, clear out all the others MoveToNumTableElements(/*From*/0, /*Start Index*/nSourceIndex+1, /*End Index*/OPTION_LAST, /*Of Table*/ ntSouce); nSourceIndex = OPTION_LAST; // to bail out of the loop, since we’re done endif nSourceIndex = nSourceIndex + 1; wend
Hooray for loops and more maintainable code!
Disclaimer: I did not test this code, I made a few assumptions here, and sometimes I write bugs. Use at your own risk.