How to pass parameters to another function directly and once.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By moonrise

In python, we can use *args and **kwargs as arguments of a function when we are unsure about the number of arguments to pass in the functions.

As an example,

def my_print(*args):
    if some_condiction:
      print("xxx: ", args)

my_print(2, 3)
my_print(a,b,"cde")

How to achieve the same purpose in GDScript?

func my_print():
   ???
:bust_in_silhouette: Reply From: BoxyLlama

I don’t believe variadic functions are supported. I’ve seen a discussion or two about adding them to G4 in the github, but I don’t think any of them actually made it in.

As a work around, this could be done with something like a Array. Just a shot using your example:

func my_print(args=[]):
  if some_condition:
      print("xxx: %s" % [args])

my_print([2, 3]) // "xxx: [2, 3]"
var a = "a"
var b = 2
my_print([a, b, "cde"]) // "xxx: ["a", 2, "cde"]"

Could have conditions in the method that check the size of the args array. Additionally this could also be done with a dictionary instead of an array.

Sorry to hear that godot dose not support.
But, args array is the best alternative way I heard.
Thanks anyway.

moonrise | 2022-09-29 14:26

:bust_in_silhouette: Reply From: godot_dev_

As BoxyLlama states, I don’t think you can achieve exactly what you want to do in Godot. However, you can achieve something similar using the callv function. It takes the function name as the first argument and an array of parameters as the second parameter, so the caller doesn’t need to know how many paramters are required, it just needs an array with all the arguments. The function being called must know how many arguments it expects. For example:

#YourCustomScript

func my_print(param1,param2):
    print(param1)
    print(param2)

#Anotherscript

customScript.callv('my_print',["hello","world"])