Using a variable as a property name

Twine Version:2.5.1
Story Format: sugarcube 2.36.1

I have the following block of code within a widget.

<<if $args[0].hasOwnProperty(_spellname)>>
    	<<set _setter=$args[0]._spellname>>
    	<<goto `_setter`>>
<</if>>

When the if statement is true, I get an error at the goto line.
Error:<>:error within widget code (Error: cannont execute macro <>: Story has title parameter cannot be undefined

yet when I replace the variable property name with a literal property name (as below) it works just fine, so there must be something wrong with my syntax. Please advise.

<<if $args[0].hasOwnProperty(_spellname)>>
    	<<set _setter=$args[0].literalnameoftheproperty>>
    	<<goto `_setter`>>
<</if>>

Ah, try $args[0][_spellname].

The $args[0]._spellname is the same as $args[0]["_spellname"]: it’s using the name as the property name, not the contents of the variable.

1 Like

just for clarification…

There are two syntaxes that can be used to access a property of an Object:

note: the following examples will be referencing the following variable and object…

<<set $book to {name: "Tarzan of the Apes", pages: 224}>>

1: Bracket Notation. eg. object["propertyName"]

This older syntax looks similar to how an Array element is accessed (eg array[index]), except the identifier between the open & close square brackets is a String literal instead of an Integer. This syntax is ideal for the situation where you need to dynamically determine the Name/Key of the property being accessed.

<<set _property = 'pages'>>
<<set _pages to $book[_property]>>

Book: Name: <<= $book['name']>>; pages <<= _pages>>.

2: Dot Notation. eg. object.propertyName

This newer syntax requires the property’s Name/Key to be known and supplied statically at the time the code was written. It can not be used in situations when the property name will be determined dynamically at runtime.

<<set _pages to $book.pages>>

Book: Name: <<= $book.name>>; pages <<= _pages>>.

note: You can use both syntaxes at the same time if required.

/* Add the book to a Library using its ISBN as the key. */
<<set $library to {'0486295702' : $book}>>

<<set _isbn to '0486295702'>>
<<set _pages to $library[_isbn].pages>>

Book: Name: <<= $library[_isbn].name>>; pages <<= _pages>>
2 Likes