Callable¶
A built-in type representing a method or a standalone function.
Description¶
Callable is a built-in Variant type that represents a function. It can either be a method within an Object instance, or a standalone function not related to any object, like a lambda function. Like all Variant types, it can be stored in variables and passed to other functions. It is most commonly used for signal callbacks.
Example:
func print_args(arg1, arg2, arg3 = ""):
prints(arg1, arg2, arg3)
func test():
var callable = Callable(self, "print_args")
callable.call("hello", "world") # Prints "hello world ".
callable.call(Vector2.UP, 42, callable) # Prints "(0, -1) 42 Node(node.gd)::print_args".
callable.call("invalid") # Invalid call, should have at least 2 arguments.
// Default parameter values are not supported.
public void PrintArgs(Variant arg1, Variant arg2, Variant arg3 = default)
{
GD.PrintS(arg1, arg2, arg3);
}
public void Test()
{
// Invalid calls fail silently.
Callable callable = new Callable(this, MethodName.PrintArgs);
callable.Call("hello", "world"); // Default parameter values are not supported, should have 3 arguments.
callable.Call(Vector2.Up, 42, callable); // Prints "(0, -1) 42 Node(Node.cs)::PrintArgs".
callable.Call("invalid"); // Invalid call, should have 3 arguments.
}
In GDScript, it's possible to create lambda functions within a method. Lambda functions are custom callables that are not associated with an Object instance. Optionally, lambda functions can also be named. The name will be displayed in the debugger, or when calling get_method.
func _init():
var my_lambda = func (message):
print(message)
# Prints Hello everyone!
my_lambda.call("Hello everyone!")
# Prints "Attack!", when the button_pressed signal is emitted.
button_pressed.connect(func(): print("Attack!"))
Note: Methods of native types such as Signal, Array, or Dictionary are not of type Callable in order to avoid unnecessary overhead. If you need to pass those methods as Callable, use a lambda function as a wrapper.
func _init():
var my_dictionary = { "hello": "world" }
# This will not work, `clear` is not a callable.
create_tween().tween_callback(my_dictionary.clear)
# This will work, as lambdas are custom callables.
create_tween().tween_callback(func(): my_dictionary.clear())
Note
There are notable differences when using this API with C#. See C# API differences to GDScript for more information.
Constructors¶
Callable ( ) |
|
Callable ( Object object, StringName method ) |
Methods¶
bind ( ... ) vararg const |
|
call ( ... ) vararg const |
|
void |
call_deferred ( ... ) vararg const |
get_bound_arguments ( ) const |
|
get_bound_arguments_count ( ) const |
|
get_method ( ) const |
|
get_object ( ) const |
|