0 votes

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():
   ???
in Engine by (21 points)

2 Answers

+1 vote
Best answer

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.

by (334 points)
edited by

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

0 votes

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"])
by (434 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.