E 0:00:00:342 background.gd:56 @ get_variant(): Index p_index = 1 is out of bounds (p_instance->size() = 1).
<C++ Source> core/variant/variant_call.cpp:681 @ func_Array_get()
<Stack Trace> background.gd:56 @ get_variant()
background.gd:46 @ load_bg_part()
background.gd:31 @ _ready()
So basically I have a piece of data that is an Array of a Dictionary. So I write a function, get_variant(), to ensure it can return a fallback of value in case the index is out of bound. So yes, I expect “out of bound” senario. The inside function look like this:
func get_variant(inx: int, type: String):
if !variant_map.get(inx): return ''
if !variant_map[inx].get(type): return ''
return variant_map[inx][type]
Before that I did this but due to the error I have to try different way (and it’s still no hope)
const variant_value = variant_map[inx][type] if variant_map.get(inx) else ''
Is there anyway to get rid of the error because I want that error happens. It simply a case where I already covered.
I had fixed with your note but the problem is still here. I think it is the problem coming from the array that wrap the dictionary rather then the dictionary itself.
I feel like it’s not ideal to write code that fails intentionally. I would suggest writing this function / class in such a way that either avoids failure states, or you handle exceptions before they happen.
Maybe check how large your dictionary is before you try to get something out with an index?
Sometime you have to do it wrong to get the right result. But thanks for the idea, that seems work.
I just think that missing out a solution to handle the error is such a mistake in gdscript. Also, the same has method but dictionary accept index and array is value? I wouldn’t do that if I was them. And even if the array.has(value) makes sense it still not very flexible in returning value. A returned index int would be more useful than just boolean.
Usually if your code fails, it’s better to understand why it does, and if you feel like there’s no correct fix, then perhaps the way you approached the given problem was incorrect to begin with. It’s worth exploring other ways on how to solve a given task / problem.