vJass "operator" keyword

Grundy

Ultra Cool Member
Reaction score
35
Can anyone explain to me what the "operator" keyword does, and how to use it?

I'm trying to look at the manual and the page keeps timing out, i don't know why.
 

Romek

Super Moderator
Reaction score
964
I don't know why you are unable to view the manual, but here you go:

Taken from JassHelper Manual 0.9.E.0
Operator making

Jasshelper allows you to declare custom operators for your structs, these operators would then be converted to method calls, vJass currently allows operators for <, > , array set and array get.

The official name for this process (In wikipedia and books) is operator overloading. In the case of vJass, An overloaded operator is a method, but it gets operator as name, after the operator keyword you specify the operator being overloaded.

An example is worth 1000 words:


JASS:
    struct operatortest
        string str=&quot;&quot;

        method operator [] takes integer i returns string
            return SubString(.str,i,i+1)
        endmethod

        method operator[]= takes integer i, string ch returns nothing
            set .str=SubString(.str,0,i)+ch+SubString(.str,i+1,StringLength(.str)-i)
        endmethod

    endstruct


    function test takes nothing returns nothing
     local operatortest x=operatortest.create()
        set x.str=&quot;Test&quot;
        call BJDebugMsg( x[1])
        call BJDebugMsg( x[0]+x[3])

        set x[1] = &quot;.&quot;
        call BJDebugMsg( x.str)
    endfunction



By this example we are overloading the [] operator and giving it a new function for the objects of type operatortest. The operator [] specifies the replacement for array get and []= is the replacement for array get.

After inspecting the code you may notice that we are making the string function as an array of strings (or actually characters)

The [] operator requires 1 argument (index), the []= operator requires 2 arguments (index and value to assign). [] must return a value.

[] and []= operators can also be declared as static. This might have some uses, the struct name is going to be allowed to use index operators.

There is a lot of criticism towards operator overloading since it allows programmers to make code that does not make sense, please use this feature with responsibility.

You can also overload < and > , notice that there is only syntax to declare < by declaring it you are forcefully determining an order relation for structs of that type. So it automatically makes > based on your < declaration.


JASS:
    struct operatortest
        string str=&quot;&quot;

        method operator [] takes integer i returns string
            return SubString(.str,i,i+1)
        endmethod

        method operator[]= takes integer i, string ch returns nothing
            set .str=SubString(.str,0,i)+ch+SubString(.str,i+1,StringLength(.str)-i)
        endmethod

        method operator&lt; takes  operatortest b returns boolean
            return StringLength(this.str) &lt; StringLength(b.str)
        endmethod

    endstruct


    function test takes nothing returns nothing
     local operatortest x=operatortest.create()
     local operatortest y=operatortest.create()

        set x.str=&quot;Test...&quot;
        set y.str=&quot;.Test&quot;

        if (x&lt;y) then
            call BJDebugMsg(&quot;Less than&quot;)
        endif
        if (x&gt;y) then
            call BJDebugMsg(&quot;Greater than&quot;)
        endif
    endfunction



In the example, an object of type operatortest is considered greater than another object of that type if the length of its str member is greater than the length of the other object's str member.

operator< must return a boolean value and take an argument of the same type as the struct.

Operators are interface friendly meaning that an interface may declare operators, there is a catch and it is that the operator< must be declared without signature in an interface. Also when using > or < to compare interface objects both instances must have the same type, otherwise the function would halt before performing the comparisson, if debug mode was enabled when compiling, it will also show a warning message.

JASS:
    interface ordered
        method operator &lt;
    endinterface

    interface indexed
        method operator [] takes integer index returns ordered
        method operator []= takes integer index, ordered v returns nothing
    endinterface

    function sort takes indexed a, integer from, integer to returns nothing
     local integer i
     local integer j
     local ordered aux

        set i=from
        loop
            exitwhen (i&gt;=to)
            set j=i+1
            loop
                exitwhen (j&gt;to)
                if (a[j]&lt;a<i>) then
                    set aux = a<i>
                    set a<i> = a[j]
                    set a[j] = aux
                endif
                set j=j+1
            endloop

            set i=i+1
        endloop
    endfunction</i></i></i>


