Attract-Mode Support Forum
Attract-Mode Support => Scripting => Topic started by: Bgoulette on January 30, 2019, 06:52:27 AM
-
This is probably a silly question, but I haven't been able to divine an answer through the Squirrel reference docs or googling.
I'm used to Javascript (Actionscript, really), where I could test for the existence of an object property something like this:
if (obj.prop) {
// Property exists: do stuff:
}
else {
// Property DOES NOT exist: do something else:
}
If I try something similar with Squirrel (in my layouts), I get an error because the slot doesn't exist. Currently, I have a rat's next of try..catch statements to determine whether a slot exists, but it's messy (even though it works). Is there a cleaner way to handle checking whether a slot exists?
-
If I remember correctly, squirrel doesn’t have exists or empty methods. I could create a function that utilizes typeof to test if it has been created.?
-
That's what I'd run into, I think. I had it in mind to write an adjunct function that I could pass properties to, but then I realized they'd fail during the initial call (I think), since there's potentially no property to pass? I'll probably give it a try just to see. Unless someone comes up with something better in the meantime! ;-)
-
Just use try/catch in that instance. Changing the property of a variable that does not exist or is the wrong type will fail.
-
Haven't had a chance to try it out yet, but I wrote a convenience function that should allow for cleaner code. I'm posting it here in case anyone else encounters similar circumstances:
function exists (t, s) {
// Pass a known table (t) as-is and an unknown slot (s) as a string:
try {
// Perform some non-destructive operation to determine existence:
// (I wonder if just referencing the potential slot would work?)
t[s];
return true;
}
catch (e) {
return false;
}
}
// Usage example:
myImage.alpha = ( exists(table, "slot") ) ? 255 : 0; // If table["slot"] exists, set myImage to full alpha; otherwise, set it to 0
If I get home and discover this doesn't work, I'll try something else!