Arrays matching each other?

Having a very weird error. Short answer is I think two arrays are actually pointers to the same array. Long explanation follows.

Two arrays (on two container objects, player_frame and enemy_frame) are initialized as such:

set player_frame.conditions (new Array)
set player_frame.persistent_conditions (new Array)


set enemy_frame.conditions (new Array)
set enemy_frame.persistent_conditions (new Array)

To add conditions to these, I use two setter functions:

set_persistent_condition target condition:
  if (== $target "player_frame"):
    push $player_frame.persistent_conditions $condition
  elseif (== $target "enemy_frame"):
    push $enemy_frame.persistent_conditions $condition
    "Error in set persistent condition, target is %{$target}, condition is %{$condition}"

  run update_hud

set_condition target condition:
  if (== $target "player_frame"):
    push $player_frame.conditions $condition
  elseif (== $target "enemy_frame"):
    push $enemy_frame.conditions $condition
    "Error in set condition, target is %{$target}, condition is %{$condition}"

  run update_hud

Fairly straightforward! So to my confusion, I found that using set_condition as such:

if (== $initiator "enemy_frame"):
  run set_condition "enemy_frame" Resilient
  run set_condition "player_frame" Resilient

set the condition for both arrays!

Screenshot 2023-09-10 at 10.57.13 AM

Using debug statements I’ve determined that it never hits set_persistent_condition, this all goes through set_condition only.

So I’m wondering, is there any chance that both of those arrays are somehow being designated as pointers to the same array? If so, how do we avoid this?

Scratch this! But I’m going to post the answer here so other people don’t run into this:

In my update loop, I did:

set player_frame.conditions $player_frame.persistent_conditions
set enemy_frame.conditions $enemy_frame.persistent_conditions

I believe this is the cause of it, because when I pointedly did something to break that relationship:

set player_frame.conditions (array_concat $player_frame.persistent_conditions (new Array))
set enemy_frame.conditions (array_concat $enemy_frame.persistent_conditions (new Array))

That fixed the issue. An explicit array_copy function that basically just does this would be nice.

Yeah that makes sense, all those things are javascript objects so setting a variable to the value of another object or array will create a reference to it

I added those copy functions recently for one of the jam games in a plugin for similar reasons to what you needed, but I still need to add them back to the engine. You can easily add a similar plugin to your game though (I’ll add the code when I can get it on my pc)

1 Like