Howdy, Stranger!

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

[SugarCube] Updating arrays

edited May 2016 in Help! with 2.0
Okay, I feel like I'm losing my mind. I've got a passage that is intended to take an array representing a group of people and split it into two arrays representing two groups of nearly-identical characteristics except the population is halved. The new arrays would then be saved into the master array of.

I copy the array into two new arrays ($original and $split) and then halve the population variables (in index 3). However, for reasons I cannot figure out, both halving operations are somehow applied to both arrays as well as the master array.

CODE:
We're splitting this population:

Prime:
<<print $units[$unit]>>
   
<<set $original = $units[$unit] ; $split = $units[$unit] ; $original[3] = Math.ceil($original[3]/2) ; $split[3] = Math.floor($split[3]/2) >>

Original:
<<print $original>>

New Pop:
<<print $split>>
 
UNIT:
<<print $units[$unit]>>

[[Dashboard]]

RESULT:
We're splitting this population:

Prime:
Hoafolk Clan, 34, 27, 28, 910, 0, 100, 20, 20, 71,44,91,63,62, 0,0,0, 0,0,14

Original:
Hoafolk Clan, 34, 27, 7, 910, 0, 100, 20, 20, 71,44,91,63,62, 0,0,0, 0,0,14

New Pop:
Hoafolk Clan, 34, 27, 7, 910, 0, 100, 20, 20, 71,44,91,63,62, 0,0,0, 0,0,14

UNIT:
Hoafolk Clan, 34, 27, 7, 910, 0, 100, 20, 20, 71,44,91,63,62, 0,0,0, 0,0,14

I'm sure I'm overlooking something stupid, but I cannot for the life of me find the problem!

Comments

  • edited May 2016
    Okay, if I modify the initial definitions of $original and $split to copy out each index of $units[$unit] into the new arrays, I can modify the population just fine. However, if I try to modify the nested arrays (for splitting their equipment in index 11, for instance) it still gets applied to both child arrays and the $units[$unit].

    I'm thinking this would be consistent if copying these arrays copies not the values within the arrays themselves but references to variables elsewhere. So using the simple declaration quoted above, I'm not copying values, I'm copying references. Then whenever I try to modify $split, I'm actually modifying the floating variables floating out there which $units[$unit] also references.

    So if that is all correct, the question becomes: how do I copy the actual values and not references?
  • Aha. Once I figured out how to ask the right question, I found the answer at https://twinery.org/forum/discussion/5982/how-do-i-copy-an-object-properly-in-sugarcube/p1

    The answer, for those playing at home, is:
    <<set $original = clone($units[$unit]) ; $split = clone($units[$unit])>>
    
Sign In or Register to comment.