Writing a foo.isNil.or(foo[\bar]!="tor")

I’m trying to write in a concise form a test that should pass if an object is nil or if it doesn’t contain a certain key.

In Javascript, I would write it like this:

//var x=null;
//var x={a: "xx"};
var x={a: "yy"};

if ((x==null) || (x.a!=="xx")) { console.log("No XX");} else  { console.log("XX");}

In SC, I’ve written it like this

~x=nil;
~x=(a: "xx");
~x=(a: "yy");
~x=(b: "ss");
~x.isNil.or(~x[\a]!="xx").if({"No XX"},{"XX"});

It fails for ~x==nil because it evaluates the or function despite the left side of the or being already true.

According to the doc, this seems to be an implementation issue in the or function:
image

Correct ?

I don’t find a one-line alternative to this…

That’s because you haven’t provided a function - try this:

if (~x.isNil or: { ~x.a != "xx" }) { "No XX".postln } { "XX".postln };

or in your syntax:

~x.isNil.or({~x[\a]!="xx"}).if({"No XX"},{"XX"});

although I find the above version to be much clearer (it’s pretty much the standard idiom for writing conditional checks and appears throughout the standard library). Note the curly brackets/braces. Sclang also has special conditional execution operators (?, ?? and !?) for simple nil checks.

1 Like