Page 1 of 1

Return Array

Posted: Sat Dec 17, 2016 4:09 pm
by coder14
Is it possible to return an array from a procedure maybe by its pointer?

Re: Return Array

Posted: Sat Dec 17, 2016 4:54 pm
by fryquez
It can be done with a Structure.

Code: Select all

EnableExplicit

Structure BuildArrayHelper
  Array _array.s(1)
EndStructure

Procedure BuildArray()
  Protected *Array.BuildArrayHelper
  
  *Array = AllocateMemory(SizeOf(BuildArrayHelper))
  InitializeStructure(*Array, BuildArrayHelper)
  
  ReDim *Array\_array(6)
  
  *Array\_array(0) = "Hello"
  *Array\_array(1) = "I'am"
  *Array\_array(2) = "an"
  *Array\_array(3) = "Array"
  *Array\_array(4) = "returned"
  *Array\_array(5) = "from"
  *Array\_array(6) = "Procedure"
  
  ProcedureReturn *Array
EndProcedure

Define *Array.BuildArrayHelper = BuildArray(), x

For x = 0 To ArraySize(*Array\_array())
  Debug *Array\_array(x)
Next

;free Memory if no longer needed
ClearStructure(*Array, BuildArrayHelper)

Re: Return Array

Posted: Sat Dec 17, 2016 5:38 pm
by mk-soft
A clean method is to pass an array byref

Code: Select all

Procedure InitData(Array data1(1))
  Protected i
  
  ReDim data1(10)
  For i = 0 To 10
    data1(i) = i + 1000
  Next
  ProcedureReturn ArraySize(data1())
  
EndProcedure

Global Dim MyData(0)

Debug InitData(MyData())
For i = 0 To 10
  Debug MyData(i)
Next

Re: Return Array

Posted: Sat Dec 17, 2016 6:53 pm
by Bisonte
mk-soft wrote:A clean method is to pass an array byref
And the same with Maps() and Lists() !

Re: Return Array

Posted: Sun Dec 18, 2016 12:27 am
by coder14
Sorry guys - I need to RETURN an array. So far only the structure seems to work although I prefer to not use structures. Can it be done with maps or lists maybe?

Re: Return Array

Posted: Sun Dec 18, 2016 7:18 am
by Fred
You can allocate a memory buffer of the array size and copy all the elements in it

Re: Return Array

Posted: Sun Dec 18, 2016 10:02 am
by coder14
Fred wrote:You can allocate a memory buffer of the array size and copy all the elements in it
Thanks Fred. I'm not quite sure how to do that but I'm trying. :D

Re: Return Array

Posted: Sun Dec 18, 2016 12:20 pm
by Bisonte
This is a variant :

Code: Select all

Structure struct_array
  a.i
  b.s
EndStructure

Dim arr_struct.struct_array(9)

;: Fill Arrays
For i=0 To 9
  arr_struct(i)\a = Random(100,1)
  arr_struct(i)\b = Str(i)
Next i

Procedure GetOneStructArray(Array arr_struct.struct_array(1), Number.s = "3")
  
  Protected i, Result = 0
  
  For i=0 To 9
    If arr_struct(i)\b = Number
      Result = @arr_struct(i)
      Break
    EndIf
  Next i
  
  ProcedureReturn Result
  
EndProcedure

Original = @arr_struct(3)
fromProc = GetOneStructArray(arr_struct(), "3")

*Single.struct_array
*Single = fromProc

Debug Original
Debug fromProc
Debug "Result : "
Debug *Single\b