-
Notifications
You must be signed in to change notification settings - Fork 118
Meta methods
There are some essential meta methods which are called in MY-BASIC for particular contexts. Assuming got a class as follow:
class cls
endclass
print clz; ' a)
d = dict(clz, 1, clz, 2) ' b)
It just prints the type name "CLASS" at a). The address of an object is not operable in MY-BASIC code, however the collections use the address of advanced types to get hash values or to compare two class instances. Sometimes it's necessary to be able to customize behavior of these operations. See the code as follow:
class clz
var v = 123
def to_string()
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 method named to_string
to prompt the text at a). And collections will use methods named hash
and compare
to get a hash value or to compare two elements to make a dictionary insertion at b) or a list sorting at c).
The hash
and compare
meta functions must be overridden both together, or 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 with the previous clz
by changing something that would affect the return values:
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