Code: Select all
switch(val,cases){
global switchVal:=val
if(!isObject(cases))
throw "Second param (cases) must be an object."
for i,a in cases{
if(i=="default")
hasDefault:=1
else if(val=a){
if(!isLabel(i))
throw "Label """ . i . """ doesn't exist."
else
gosub % i
return a
}
}
if(hasDefault){
if(!isLabel(cases.default))
throw "Label """ . cases.default . """ doesn't exist."
else
gosub % cases.default
return "default"
}
return 0
}
Code: Select all
var1:=10
var2:=5
loop
switch(rand(1,10),{label_1:var1
,label_2:var2
,label_4:9
,default:"label_3"})
label_1:
label_2:
label_3:
msgbox % a_thislabel . "`n" . switchVal
return
esc::exitApp
switch(val,cases){
global switchVal:=val
if(!isObject(cases))
throw "Second param (cases) must be an object."
for i,a in cases{
if(i=="default")
hasDefault:=1
else if(val=a){
if(!isLabel(i))
throw "Label """ . i . """ doesn't exist."
else
gosub % i
return a
}
}
if(hasDefault){
if(!isLabel(cases.default))
throw "Label """ . cases.default . """ doesn't exist."
else
gosub % cases.default
return "default"
}
return 0
}
; stdlib
rand(lowerBound,upperBound){
random,rand,% lowerBound,% upperBound
return rand
}
I'll explain in more detail how this works. Foremost, you have the definition, which is switch(val,cases). val will be the value to be checked against. cases will be an object/associative array that has a switch-case like design. The object keys will represent the label to be executed, while the key value will be a value checked against val. In doing this, rather than having it directly in the case name, custom label names may be used. default breaks the convention though; to use default, there must be a key with the name of default. The key value will be the label. I chose to write it this way so "default" may be used as a literal value still.
In the example, the val is a random number between 1 and 10. The case compensates 10, 5, 9, and then default. If it happens to be 5, label_2 will be ran. If it's 10, label_1 will be ran. If it's none of the specified numbers, label_3 is ran. If it's 9, however, it will run label_4. Except, label_4 doesn't exist. This will throw an error and kill the logical thread.
Since it uses an object and literal labels, both the object and labels may be defined anywhere and used whenever needed, thus expanding the limited nature of switch-case, if only slightly.