Page 1 of 1
Switch statement
Posted: Sun Jun 02, 2013 4:06 am
by sandybassett
I'm trying to limit input to a field for telephone number so it will only take numbers and '-' and only up to 12 characters. After reading about switch in the dictionary I tried the following:
on keyDown
switch
case the length of me >=12
case theKey is not a number
case theKey is not "-"
beep
break
default
pass keyDown
end switch
end keyDown
It stops all entry and beeps. If I comment out all of the case lines, and then use them one at a time, the first one works but the 2nd and 3rd even when standing alone stop all entry. What's wrong? All three of them work in an if...then statement, but only two at a time; adding any one as a third stops all entry. Surely LC can count higher than 2. Can anyone see how to accomplish this. Thanks
Re: Switch statement
Posted: Sun Jun 02, 2013 6:58 am
by Simon
Hi Sandy,
I'd use:
Code: Select all
if (isNumber(tKey) or tKey is "-") and (the length of me <=12) then
put tKey after me
end if
A few days ago I ran a speedtest on if/then versus switch/case and while I thought switch would be faster it actually wasn't.
If you really want to use switch there are a few errors in your script:
on keyDown theKey
You left that out. But there are more problems, if you want more help just ask
Simon
Re: Switch statement
Posted: Sun Jun 02, 2013 8:21 am
by dave_probertGA6e24
Hi,
The problem lays with the programmer - not the language
case the length of me >=12
case theKey is not a number
case theKey is not "-"
What does the above actually mean? (rhetorical question)
It means that this entry in the switch statement will be called when
ANY of the factors is true (Note: ANY)
If the length >= 12
OR The Key is not a number
OR the key is not "-" . Well that basically covers virtually any key on the keyboard!!!!
I think you need to read, understand and practice more with Switch statements before complaining
As Simon wrote - try the more compact and Logically correct If statement - it should work a lot better.
Cheers,
Dave
Re: Switch statement
Posted: Sun Jun 02, 2013 11:56 am
by Klaus
Hi friends,
looks like the SWITCH structure is intended to do what Sandy wants,
but it is mandatory to supply the pressed key as a PARAMETER to the
keydown handler to make this work:
on keyDown theKey
...
When you omit this, "theKey" in the handler is treated as the STRING -> "theKey",
and "theKey" is NOT/NEVER a number nor "-".
Best
Klaus
Re: Switch statement
Posted: Mon Jun 03, 2013 3:24 am
by sandybassett
Finally, Success! This works:
on keyDown theKey
switch
case theKey is a number and length(me) <=11
pass keyDown
case theKey is "-" and length(me) <=11
pass keyDown
end switch
end keyDown
I think my previous problems related to using cumulative negative tests and using the OR operator, which may not be possible. I'll learn more about that later. Now onward and upward to SQLite to store the entered data.