Callable
Un tipo incorporado que representa un método o una función independiente.
Descripción
Callable is a built-in Variant type that represents a function. It can either be a method within an Object instance, or a custom callable used for different purposes (see is_custom()). Like all Variant types, it can be stored in variables and passed to other functions. It is most commonly used for signal callbacks.
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.0, -1.0) 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!"))
In GDScript, you can access methods and global functions as Callables:
tween.tween_callback(node.queue_free) # Object methods.
tween.tween_callback(array.clear) # Methods of built-in types.
tween.tween_callback(print.bind("Test")) # Global functions.
Note: Dictionary does not support the above due to ambiguity with keys.
var dictionary = { "hello": "world" }
# This will not work, `clear` is treated as a key.
tween.tween_callback(dictionary.clear)
# This will work.
tween.tween_callback(Callable.create(dictionary, "clear"))
Nota
Hay diferencias notables cuando usa esta API con C#. Véase Diferencias de la API de C# con GDScript para más información.
Constructores
Callable() |
|
Callable(object: Object, method: StringName) |
Métodos
bind(...) vararg const |
|
call(...) vararg const |
|
void |
call_deferred(...) vararg const |
create(variant: Variant, method: StringName) static |
|
get_argument_count() const |
|
get_bound_arguments() const |
|
get_bound_arguments_count() const |
|
get_method() const |
|
get_object() const |
|
get_object_id() const |
|
get_unbound_arguments_count() const |
|
hash() const |
|
is_custom() const |
|
is_null() const |
|
is_standard() const |
|
is_valid() const |
|
void |
rpc(...) vararg const |
void |
|
Operadores
operator !=(right: Callable) |
|
operator ==(right: Callable) |
Descripciones de Constructores
Construye un Callable vacío, sin ningún objeto ni método vinculado.
Callable Callable(from: Callable)
Construye un Callable como una copia del Callable dado.
Callable Callable(object: Object, method: StringName)
Crea un nuevo Callable para el método llamado method en el object especificado.
Nota: Para métodos de tipos Variant incorporados, usa create() en su lugar.
Descripciones de Métodos
Callable bind(...) vararg const 🔗
Devuelve una copia de este Callable con uno o más argumentos vinculados. Cuando se llama, los argumentos vinculados se pasan después de los argumentos proporcionados por call(). Véase también unbind().
Nota: Cuando este método se encadena con otros métodos similares, el orden en que se modifica la lista de argumentos se lee de derecha a izquierda.
Callable bindv(arguments: Array) 🔗
Devuelve una copia de este Callable con uno o más argumentos vinculados, leyéndolos desde un array. Cuando se llama, los argumentos vinculados se pasan después de los argumentos proporcionados por call(). Véase también unbind().
Nota: Cuando este método se encadena con otros métodos similares, el orden en que se modifica la lista de argumentos se lee de derecha a izquierda.
Variant call(...) vararg const 🔗
Llama al método representado por este Callable. Se pueden pasar argumentos y deben coincidir con la firma del método.
void call_deferred(...) vararg const 🔗
Calls the method represented by this Callable in deferred mode, i.e. at the end of the current frame. Arguments can be passed and should match the method's signature.
func _ready():
grab_focus.call_deferred()
public override void _Ready()
{
Callable.From(GrabFocus).CallDeferred();
}
Note: Deferred calls are processed at idle time. Idle time happens mainly at the end of process and physics frames. In it, deferred calls will be run until there are none left, which means you can defer calls from other deferred calls and they'll still be run in the current idle time cycle. This means you should not call a method deferred from itself (or from a method called by it), as this causes infinite recursion the same way as if you had called the method directly.
See also Object.call_deferred().
Variant callv(arguments: Array) const 🔗
Llama al método representado por este Callable. A diferencia de call(), este método espera que todos los argumentos estén contenidos dentro del arguments Array.
Callable create(variant: Variant, method: StringName) static 🔗
Crea un nuevo Callable para el método llamado method en el variant especificado. Para representar un método de un tipo Variant incorporado, se utiliza un objeto invocable personalizado (véase is_custom()). Si variant es Object, se creará un objeto invocable estándar en su lugar.
Nota: Este método es siempre necesario para el tipo Dictionary, ya que la sintaxis de propiedad se utiliza para acceder a sus entradas. También puedes utilizar este método cuando el tipo de variant no se conoce de antemano (para el polimorfismo).
int get_argument_count() const 🔗
Devuelve el número total de argumentos que debe tomar este Callable, incluidos los argumentos opcionales. Esto significa que cualquier argumento vinculado con bind() se resta del resultado, y cualquier argumento desvinculado con unbind() se suma al resultado.
Array get_bound_arguments() const 🔗
Returns the array of arguments bound via successive bind() or unbind() calls. These arguments will be added after the arguments passed to the call, from which get_unbound_arguments_count() arguments on the right have been previously excluded.
func get_effective_arguments(callable, call_args):
assert(call_args.size() - callable.get_unbound_arguments_count() >= 0)
var result = call_args.slice(0, call_args.size() - callable.get_unbound_arguments_count())
result.append_array(callable.get_bound_arguments())
return result
int get_bound_arguments_count() const 🔗
Devuelve la cantidad total de argumentos vinculados a través de sucesivas llamadas a bind() o unbind(). Esto es lo mismo que el tamaño del array devuelto por get_bound_arguments(). Véase get_bound_arguments() para más detalles.
Nota: Los métodos get_bound_arguments_count() y get_unbound_arguments_count() pueden devolver valores positivos.
StringName get_method() const 🔗
Devuelve el nombre del método representado por este Callable. Si el objeto invocable es una función lambda de GDScript, devuelve el nombre de la función o "<anonymous lambda>".
Devuelve el objeto en el que se llama a este Callable.
Devuelve el ID del objeto de este Callable (véase Object.get_instance_id()).
int get_unbound_arguments_count() const 🔗
Devuelve la cantidad total de argumentos desvinculados a través de sucesivas llamadas a bind() o unbind(). Véase get_bound_arguments() para más detalles.
Nota: Los métodos get_bound_arguments_count() y get_unbound_arguments_count() pueden devolver valores positivos.
Devuelve el valor hash de 32 bits del objeto de este Callable.
Nota: Los Callables con contenido igual siempre producirán valores hash idénticos. Sin embargo, lo contrario no es cierto. Devolver valores hash idénticos no implica que los invocables sean iguales, porque diferentes invocables pueden tener valores hash idénticos debido a colisiones de hash. El motor utiliza un algoritmo hash de 32 bits para hash().
Devuelve true si este Callable es un objeto invocable personalizado. Los objetos invocables personalizados se utilizan:
para vincular/desvincular argumentos (véase bind() y unbind());
para representar métodos de tipos Variant incorporados (véase create());
para representar funciones globales, lambda y RPC en GDScript;
para otros propósitos en el núcleo, GDExtension y C#.
Devuelve true si este Callable no tiene un objetivo al que llamar al método. Equivalente a callable == Callable().
Nota: Esto no es lo mismo que not is_valid() y usar not is_null() no garantiza que se pueda llamar a este objeto invocable. Utiliza is_valid() en su lugar.
Devuelve true si este Callable es un objeto invocable estándar. Este método es lo opuesto a is_custom(). Devuelve false si este objeto invocable es una función lambda.
Devuelve true si el objeto invocable existe y tiene un nombre de método válido asignado, o es un objeto invocable personalizado.
void rpc(...) vararg const 🔗
Realiza una RPC (Remote Procedure Call) en todos los pares conectados. Esto se utiliza para el multijugador y normalmente no está disponible, a menos que la función a la que se llame se haya marcado como RPC (usando @GDScript.@rpc o Node.rpc_config()). Llamar a este método en funciones no soportadas resultará en un error. Véase Node.rpc().
void rpc_id(peer_id: int, ...) vararg const 🔗
Perform an RPC (Remote Procedure Call) on a specific peer ID (see multiplayer documentation for reference). This is used for multiplayer and is normally not available unless the function being called has been marked as RPC (using @GDScript.@rpc or Node.rpc_config()). Calling this method on unsupported functions will result in an error. See Node.rpc_id().
Callable unbind(argcount: int) const 🔗
Returns a copy of this Callable with a number of arguments unbound. In other words, when the new callable is called the last few arguments supplied by the user are ignored, according to argcount. The remaining arguments are passed to the callable. This allows to use the original callable in a context that attempts to pass more arguments than this callable can handle, e.g. a signal with a fixed number of arguments. See also bind().
Note: When this method is chained with other similar methods, the order in which the argument list is modified is read from right to left.
func _ready():
foo.unbind(1).call(1, 2) # Calls foo(1).
foo.bind(3, 4).unbind(1).call(1, 2) # Calls foo(1, 3, 4), note that it does not change the arguments from bind.
Descripciones de Operadores
bool operator !=(right: Callable) 🔗
Devuelve true si ambos Callable invocan diferentes destinos.
bool operator ==(right: Callable) 🔗
Devuelve true si ambos Callable invocan el mismo destino personalizado.