This is an interface for a sorting algorithm. We may now declare custom types that work to sort stuff:


JASS:
    struct integerpair extends ordered
        integer x
        integer y

        method operator&lt; takes integerpair b returns boolean
            if (b.x==this.x) then
                return (this.y&lt;b.y)
            endif
            return (this.x&lt;b.x)
        endmethod
    endstruct

    type ipairarray extends integerpair array [400]

    struct integerpairarray extends indexed
        ipairarray data

        method operator[] takes integer index returns ordered
            return ordered( this.data[index] )
        endmethod

        method operator[]= takes integer index, ordered value returns nothing
            set this.data[index] = integerpair( value)
        endmethod
    endstruct


Of course, it is just an example, the logical way would be using quicksort, operators are also good since they would also allow textmacros to use them, the same sorting textmacro might then be compatible with integer, real and any struct with overloaded < operator.

More things we can do with custom operators

One thing is to overload [], >, <, you can also make a method mimic a field, to keep abstraction and simplify syntax.

JASS:
struct X
    integer a=2
    integer b=2

    method operator x takes nothing returns integer
        return this.a*this.b
    endmethod

    method operator x= takes integer v returns nothing
        set this.a=v/this.b
    endmethod


endstruct



function test takes nothing returns nothing
 local X obj= X.create()

    set obj.x= obj.x + 4

    call BJDebugMsg(I2S( obj.x) ) //outputs 8
    set obj.b=4

    call BJDebugMsg(I2S( obj.x) ) //outputs 16

endfunction
You can use this to implement read only fields:

struct X
    private integer va=2

    method operator a takes nothing returns integer
        return this.a
    endmethod

endstruct



function test takes nothing returns nothing
 local X obj= X.create()

    call BJDebugMsg(I2S( obj.a) ) //This is legal

    set obj.a=2 //this is not

endfunction

More importantly, you can use it to implement fields that take extra provisions for assigments:

JASS:
struct movableEffect

    private unit dummy
    private string rfx
    private effect uniteffect

    //...
        //(A lot of code implementing other actions and creation)
    //...

    method operator x takes nothing returns real
        return GetUnitX(this.dummy)
    endmethod

    method operator y takes nothing returns real
        return GetUnitY(this.dummy)
    endmethod

    method operator x= takes real value returns nothing
        call SetUnitX(this.dummy, value)
    endmethod

    method operator y= takes real value returns nothing
        call SetUnitY(this.dummy, value)
    endmethod


    method operator effectpath takes nothing returns string
        return this.rfx
    endmethod

    method operator effectpath= takes string path returns nothing
        set this.rfx=path
        call DestroyEffect( this.uniteffect)
        set this.uniteffect = AddSpecialEffectTarget(this.dummy, path, &quot;origin&quot;)
    endmethod

endstruct


function moveRandom takes movableEffect me returns nothing
    set me.x= me.x + GetRandomReal(-50,50)
    set me.y= me.y + GetRandomReal(-50,50)
endfunction

function toFire takes movableEffect me returns nothing
    set me.effectpath =&quot;war3mapimporte\\cutefireeffect.mdl&quot;
endfunction

Hint: With operators like .fieldname= and []= it is possible to have a return value in the method, however this return value would almost always be impossible to get from outside the function, there is an exception, and it is when these methods return a value of the struct's type, then it will get translated to an assignment. For example, instead of call var_set(object,45), the result would be set object=var_set(object,45)
 

Grundy

Ultra Cool Member
Reaction score
35
Well I'm not at home right now so I don't have my local copy to look at. I found a link on these forums to the manual and that page keeps timing out for me.

Thanks for pasting that for me. So you can (among other things) make "properties" using the operator keyword... This could be very useful to me...
 

Grundy

Ultra Cool Member
Reaction score
35
Well I know what a properties are but I'm not sure how I would explain them to someone...

