How not to copy an Array

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

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]


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.

thanks for the .. tip.

Just for the record...
Print "My ears hurt!"
...wont copy an array either.

;o)

If you have nothing to say, why not follow rule one: don't say anything, just to raise your "get on their nuts" count.

...And I always thought you were a big fan of inane posts?

I thought it was quite funny :-) and generally I don't mind my threads deterioratig, but I can see how it would annoy others.

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.

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

Thanks Grey, I forgot about that jazz.

Everyone else:

That's right

Best thread ever.

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...'

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 ;-)