News:

PlayBASIC2DLL V0.99 Revision I Commercial Edition released! - Convert PlayBASIC programs to super fast Machine Code. 

Main Menu

Swapping Typed Cells In Arrays

Started by kevin, February 28, 2010, 08:02:00 AM

Previous topic - Next topic

kevin

 Swapping Typed Cells In Arrays

 This little example demo's how you can manually swap a pair of cells within a typed array.  
     


PlayBASIC Code: [Select]
   Type tObject
Name$
X#,y#
EndType

Dim Stuff(10) as TObject


// Swapping The Handles Safely
//
// Normally we'd swap using this type of logic
//
// Temp = Item1
// Item1 = Item2
// Item2 =Temp
//
// This is fine for integers/floats and strings, but not typed banks
// within type arrays/lists. As if you write over an existng type, it'll get
// freed..
//
// One way aroudn this is peek/poke the array list the function bellow does
// This removes any catch of the PB freeing the data, but it does mean you hve to
// to be a little more careful.
//

Stuff(1) = New TObject
Stuff(1).Name$ ="Joe"
Stuff(1).x# =100
Stuff(1).Y# =101


Stuff(2) = New TObject
Stuff(2).Name$ ="Bill"
Stuff(2).x# =200
Stuff(2).Y# =201



// Display the 'handle' of this cells
Print "Handles of Both Banks"
print Stuff(1)
print Stuff(2)


// Since cell 5 and 1 are point at the same data, if i delete one of them
// the other is doomed
print ""
print "results before swap"
print ""
print Stuff(1).name$
print Stuff(1).x#
print Stuff(1).y#

print Stuff(2).name$
print Stuff(2).x#
print Stuff(2).y#


SwapCells(1,2)


// Display the 'handle' of this cells
print ""
print ""

print "results after Swap"
print ""

Print "Handles of Both Banks"
print Stuff(1)
print Stuff(2)
print ""
print Stuff(1).name$
print Stuff(1).x#
print Stuff(1).y#

print Stuff(2).name$
print Stuff(2).x#
print Stuff(2).y#




Sync
Waitkey




Function SwapCells(Index1,Index2)
Ptr=getArrayPtr(Stuff())
// Here we really should sanity check the pointer, as the Array might not exist !

CellZeroPtr=Ptr+PBArrayStruct_size

// Here it should sanity check the users inputs,

Index1*=4
Index2*=4

// Read the bank handles from both cells
TypeBank1=PeekInt(CellZeroPtr+Index1)
TypeBank2=PeekInt(CellZeroPtr+Index2)

// write them back in the oppisite order
PokeInt CellZeroPtr+Index1, TypeBank2
PokeInt CellZeroPtr+Index2, TypeBank1

EndFunction







The same type of approach can also be used on Typed Variables / Type Lists