Page 1 of 1
SWITCH - can it be used with an expression
Posted: Sun Sep 06, 2015 3:10 am
by golive
Can one use a condition in the CASE statement?
I tried this but it doesn't work.
Code: Select all
switch tCount
case tCount <10
-- do something
break
case tCount <20
-- do something else
break
Re: SWITCH - can it be used with an expression
Posted: Sun Sep 06, 2015 7:16 am
by SparkOut
Yes, just leave out the reference to tCount in the switch statement and only in the conditional tests
Code: Select all
switch
case tCount >20
answer "count is high"
break
case tCount <5
answer "count is low"
break
default
answer "count is just right"
break
end switch
Re: SWITCH - can it be used with an expression
Posted: Sun Sep 06, 2015 7:24 am
by SparkOut
Also, a switch statement unmatched with a variable like that can check multiple conditions such as
Code: Select all
switch
case tGender is "male"
set the cPermission of this stack to false
answer "Sorry, ladies only"
break
case tAge < 18
set the cPermission of this stack to false
answer "Sorry, adults only"
break
end switch
Re: SWITCH - can it be used with an expression
Posted: Sun Sep 06, 2015 5:36 pm
by bn
Hi golive,
you might also have a look here:
http://forums.livecode.com/viewtopic.php?f=8&t=25082
switch statements can get very tricky.
I mostly use if-then, except when choosing from a larger number of options. Then I use the "switch variable" form. With appropriate break.
If you do conditionals on a variable as done in above link, be careful and know what you are doing. You can get surprising result. Although they are consistent with the logic of Switch case.
Kind regards
Bernd
Re: SWITCH - can it be used with an expression
Posted: Sun Sep 06, 2015 6:52 pm
by FourthWorld
Switch statements are trickiest when you use the case evaluation form without break statements. Beyond that very specific circumstance outlined in the forum discussion Bernd linked to, they're pretty straightforward and very useful for a wide range of circumstances where if-then blocks may be cumbersome or less flexible.
The key here is that you can either evaluate a condition in the switch statement, or within each case statement, but not both.
As SparkOut wrote, in your code you were evaluating the condition with each case statement, so just removing the comparison value from the switch statement addresses the issue you encountered.
Re: SWITCH - can it be used with an expression
Posted: Mon Sep 07, 2015 3:40 am
by golive
Very useful info from all, many thanks.
Suggestion: For beginners like me, more info like the above in the Dictionary would be useful
