Hello, I’m working with a function with Dictionary and other type of parameters. For some reason I need to make the Dictionary parameter empty, like:
func test(p1: int, p2: Dictionary = {}) -> void:
pass
# so can be used like
test(3, {'abc': 123})
# and also
test(123)
I know the {} value of dict is not safe in python, but is this ok in gdscript? Or maybe use like:
# better?
const EMPTY_DICT = {}
func test(p1: int, p2: Dictionary = EMPTY_DICT) -> void:
pass
# I know it's wrong below, but that's somehow I want directly.
# and union type is not allowed: Dictionary | null
func test(p1: int, p2: Dictionary = null) -> void:
pass
So, I want to keep my type notations for parameters, and the same time make the Dictionary default value empty in a safe way, please give me some advice, thank you!
I don’t know of any problem with {} in GDScript, I always use it as the default value for a dictionary and then check .size() == 0 to see if it’s empty.
{} is passed by reference in python and Godot, where most base types are copied when given to a function. In python the default-argument dictionary is kept between calls, Godot does not seem to do this luckily, but it’s a good habit to avoid defaults on reference-types.