-
Notifications
You must be signed in to change notification settings - Fork 127
Meta methods
There are some essential meta methods which MY-BASIC would use for particular contexts. Assuming we got a class as below:
class cls
endclass
print clz; ' a)
d = dict(clz, 1, clz, 2) ' b)It will just print the type name "CLASS" at a). The collections use the raw pointer to get hash code or compare two class instances. It's useful to let us to specify behavior of these usage. See the code below:
class clz
var v = 123
def tostring()
return "test"
enddef
def hash()
return v
enddef
def compare(o)
return v - o.v
enddef
endclass
print clz; ' a)
d = dict(clz, 1, clz, 2) ' b)
l = list(clz, clz)
sort(l) ' c)The PRINT statement will try to use a tostring method to serialize the text at a). And collections will use hash and compare methods to get a hash code or compare two elements to do a dictionary insertion at b) or a list sorting at c).
The hash and compare meta function must be overridden together, because incompletely overriding only one of them will cause problems.
Note the gist is that the return values of hash and compare must be immutable once an object is created, or mutable hash value and compare result would bring about undetectable bug for collections. Thus the following code is incorrect:
d = dict()
set(d, clz, "original")
clz.v = 321
set(d, clz, "wrong")- Principles
- Coding
- Data types
- Standalone shell
- Integration
- Customization
- More scripting API
- FAQ