Twin Matrix
Oct 10 2011, 02:05 AM
Say that I want to store the old stats in a variable like so:
@old_stats[i][2] = $game_party.actors[i].states
What happens is that when the states update, the old_stats actually update as well without me directly touching them. I'm guessing this is because it's a link -- because I directly made old_stats[i][2] the states.
If I do this it works:
@old_stats[i][2] = []
for i2 in 0...$game_party.actors[i].states.size
@old_stats[i][2][i2] = $game_party.actors[i].states[i2].to_i
end
But to be honest I've never seen this before and it looks pretty crappy. I'm sure there's a better way of disabling the link? Of making @old_stats[i][2] a simple variable on its own that doesn't automatically update. (Though if such a thing doesn't exist and the fault lies somewhere else, please do correct me.)
Atoa
Oct 10 2011, 03:06 AM
States are arrays, when you define an variable equal an array, it stores the *whole* array, including it memory address. (This happens with many types of objects in fact)
So if you make
@array_1 = [1,2,3]
@array_2 = @array_1
any change you do to @array_2 will take effect on @array_1and vice versa, since they're basically the same object
To solve that, you can make a duplicate of the array
@array_1 = [1,2,3]
@array_2 = @array_1.dup
that way, the array will have the same value, but WILL NOT be the same. So the chances won't affect both.
The second alternative you posted works because you're not assing the array the same as another, but simply making a new array (@old_stats[i][2] = []) and adding values in the same order as the other one.
Twin Matrix
Oct 10 2011, 10:14 AM
Perfect! Thank you for explaining. I assume then that this is not the case when copying simple variables?
e.g. old_stats = $game_party.actors[i].hp
Night5h4d3
Oct 10 2011, 10:41 AM
The issue that's arising only affects objects, not number values. Ruby's funky way with handling pointers.
Atoa
Oct 10 2011, 03:18 PM
In fact it affects various types of object, (arrays, hashes, strings, and custom classes like window, game_battler, and such) but not numeric values. (in fact numeric is the only object that come in mind with this kind of behavior, i don't remember any other).
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please
click here.