[RMXP] RUBY'S INCREDIBLE REFERENTIAL ABILITY IS ROADBLOCK

Posts

Pages: 1
Hello,

I'm attempting to store a sprite and some of its values into a premade array "grid". Like so:


sprite = Sprite.new
sprite.x = x_value
sprite.y = y_value
sprite.z = z_value
@sprites[nested_array_1][nested_array_2][nested_array_3][0] = sprite
@sprites[nested_array_1][nested_array_2][nested_array_3][1] = sprite.x
@sprites[nested_array_1][nested_array_2][nested_array_3][2] = sprite.y
@sprites[nested_array_1][nested_array_2][nested_array_3][3] = sprite.z


The "nested_array"s change around depending on which variable is active. This is inside a small method which is remaking the same graphic called "sprite" over and over, different each time, and storing it into a grid array. Or at least, that's what I'd like to do.

My problem, is that storing the items into the array in this fashion... well... because Ruby is so amazingly referential, it's storing the last value of the last code execution of "sprite" into EVERY array I operate on. These "sprite"s aren't copies, they're references to that one single object. If I have a whole bunch of "sprite"s that are at X 0 and then the very last sprite is at X 640, then all of them in my arrays become 640.

My question is, how do I copy "sprite" to the array without making it a reference? I know that .push does this, but .push always copies the object to the end of an array. How do I copy the object into a specific position in the array?
Why not just make a new sprite each time? For your situation I think you need to store it as a duplicate or clone

@sprites[nested_array_1][nested_array_2][nested_array_3][0] = sprite.dup

or .clone
Thanks for the answer.

I didn't know it were possible to .dup or .clone a sprite. Can any object be cloned?

After doing some more research, I found out that the real reference problem was that I didn't initialize my dimensional arrays properly. I used:


array_part = Array.new(4, [0,0,0,0])
nested_array1 = Array.new(4, array_part)
nested_array_a = [nested_array1, nested_array2, ..]


...when I should have put the "Array.new"s inside execution blocks (the curly braces), like so:


nested_array1 = Array.new(4) { Array.new(4) { [0,0,0,0] } }
nested_array_a = [nested_array1, nested_array2, ..]


This kept them separate and non-referential.
Pages: 1