Skip to content

Meta methods

Wang Renxin edited this page Aug 6, 2016 · 12 revisions

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 overriding only one of them is incomplete.

Note the gist 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")
Clone this wiki locally