Author Topic: How to return an UDT as the result of a function?  (Read 1435 times)

0 Members and 1 Guest are viewing this topic.

  • Guest
How to return an UDT as the result of a function?
« on: September 30, 2018, 02:55:50 PM »
And I mean to return an UDT, not passing a variable by reference to receive the result or something like that. I just want to know if O2 can return an UDT or not.

This does not compile.

Code: [Select]
type MyUdt double x,y

function Foo () as MyUdt
   dim z as MyUdt
   z.x = 123
   z.y = 34
   return z
end function

Like with classes (called Type in FreeBasic), FreeBasic can do it by creating a temporary copy of the UDT on the fly and returning it. The temporary copy destoys itself.
« Last Edit: September 30, 2018, 03:32:27 PM by José Roca »

Charles Pegge

  • Guest
Re: How to return an UDT as the result of a function?
« Reply #1 on: September 30, 2018, 06:19:54 PM »
The straight answer is no.

But we have macro-functions which 'return' temp variables. (You can also create operator sets for UDTs using the macro system.)

Code: [Select]
type MyUdt double x,y

function Foo () as MyUdt
   dim z as MyUdt
   z.x = 123
   z.y = 34
   return z
end function
--->
macro Foo MyUdt (z)
   z.x = 123
   z.y = 34
end macro
« Last Edit: September 30, 2018, 06:27:30 PM by Charles Pegge »

José Roca

  • Guest
Re: How to return an UDT as the result of a function?
« Reply #2 on: October 01, 2018, 12:11:36 AM »
And how to use it? This does not compile:

Code: [Select]
macro Foo MyUdt (z)
   z.x = 123
   z.y = 34
end macro

dim z AS MyUdt = Foo(z)

Charles Pegge

  • Guest
Re: How to return an UDT as the result of a function?
« Reply #3 on: October 01, 2018, 12:15:04 AM »
You need an operator & function set to go with the type.

This is a small set to illustrate:

Code: [Select]
type MyUdt
  double x,y
end type

macro MyUdt_op
  '
  macro ."load" (acc,a) 'mandatory
 
    acc.x=a.x
    acc.y=a.y
  end macro
  '
  macro ."+" (acc,a)
    acc.x+=a.x
    acc.y+=a.y
  end macro
  '
  macro ."save" (a,acc) 'mandatory
    a.x=acc.x
    a.y=acc.y
  end macro
  '
  macro ."foo" (z)
    z.x = 123
    z.y = 34
  end macro
  '
  macro ."import" (z,a,b)
    z.x = a
    z.y = b
  end macro
  '
  macro ."str" string (s,z)
    s=str(z.x)+", "+str(z.y)
  end macro
  '
end macro


'myudt v=foo()
'dim myudt v=foo()
dim as myudt v=foo()
'dim v as myudt = foo() 'not working
print v.y
'
myudt va,vb,vc
va=foo()
vb=va+va
print vb.y '68
'
vc=foo()+foo()+va
print vc.y '102
'
vc=va+import(1000,100)
print vc.y '134
'
print ""+str(vc) '1123,134
'