November 9, 2018 at 12:04 pm #15578
Some notes on programming with pointers in Monkey. In some cases where you want to send an object to a function and change it. However there are some reasons of why this not happens out of the box. Structs are passed by value which means that the object is copied each time is sent to a function. Classes are a little bit different because they are sent as references which means that changes can be made, however the object itself can’t be allocated (which makes them not pure references but copy to references actually).
Jumping straight to example.Monkey123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778#Import "<std>"Using std..' a classic struct hereStruct TheStructField A:StringField B:IntMethod To:String()Return A + " " + BEndEnd' a class alsoClass TheClassField A:StringField B:IntMethod To:String()Return A + " " + BEndEnd' this function will allocate a new struct' notice the strange s notation? is important! 🙂Function TheStruct_Create(s:TheStruct Ptr)s = New TheStructEnd' this one does some assignment' notice the pointer operator [->] which means' that I won't have to dereference the variable first to use dot operator [.]Function TheStruct_Init(s:TheStruct Ptr, n:String, i:Int)s->A = ns->B = iEnd' the same concept as TheStruct_InitFunction TheStruct_Update(s:TheStruct Ptr)s->B += 1End' it is clearly seen that structs need to' be passed as pointers if to be changed or allocated' same concept as the struct hereFunction TheClass_Create(c:TheClass Ptr)c = New TheClassEnd' and the sameFunction TheClass_Init(c:TheClass Ptr, n:String, i:Int)c->A = nc->B = iEnd' however here is some special case' because classes are passed by reference' you can actually skip pointer usage for good' (unless for sure you want to do the object initialization)Function TheClass_Init2(c:TheClass, n:String, i:Int)c.A = nc.B = iEndFunction Main()Local a:TheStructTheStruct_Create(Varptr a)TheStruct_Init(Varptr a, "Default Struct", 1000)TheStruct_Update(Varptr a)Print(a)Local b:TheClassTheClass_Create(Varptr b)TheClass_Init(Varptr b, "Default Class", 5000)Print(b)TheClass_Init2(b, "Nice", 1)Print(b)End
You must be logged in to reply to this topic.