[Gambas-user] Array question

ron ronstk at ...239...
Mon Oct 11 16:22:10 CEST 2004


On Monday 11 October 2004 14:15, Paolo Saudin wrote:
> ron wrote:
> 
> >On Saturday 09 October 2004 11:11, Paolo Saudin wrote:
> >  
> >
> >>Hi all,
> >>I need to use a multidimensional array ( x1[0][0] , x1[0][1] , x1[1][0] 
> >>, x1[1][1] ...  ) and at a certain time,
> >>I want to copy it in a bakup array in order to work with the new one 
> >>without loose the original data.
> >>Here's my problem : when I copy ( x2=x1.copy() ) a single dimension 
> >>array all it works as expected,
> >>but as soon as I use a multidimensional one, the original is treated as 
> >>a "referenced" copy and get modified as well.
> >>Attached there is an example to demonstrate it clearer :-). Is there 
> >>another way to deep copy two arrays?
> >>
> >>Many thanks,
> >>Paolo
> >>
> >>    
> >>
> >
> >the array.copy is not an new array with a copy of the content.
> >It is the same but with a different name.
> >
> >arrB = arrA.copy()
> >arrB is the same as aarA only the name differs.
> >
> >The exact name should be .Clone() I think.
> >or arrB.Alias( arrA ) or arrB.Link(arrA)
> >
> >A copy is an new instance of it with the content of the source.
> >
> >  
> >
> I tried but the only methods available for a Variant[] are _Add  Clear  
> Copy  Insert  Pop  Push  Remove  Resize  Reverse  Sort
> _and so I couldn't manage to really get a copy of the array. In the 
> Gambas-wiki, the copy() function is said to return a true copy of it,
> if I understand it correctly ?. FUNCTION Copy ( ) AS Variant[] Returns a 
> deep copy of the array.
> Paolo
> 

arrB = arrA.copy()
arrB is the same as arrA only the name differs.

It has been already somewehre in the mail list to.
Benoit had say that arrB _is_ the _same_ array as arrA.
That is not a stand alone copy but have a alternate name
for the same array.

You want however a new array as arrB with a copy of the content of arrA.

The possible way is next example:


Function ArrClone(arrA as yourtype[]) as yourtype[]
 dim i as integer
 dim arrB as new yourtype[]

 for i=0 to arrA.count-1
   arrB.add(arrA[i]) 
   'copy the first dimension elements 
   'The arrA[i] can be a array itself. 
 next
 return arrB
END

You can use it by: arrB= ArrClone(arrA)

arrA[0][3] = "arr03"
arrB = ArrClone(arrA)
print arrB[0][3] 'gives "arr03"
arrB[0][3] = "brr30"

print arrA[0][3] 'gives "arr03"
print arrB[0][3] 'gives "brr30"

"yourtype" should be the type you realy want. :)


This is not tested code. Its an example how it could be!!














More information about the User mailing list