Envision, Create, Share

Welcome to HBGames, a leading amateur game development forum and Discord server. All are welcome, and amongst our ranks you will find experts in their field from all aspects of video game design and development.

Copying via .dup

khmp

Sponsor

I have a question in which I first scoured the web for an answer, to no avail. I'm attempting to copy an object which I thought simple enough to do. So I'm trying to use .dup/.clone/= and it copies and all but whatever alteration I make to the duplicate the original is also altered. I guess they both reference the same memory. The question I have is how do I create a copy and have it be new memory? Do I have to write a method that acts as a copy constructor for the object?

Thanks for taking the time to read my problem! :thumb:
 

Zeriab

Sponsor

Both .dup and .clone returns a shallow copy.
Here is a code snippet which should increase your knowledge what is meant with a shallow copy:
Code:
class IntegerContainer
  attr_accessor :integer
  def initialize(value=0)
    self.integer = value
  end
  def inspect
    return integer.to_s
  end
end

a = IntegerContainer.new
b = IntegerContainer.new(2)
c = IntegerContainer.new(5)
d = IntegerContainer.new(-6)
array = [a,b,c]
p array
array2 = array.dup

array2 << d

p array, array2

array[1].integer += 10

p array, array2

If you have questions to this code please do ask ^_^
 

khmp

Sponsor

The problem is the shallow copy with using some simpler objects the behavior is as expected. But what I was trying to copy was a Game_Map. So the code I had was the following:
Code:
  ...
  @new_map = Game_Map.new
  map = Game_Map.new
  map.setup(map_id)
  @new_map = map
  # Made an accessor method for changing width.
  @new_map.width = 40
  p @new_map.width  #-> 40
  p map.width  #-> 40
  ...

But this line particular could be swapped and the result would be the same.
Code:
@new_map = map, @new_map = map.dup, @new_map = map.clone

I solved it but I had to make a copy function. It probably had to do with the map.map being a pointer or something and thus the bane of shallow copy. Thanks though for replying.
 

Thank you for viewing

HBGames is a leading amateur video game development forum and Discord server open to all ability levels. Feel free to have a nosey around!

Discord

Join our growing and active Discord server to discuss all aspects of game making in a relaxed environment. Join Us

Content

  • Our Games
  • Games in Development
  • Emoji by Twemoji.
    Top