Can you copy an object?

BlitzMax Forums/BlitzMax Beginners Area/Can you copy an object?

nawi(Posted 2009) [#1]
1. Can you copy an object?
2. If you can copy an object, how can you copy an object?


ImaginaryHuman(Posted 2009) [#2]
To have two references to the same object you just do:

Local p1:TPixmap=New TPixmap
Local p2:TPixmap=p1

To make a duplicate of an object, so that you have two separate but identical copies, you have to manually copy over all the fields and data.


nawi(Posted 2009) [#3]
I managed to get a object copying function done for simple types, but when you add recursion, and tlists, it just got too complicated. Here's a start if someone wants to try..
It crashes without any error message so it's difficult to debug.

Function Copy:Object(Obj:Object)
	Local id:TTypeId = TTypeId.ForObject(Obj)
	Local NewObj:Object = id.NewObject()
	For Local fld:TField = EachIn id.EnumFields()
		Local nf:TField = GetField(NewObj,fld.Name())
		Local ti:TTypeId = nf.TypeId()
		If ti.Name() = "TList" Then
			'...
		ElseIf ti = ByteTypeId Or ti = ShortTypeId Or ti = IntTypeId Or ti = LongTypeId ..
		Or ti = FloatTypeId Or ti = DoubleTypeId Or ti = StringTypeId Or ti = ObjectTypeId ..
		Or ti = ArrayTypeId Or ti.Fields().Count() = 1 Then 
			nf.Set(NewObj,fld.Get(Obj))
			Print nf.Name()
		Else
			Print nf.Name()
			nf.Set(NewObj,Copy(fld.Get(Obj)))
		EndIf
	Next
	Return NewObj
End Function

Function GetField:TField(Obj:Object,FieldName:String)
	Local id:TTypeId = TTypeId.ForObject(Obj)
	For Local fld:TField = EachIn id.EnumFields()
		If fld.Name() = FieldName Then Return fld
	Next
	Return Null
End Function



MGE(Posted 2009) [#4]
"To make a duplicate of an object, so that you have two separate but identical copies, you have to manually copy over all the fields and data."

Yah...this really sucks.


altitudems(Posted 2009) [#5]
Actually someone created this handy function but I forget who?




Htbaa(Posted 2009) [#6]
Although reflection takes away a lot of hassle it's probably too slow. So, at least for simple objects that need to be cloned a lot I'd say it's better to write a custom clone() method in which you manually copy all the fields to the new object.


Azathoth(Posted 2009) [#7]
Actually someone created this handy function but I forget who?
That would be me.