How not to copy an Array

BlitzMax Forums/BlitzMax Beginners Area/How not to copy an Array

Grey Alien(Posted 2006) [#1]
Oops, I wrote some code similar to the example below to make a copy of an array and then modify the copy. However, it just points to the original array (obviously doh!) and doesn't copy it, so this code outputs 10,10 - not 10,1. However, comment out Local a2[]=a1 and uncomment the line below and it will work because using slices makes a copy of the array. Just thought I'd post this so other beginners won't make the same mistake that I did.

Strict
Local a1[] = [1,2,3,4,5]
Local a2[]=a1
'Local a2[]=a1[0..Len(a1)]

a2[0] = 10
Print a2[0]
Print a1[0]



Dreamora(Posted 2006) [#2]
On the slicing: You can clone the whole array far easier:

local a2:int[] = a1[..]


But your point on that is right. As an array is a type inherited from :Object, assigning it to something only changes the reference of the array, not its content.


Grey Alien(Posted 2006) [#3]
thanks for the .. tip.


Yan(Posted 2006) [#4]
Just for the record...
Print "My ears hurt!"
...wont copy an array either.

;o)


Dreamora(Posted 2006) [#5]
If you have nothing to say, why not follow rule one: don't say anything, just to raise your "get on their nuts" count.


Yan(Posted 2006) [#6]
...And I always thought you were a big fan of inane posts?


Grey Alien(Posted 2006) [#7]
I thought it was quite funny :-) and generally I don't mind my threads deterioratig, but I can see how it would annoy others.


Yan(Posted 2006) [#8]
I agree, there's a time and a place for such comments and as I know you're partial to a bit of 'threadular silliness(TM)' I didn't see the harm.


H&K(Posted 2006) [#9]
Lets face it the first post was a solution with explination, the second was an expansion of the solution, what else was there to post? "Well Done/ Thanks Dream/Grey"?

At least Yans post was funny whilst being pointless, but Dreams "Dont post if you have nothing to add", was pointles and unfunny.

You really need to get a sence of humour Dream. Hahahahaha


Dubious Drewski(Posted 2006) [#10]
Thanks Grey, I forgot about that jazz.

Everyone else:

That's right

Best thread ever.


Blitzplotter(Posted 2006) [#11]
Cheers Grey, you never know when a coding tit-bit might help the masses, I've no doubt you did a search on copying arrays and came up blank - now all can benefit from 'how to copy arrays...'


Grey Alien(Posted 2006) [#12]
I've no doubt you did a search on copying arrays and came up blank
you put too much faith in me. I just blindly posted ;-)