pocketlang
pocketlang copied to clipboard
[Design] reconstruction magic methods
- add array of magic methods to class struct.
- current magic methods: _init, _getter, _setter, _str, _repr, _call.
- optimize method calling for magic methods.
- add _call so that object can be callable.
- add Object.getattr and Object.setattr so that attribs can be accessed via dynamic name.
- getter/setter can be called in script, no only in native code.
Example (this example needs "[Bugfix] native class can be inherited in script" to run):
from types import Vector
class Vector2 is Vector
def _init(x, y, z, a)
super(x, y, z)
self.a = a
end
def _setter(name, value)
if name in ['x', 'y', 'z'] then
super(name, value)
else
# last "true" means skip the default setter to avoid infinite loop
self.setattr(name, value, true)
end
end
def _getter(name)
if name in ['x', 'y', 'z'] then
return super(name)
else
# last "true" means skip the default getter to avoid infinite loop
return self.getattr(name, true)
end
end
def _repr
return super()[0..-2] + ", ${self.a}]"
end
def *=(n)
self.x *= n; self.y *= n; self.z *= n; self.a *= n;
return self
end
def _call
print(self)
end
end
v = Vector2(1, 2, 3, 4)
print(v)
v *= 2
v() # object is callable
Output:
[1, 2, 3, 4]
[2, 4, 6, 8]
Please have a look at my comment/question here
https://github.com/ThakeeNathees/pocketlang/commit/7a736f1915fac0a0ec9c40ab22038f3622b7c0dd#r137787262
Thank you