Here's an example of how it would lookin VB.NET
Code:
Class Person
	Private sFirstName As String
	Private sLastName As String

	Public Property FirstName As String
		Get
			return sFirstName
		End Get
		Set (value As String)
			sFirstName = value
		End Set
	End Property

	Public Property LastName As String
		Get
			return sLastName
		End Get
		Set (value As String)
			sLastName = value
		End Set
	End Property

	Public ReadOnly Property FullName As String
		Get
			return sFirstName + " " + sLastName
		End Get
	End Property
End Class

Then somewhere else in your program, you could use the class like so (BTW the ' means everything after it is a comment. it's the same as "//" in jass):
Code:
Dim oPerson As New Person
oPerson.sFirstName = "Brock" 'ERROR! sFirstName is private you can't access it.
oPerson.sLastName = "Lesnar" 'ERROR! sLastName is private you can't access it.
oPerson.FirstName = "Randy" 'No error. It calls the "Set" in the "FirstName" property using the "Randy" as the value
oPerson.LastName = "Couture" 'No error. It calls the "Set" in the "LastName" property using the "Couture" as the value
MessageBox.Show(oPerson.FullName) 'No error. It will display a messagebox that says "Randy Couture"

and the equivalent in vJass would be (if i'm understanding how operator is used correctly):
JASS:

struct Person
	private string sFirstName
	private string sLastName

	method operator FirstName takes nothing returns string
		return sFirstName
	endmethod

	method operator FirstName= takes string sName returns nothing
		set .sFirstName = sName
	endmethod

	method operator LastName takes nothing returns string
		return sLastName
	endmethod

	method operator FirstName= takes string sName returns nothing
		set .sLastName = sName
	endmethod

	method operator FullName takes nothing rturns string
		return .sFirstName + &quot; &quot; + .sLastName
	endmethod
endstruct


and then in another function you have:
JASS:

local Person p = Person.create()
set p.sFirstName = &quot;Brock&quot; //ERROR! sFirstName is private you can&#039;t access it.
set p.sLastName = &quot;Lesnar&quot; //ERROR! sLastName is private you can&#039;t access it.
set p.FirstName = &quot;Randy&quot; //No error. It calls the FirstName= operator using &quot;Randy&quot; as the sName
set p.LastName = &quot;Couture&quot; //No error. It calls the LastName= operator using &quot;Couture&quot; as the sName
call BJDebugMsg(p.FullName) //No error. It will display a message that says &quot;Randy Couture&quot;
 
H

hitokirixeno

Guest
I believe that the operator keyword in Jass works like the operator keyword in .NET as well, it allows you to do simple comparisons using a defined operator between two objects. Like < and > with integers.
 

Grundy

Ultra Cool Member
Reaction score
35
Yea, in the thing Romek posted it shows how to overload the standard operators, BUT the only operators that can be overloaded are <, >, [], and []= it apparently doesn't let you overload the +, -, /, or * operators.
 

Grundy

Ultra Cool Member
Reaction score
35
Hey I started with normal C++ but in my job search I noticed *everyone* that was hiring wanted people that know C# or VB.NET.

.NET isn't all bad. It might have a lot of unnecessary things in it, but given the same project, 1 using .NET and 1 not using .NET, the one that uses .NET will be way easier and faster to finish.
 

Vexorian

Why no custom sig?
Reaction score
187
ey I started with normal C++ but in my job search I noticed *everyone* that was hiring wanted people that know C# or VB.NET.
Not my fault.
.NET isn't all bad. It might have a lot of unnecessary things in it, but given the same project, 1 using .NET and 1 not using .NET, the one that uses .NET will be way easier and faster to finish.
Myth.
 

cr4xzZz

Also known as azwraith_ftL.
Reaction score
51
Can someone post another simple example of operator usage? I'm trying to understand them too and with what purpose they're used. It seems like custom arrays but can be with different array values. :/
 

Flare

Stops copies me!
Reaction score
662
Table is a pretty nice example of it's usage IMO with the H2I usage i.e.
JASS:
struct GC
static method operator [] takes handle h returns integer
//You could probably just use a constant key for otherKey there
  return GetStoredInteger (myCache, I2S (H2I (h)), otherKey)
endmethod

static method operator []= takes handle h, integer i returns nothing
  call StoreInteger (myCache, I2S (H2I (h)), otherKey, i)
endmethod
endstruct


...
local StructName data = StructName.create ()
local timer t = CreateTimer ()
set GC[t] = data

...
local StructName data = GC[GetExpiredTimer ()]
 

cr4xzZz

Also known as azwraith_ftL.
Reaction score
51
Thanks Flare, haven't noticed before that Table uses operator keyword.
 
General chit-chat
Help Users
  • No one is chatting at the moment.
  • Ghan Ghan:
    Howdy
  • Ghan Ghan:
    Still lurking
    +3
  • The Helper The Helper:
    I am great and it is fantastic to see you my friend!
    +1
  • The Helper The Helper:
    If you are new to the site please check out the Recipe and Food Forum https://www.thehelper.net/forums/recipes-and-food.220/
  • Monovertex Monovertex:
    How come you're so into recipes lately? Never saw this much interest in this topic in the old days of TH.net
  • Monovertex Monovertex:
    Hmm, how do I change my signature?
  • tom_mai78101 tom_mai78101:
    Signatures can be edit in your account profile. As for the old stuffs, I'm thinking it's because Blizzard is now under Microsoft, and because of Microsoft Xbox going the way it is, it's dreadful.
  • The Helper The Helper:
    I am not big on the recipes I am just promoting them - I use the site as a practice place promoting stuff
    +2
  • Monovertex Monovertex:
    @tom_mai78101 I must be blind. If I go on my profile I don't see any area to edit the signature; If I go to account details (settings) I don't see any signature area either.
  • The Helper The Helper:
    You can get there if you click the bell icon (alerts) and choose preferences from the bottom, signature will be in the menu on the left there https://www.thehelper.net/account/preferences
  • The Helper The Helper:
    I think I need to split the Sci/Tech news forum into 2 one for Science and one for Tech but I am hating all the moving of posts I would have to do
  • The Helper The Helper:
    What is up Old Mountain Shadow?
  • The Helper The Helper:
    Happy Thursday!
    +1
  • Varine Varine:
    Crazy how much 3d printing has come in the last few years. Sad that it's not as easily modifiable though
  • Varine Varine:
    I bought an Ender 3 during the pandemic and tinkered with it all the time. Just bought a Sovol, not as easy. I'm trying to make it use a different nozzle because I have a fuck ton of Volcanos, and they use what is basically a modified volcano that is just a smidge longer, and almost every part on this thing needs to be redone to make it work
  • Varine Varine:
    Luckily I have a 3d printer for that, I guess. But it's ridiculous. The regular volcanos are 21mm, these Sovol versions are about 23.5mm
  • Varine Varine:
    So, 2.5mm longer. But the thing that measures the bed is about 1.5mm above the nozzle, so if I swap it with a volcano then I'm 1mm behind it. So cool, new bracket to swap that, but THEN the fan shroud to direct air at the part is ALSO going to be .5mm to low, and so I need to redo that, but by doing that it is a little bit off where it should be blowing and it's throwing it at the heating block instead of the part, and fuck man
  • Varine Varine:
    I didn't realize they designed this entire thing to NOT be modded. I would have just got a fucking Bambu if I knew that, the whole point was I could fuck with this. And no one else makes shit for Sovol so I have to go through them, and they have... interesting pricing models. So I have a new extruder altogether that I'm taking apart and going to just design a whole new one to use my nozzles. Dumb design.
  • Varine Varine:
    Can't just buy a new heatblock, you need to get a whole hotend - so block, heater cartridge, thermistor, heatbreak, and nozzle. And they put this fucking paste in there so I can't take the thermistor or cartridge out with any ease, that's 30 dollars. Or you can get the whole extrudor with the direct driver AND that heatblock for like 50, but you still can't get any of it to come apart
  • Varine Varine:
    Partsbuilt has individual parts I found but they're expensive. I think I can get bits swapped around and make this work with generic shit though
  • Ghan Ghan:
    Heard Houston got hit pretty bad by storms last night. Hope all is well with TH.
  • The Helper The Helper:
    Power back on finally - all is good here no damage
    +1
  • V-SNES V-SNES:
    Happy Friday!
    +1

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top