SugarCube arrays problem

Twine Version:2.3.6
Story Format: Sugarcube 2.30.0`
Hi everyone, I encountered a strange behaviour of sugarcube arrays and I’m not able to find the problem.

I have a simple random event system working with arrays, the code looks as follows:

StoryInit

<<set $Events = ["gen01", "gen02"]>>
<<set $EventsActive to []>>

Passage

<<if $EventsActive.length is 0>><<set $EventsActive to $Events>><</if>>
<<set $EventCur to $EventsActive.pluck()>>
<<if $EventCur is "gen01">>

… etc

The idea is that in $Events, the elements should remain intact, while the system cycle through the events. The issue is that the line <<set $EventCur to $EventsActive.pluck()>> removes one random element not only from $EventsActive array, but from the $Events array as well. Either I’m missing something absolutely basic, or this is a bug(I guess the former is true). Either way I’m asking for your help.

Your issue is this bit.

<<set $EventsActive to $Events>>

You’re passing a reference, not a copy.

When you have an object (an array is a type of object) and you say that A = B, you’re not saying that A holds the same items as B, you’re actually saying: A is another name for B. Whenever I mention A, I'm actually talking about B.

Does that make sense? So when you’re deleting from A, you’re deleting from B. When you’re looking at A’s items, you’re actually looking at B’s items.

To avoid this and get the result that you’re looking for, SugarCube provides a handy function called clone(), which will copy of every item of B into A, so that it really does say that A holds the same items as B.

This should get what you what you want.

<<if $EventsActive.length is 0>><<set $EventsActive to clone($Events)>><</if>>
1 Like

It does make perfect sense. Actually you not only solved this problem, but you saved me from many problems in the future, 'cause I use similar method quite often. So thank you very much!

1 Like