Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Pushing 2d array into array and editing problem

edited July 2016 in Help! with 2.0
I am pushing an 2d array into an array and trying to edit the starting array between the 2 pushes and also the ending array after the pushes. both give the same results, the effects happen to both of the arrays here is a simple code to show the problem clearly. I am trying to make a large array of characters with lots of data by having a so called template 2d array, randomizing it a bit then adding it to a large array of characters and repeating the processes.
<<set $x=[[1,2,3],[4,5,6]]>>
<<set $y=[]>>

<<set $y.push($x)>>
<<set $x[1][1]=70>>
<<set $y.push($x)>>
<<set $y[0][0][0]=9>>

<<print $y>>


prints out 9, 2, 3, 4, 70, 6, 9, 2, 3, 4, 70, 6

I am taking that this is pass by reference, but how do you pass by value then?
Not sure if this is the best way to do this, any ideas, comments are appreciated.

Thanks

Comments

  • You have use SC2's documented clone() function to add different copies of the same $x array to your $y array.
    <<set $x to [[1,2,3],[4,5,6]]>>
    <<set $y to []>>
    
    <<set $y.push($x)>>
    <<set $y.push(clone($x))>>
    
    <<set $x[1][1] to 70>>
    
    x: $x
    y: $y
    

    WARNING:
    Each time the Reader navigates from one passage to the next a copy of all known story variables is made, and it is this new copy that is made available to the next passage being display. This process can have two effects:

    a. It causes any variables that were referencing the same object (array, etc) to now be referencing their own copy of that original object, not the same copy.

    b. If you have Config.history.maxStates set to any number but one (it is 100 by default) then multiple copies of all known variables will be stored in the History system, one for each instance of each passage the Reader has navigated to. This can result in the Reader's not being able to save the story and/or their web-browser running out of memory.

    If some of your collections contain data that does not change for the life-cycle of the story then you should think about storing those collections somewhere other than story $variables, somewhere like the setup special variable
Sign In or Register to comment.