![]() |
Attention | Topic was automatically imported from the old Question2Answer platform. |
![]() |
Asked By | alexzheng |
I want to define a method with variable arguments, is that supported?
![]() |
Attention | Topic was automatically imported from the old Question2Answer platform. |
![]() |
Asked By | alexzheng |
I want to define a method with variable arguments, is that supported?
![]() |
Reply From: | Zaven Muradyan |
Unfortunately, it doesn’t appear that this is supported yet: GDScript: Variadic functions (variable number of arguments/varargs) · Issue #16565 · godotengine/godot · GitHub
The basic workaround would be to accept an array argument and just use array notation at the call site:
func foo(args):
for x in args:
pass
foo(["hello", "world"])
![]() |
Reply From: | jagc |
This is a duplicate of this question.
The answer provided there hits it perfectly.
For those too lazy to click the link, this is one example variation of implementing the answer:
func nameOfFunc(firstArg, params = {}): var data = firstArg # Ternary operation just to keep it short # But you can do whatever you want when: # checking a key's existence and assigning values var a = (0 if not params.has('a') else params['a']) var b = (0 if not params.has('b') else params['b']) var c = (0 if not params.has('c') else params['c']) data += a + b + c return data
So let’s call it inside a function.
func printExample(): var a = 1 var c = 1 # in our definition, we have named optional parameters 'a', 'b', 'c' # we're only setting up to use 'a' and 'c' var params = { a = a, c = c } var sum = nameOfFunc(1, params) print(sum) # output: 3
Tested working at Godot 3.1.1
Old thread, but in case someone else stumbles on this like I did, I want to add two points:
With the above two considerations, here’s what I’d do for arbitrary parameters:
func nameOfFunc(firstArg, params = null):
var data = firstArg
if params != null:
var a = params.get('a', 0)
var b = params.get('b', 0)
var c = params.get('c', 0)
data += a + b + c
return data
BigOzzie | 2022-10-02 17:53
I posted about a kwargs unpacker function I made, if anyone is interested. I dont know if it can be used for all situations, but you can try it and edit it as needed/wanted.
Hope it helps someone