Union

Started by Frank Brübach, December 28, 2023, 07:29:08 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Frank Brübach

Hi all simple question how to translate this Union Type to oxygen?

1)
union opcodestring
byte s 'ptr
'f as function () as long
'f1 as function ( byval long ) as long
end union

2)
This example Works fine

union utype
{
  byte  b
  short w
  long  i
}


utype v
v.b=42
print v.b

Charles Pegge

That is correct. You can use curly braces, or Basic format:  union ... end union

union utype
  byte  b
  short w
  long  i
end union

utype v
v.b=42
print v.b
print v.w
print v.i

Frank Brübach

Thanks Charles and a function to include is also possible?

f as function() AS Long in my First Code snippets?

Charles Pegge

#3
You can put functions inside a type or class, but not a union

type cc
  function f(int i) as int
    return i*2
  end function
end type
'
dim cc c
print c.f(3) '6

Were you thinking of polymorphic functions?

Frank Brübach

#4
Yes... Like oop structure

A: pets  function speak ()

C: Cats function speak ()
         Meowing

C: dogs: function speak ()
          Barking

C: Birdys: function speak ()
          Chirps

Charles Pegge

Define the cats, dogs and birds as separate classes/types, each containing their own speak method. You could also define the base class pets to contain things they all have in common.

Frank Brübach

#6
Hi Charles Here my First attempt :) 

Never used classes Methods before
Help to fix is Welcome Here
Cinstructor doesn't exists AS command?

' class pets example with oxygen
' test

class multipliers
  method cube(f as float) as float
    return f*f*f
  end method
end class

dim multipliers m
print m.cube 4 '64

''
'-- 1)
class Pet
    method Speak() as string
    end method
end class

'-- 2)
class Cat
    constructor Pet As Pet
    method Speak()
        Print "Meowing"
    end method
end class

class Dog
    constructor Pet As Pet
    method Speak()
        Print "Barking"
    end method
end class

Type Bird
    constructor Pet As Pet
    method Speak()
        Print "Chirping"
    end method
end class

Dim myCat As Cat
myCat.Pet.Speak()

Dim myDog As Dog
myDog.Pet.Speak()

Dim myBird As Bird
myBird.Pet.Speak()

 

Charles Pegge

It's simpler :) (constructor and destructor are methods which you don't need here.)

' class pets example with oxygen

''
'-- 1)
class Pet 'base class
    int head,legs,tail
    method Speak() 'gets overridden
      print "<sound>"
    end method
end class

'-- 2)
class Cat
    pet
    method Speak()
        Print "Meowing"
    end method
end class

class Dog
    pet
    method Speak()
        Print "Barking"
    end method
end class

class Bird
    pet
    method Speak()
        Print "Chirping"
    end method
end class

Dim myCat As Cat
myCat.Speak()

Dim myDog As Dog
myDog.speak()

Dim myBird As Bird
myBird.Speak()

Dim myGrasshopper as pet
myGrasshopper.speak