0 votes
by (1.1k points)
edited by

I tried the same way as in javascript and it did not work. I have an array of objects so I tried to access the last member as follows...

$myArray[$myArray.length - 1].name

$myArray[- 1].name

Usually I mistake in some small detail.

I tried to change a variable inside an array of objects by the textbox.

<<set $myArray = []>>

<<set $myArray.push( {
	name: ''
} )>>

<<textbox "$myArray[$myArray.length - 1].name" ''>>

And then...

<<print $myArray[$myArray.length - 1].name>>

But the final value remains blank for some reason.

2 Answers

+1 vote
by (68.6k points)
selected by
Best answer

In general, your problem is not how you're attempting to access the last member of the array.  SugarCube is mostly a thin layer over JavaScript, so the syntax is exactly the same.

Your problem is that the system used by the <<textbox>> macro to resolve the variable you're passing it only supports static identifiers and variables within the square bracket notation.  Meaning, the arithmetic you're performing there is unsupported.


The following should work as long as you're attempting to use it within the same passage:

<<set _ref to $myArray[$myArray.length - 1]>>\
<<textbox "_ref.name" "">>

It works by taking a reference to the object within the array and passing that to the macro.


Alternatively.  If you use a button/link to move to the next passage you could do something like the following instead:

<<textbox "_name" "">>

<<link [[Continue|Some other passage]]>>
	<<set $myArray[$myArray.length - 1].name to _name>>


by (1.1k points)
Really, thank you very much for your help. Although I also want to learn this using JS because it is a much broader language.
by (68.6k points)
I edited my answer in your other question to add some details about how to access story and temporary variables within pure JavaScript.
–1 vote
by (23.6k points)

With this you'll have to use the <<print>> macro. Something like the following should work:

<<print "$myArray[$myArray.length - 1].name">>

You can also just use <Array>.last() instead.


by (1.1k points)
The print worked though I still can not modify the variable with textbox. I'll try to explore alternatives...