This topic was marked solved by its starter, on November 25th, 2020, 06:37 AM
[Bug]Questions about two-dimensional array

Kenneth Law

  • Newbie
  • Posts: 37
[Bug] Questions about two-dimensional array
«  »
Description
Let's just start with an example.
At first I defined an array
Code: [Select]
Array<-array(2,array(2,0));
And while I changed the value of Array[1][1] to 3, the value of Array[2][1] was also automatically changed to 3, which is not reasonable.
I have tested a lot of times and it was proved that the value of Array[2][1] always equals to that of Array[1][1] no matter how I try to make them two different elements.
Here is the code which I used for test
Code: [Select]
function onScriptLoad()
{
Array<-array(2,array(2,0));
}
function onPlayerCommand( player, cmd, text )
{
if(cmd=="change")
{
if(text&&IsNum(text))
{
Array[1][1]=text.tointeger();
}
}
else if(cmd=="check")
{
MessagePlayer("Array[2][1]: "+Array[2][1],player);
}
}

Reproducible
Always

What you were doing when the bug happened

Not doing anything

What you think caused the bug
Maybe squirrel language doesn't allow the existence of two-dimensional array?

Xmair

  • Wiki Contributor
  • Posts: 951
[Bug] Re: Questions about two-dimensional array
« Reply #1,  »
I had the same issue a long time ago and SLC explained why it occured.
Quote
SLC:
reference to same array(1) is copied to every slot
so you have the same array in every slot of the host array
only fundamental types are copied. i.e. ints, floats, bools, nulls etc.
everything else is copied by reference. as usual
same applies when you create a class and have non-fundamental type members. you initialize them in the constructor instead
in official plugin with (likely) outdated squirrel, the following can be used to go around that issue.
Code: [Select]
local arr = array(5);
arr.apply(@(_) array(1));

in sqmod, that can be reduced to a statement.
Code: [Select]
local arr = array(5).apply(@(_) array(1));

Credits to Boystang!

VU Full Member | VCDC 6 Coordinator & Scripter | EG A/D Contributor | Developer of VCCNR | Developer of KTB | Ex-Scripter of EAD

habi

  • Sr. Member
  • Posts: 287

Kenneth Law

  • Newbie
  • Posts: 37
[Bug] Re: Questions about two-dimensional array
« Reply #3,  »
Thx a lot.
Now problem has been solved.
I am not sure whether you are right but I did it like this
Code: [Select]
arr <- array(2, null);
arr[0] = [0, 0];
arr[1] = [0, 0];
and it works.