[Bug]Questions about two-dimensional array

Started by Kenneth Law, Jan 28, 2020, 10:25 AM

Previous topic - Next topic

Kenneth Law

Description
Let's just start with an example.
At first I defined an array
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
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

I had the same issue a long time ago and SLC explained why it occured.
QuoteSLC:
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.
local arr = array(5);
arr.apply(@(_) array(1));

in sqmod, that can be reduced to a statement.
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

first i
Quote from: Kenneth Law on Jan 28, 2020, 10:25 AMArray<-array(2,array(2,0));
and
Quote from: Kenneth Law on Jan 28, 2020, 10:25 AMArray[2][1]
isn't there a problem with indices?

However,
b <-array(2,array(2,0));
b[1][1]=12;
print(b[0][1]);
gave 12. i hope this is the problem.

But, c <- [[0,0],[0,0]]
c[1][1]=122;
print(c[0][1]);
gave 0



Kenneth Law

Thx a lot.
Now problem has been solved.
I am not sure whether you are right but I did it like this
arr <- array(2, null);
arr[0] = [0, 0];
arr[1] = [0, 0];
and it works.