Say for example I'm trying to do try-catch where x does not exist:
@[x;::;"error"]
I get an 'x error, rather than "error". What am I doing wrong?
Say for example I'm trying to do try-catch where x does not exist:
@[x;::;"error"]
I get an 'x error, rather than "error". What am I doing wrong?
You can use the value keyword to determine if a variable exists or not. Error trapping this might be what you're looking for?
q)@[value;`x;"error"]
"error"
q)x:12
q)@[value;`x;"error"]
12
Have a look at the documentation here https://code.kx.com/q/ref/apply/#trap "In the ternary, if evaluation of the function fails, the expression is evaluated"
The function x cannot be evaluated as it does not exist. The function is not failing here it just cannot be called. The hint here is in evaluated - we can use value to check if the function exists.
q)f:{x+x}
q)@[value;`f;"error"]
{x+x}
q)@[value;`p;"error"]
"error"
The returns of values on the defined function f vs something that is not defined p >
q)value f
0x6161410003
,`x
`symbol$()
,`
5 3 4 2 2
"..f"
""
-1
"{x+x}"
q)value p
'p
[0] value p
^
Note that using value on the variable name will only work if the variable you're checking for is global, it would not work for a local variable:
q){@[value;`v;"error"]}[]
"error"
q){v:9;@[value;`v;"error"]}[]
"error"
Though in reality in most cases you would be looking for a global so this will work.
If it was a local you were looking for then things get a bit hacky and messy, but technically possible:
q){locals:?[(`$())!();();();{x!x}raze(value .z.s)1 2];$[`v in key locals;locals`v;'"error"]}[]
'error
q){v:9;locals:?[(`$())!();();();{x!x}raze(value .z.s)1 2];$[`v in key locals;locals`v;'"error"]}[]
9