Author Topic: Check if a slot exists?  (Read 305 times)

Bgoulette

  • Sr. Member
  • ****
  • Posts: 112
  • I wrote a book.
    • View Profile
    • BlakeGoulette.com
Check if a slot exists?
« 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:

Code: [Select]
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?

keilmillerjr

  • Global Moderator
  • Hero Member
  • *****
  • Posts: 863
    • View Profile
Re: Check if a slot exists?
« Reply #1 on: January 30, 2019, 02:05:20 PM »
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.?

Bgoulette

  • Sr. Member
  • ****
  • Posts: 112
  • I wrote a book.
    • View Profile
    • BlakeGoulette.com
Re: Check if a slot exists?
« Reply #2 on: January 30, 2019, 02:07:32 PM »
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! ;-)

keilmillerjr

  • Global Moderator
  • Hero Member
  • *****
  • Posts: 863
    • View Profile
Re: Check if a slot exists?
« Reply #3 on: January 30, 2019, 02:59:52 PM »
Just use try/catch in that instance. Changing the property of a variable that does not exist or is the wrong type will fail.

Bgoulette

  • Sr. Member
  • ****
  • Posts: 112
  • I wrote a book.
    • View Profile
    • BlakeGoulette.com
Re: Check if a slot exists?
« Reply #4 on: January 31, 2019, 07:27:38 AM »
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:

Code: [Select]
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!