Swap arrays

Got an idea for enhancing PureBasic? New command(s) you'd like to see?
Trond
Always Here
Always Here
Posts: 7446
Joined: Mon Sep 22, 2003 6:45 pm
Location: Norway

Swap arrays

Post by Trond »

I wish that Swap could be used with arrays, to simply swap the names/pointers to the array.
JustinJack
User
User
Posts: 89
Joined: Thu Feb 04, 2010 7:34 am
Location: Decatur, TX
Contact:

Re: Swap arrays

Post by JustinJack »

Hey, it can...try this:

Code: Select all

Dim Test1(5)
Dim Test2(5)

For k = 1 To 5
    Test1(k) = k
Next

For k = 1 To 5
    Test2(k) = k + 5
Next

Debug "Before Swap:"
Debug "Test1:"
For k = 1 To 5
    Debug Test1(k)
Next
Debug #CRLF$
Debug "Test2:"
For k = 1 To 5
    Debug Test2(k)
Next

Swap @Test1(), @Test2()

Debug #CRLF$
Debug "After Swap:"
Debug "Test1:"
For k = 1 To 5
    Debug Test1(k)
Next
Debug #CRLF$
Debug "Test2:"
For k = 1 To 5
    Debug Test2(k)
Next
I haven't found it in the PureBasic help Library, but it's very handy, you can assign arrays pointers too...like this:

Code: Select all


Procedure.l getMiscData()
    *myPtr = AllocateMemory(12)
      ; Set asside enough memory for three long integers (4 bytes ea.)
      PokeL(*myPtr, 123)
      PokeL(*myPtr+4, 456)
      PokeL(*myPtr+8, 789)
    ProcedureReturn *myPtr
EndProcedure

*thisPtr = getMiscData()

Dim myArray.l(MemorySize(*thisPtr)/4) ; same as Dim myArray.l(3)

myArray() = *thisPtr

For k = 0 To 2
    Debug myArray(k)
Next
FreeMemory(*thisPtr)

Hope it helps, I use it all the time..
User avatar
skywalk
Addict
Addict
Posts: 4211
Joined: Wed Dec 23, 2009 10:14 pm
Location: Boston, MA

Re: Swap arrays

Post by skywalk »

@JustinJack, Your solution does not work for arrays passed to procedures, but will if the arrays are global.

This is an often discussed topic, and I would use it if implemented. :)
Post Reply