Help - Search - Members - Calendar
Full Version: How to disable a 'link'?
RPG RPG Revolution Forums > Scripting > Script Development and Support
Twin Matrix
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
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
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
The issue that's arising only affects objects, not number values. Ruby's funky way with handling pointers.
Atoa
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.
Invision Power Board © 2001-2013 Invision Power Services, Inc.