reflect
This module provides many functions that can be used to interact with or modify modules, classes and functions. It is well suited for many uses cases such as creating a library that is heavily dependent on decorators (e.g. the json
module).
For example,
We can call a decorator using the reflect
module like this.
class A {
@custom_decorator() {
echo 'It works!'
}
}
import reflect
var instance_of_a = A()
var decorator = reflect.get_decorator(instance_of_a, 'custom_decorator')
# It's always good to check the result first as it will be a good
# practice to make decorators optional to make it easy for users to
# opt-in and opt-out of features your package or library provide.
if decorator {
decorator()
}
Try it out!
Functions
- reflect.has_prop(object: instance, name: string)
- Returns
true
if instance has the property name orfalse
if notreturn bool
- reflect.get_prop(object: instance, name: string)
- Returns the property of the instance matching the given name or nil if the object contains no property with a matching name. return any
- reflect.set_prop(object: instance, name: string, value: any)
- Sets the named property of the object to value.
- if the property already exist, it overwrites it
return bool: `true` if a new property was set, `false` if a property was updated
- reflect.del_prop(object: instance, name: string)
- Deletes the named property from the instance return bool
- reflect.has_method(object: instance, name: string)
- Returns true if class of the instance has the method name or false if not. return bool
- reflect.has_decorator(object: instance, name: string)
- Returns true if class of the instance implements the decorator name or false if not. return bool
- reflect.get_method(object: instance, name: string)
- Returns the method in a class instance matching the given name or nil if the class of the instance contains no method with a matching name. return function
- reflect.get_decorator(object: instance, name: string)
- Returns the decorator function matching the given name in the class of the given instance.
- the name of a decorator excludes the
@
character.
return function - the name of a decorator excludes the
- reflect.bind_method(object: instance, method: function)
- Binds the given function to the instance, allowing you to access the instance itself in the function via the
self
keyword in the function.return function
- reflect.get_type(object: instance)
- Returns the type of an instance as string return string
- reflect.get_type(object: instance)
- Returns the type of an instance as string return string
- reflect.get_class(object: instance)
- Returns the class value of an instance as an object that can be used to create a new instance of that same class. return class
- reflect.is_ptr(value: any)
- Returns
true
if value is a pointer,false
otherwise.return bool