Invalid get Index error

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

Im writing a script for procedural 2d terrain generation, and there is one line of code giving me trouble, the function that it’s in is supposed to take numbers generated elsewhere and set them as values which will determine what tile to use out of a tileset. the line “var alt = altitude[pos]” is causing an error that says “Invalid get index ‘(1,0)’ (on base: Dictionary)”. Ive tried looking around online and found nothing.

func set_tile(width, height):
for x in width:
	for y in height:
		var pos = Vector2(x, y)
		var alt = altitude[pos]
		var temp = temperature[pos]
		var moist = moisture[pos]
:bust_in_silhouette: Reply From: zhyrin

You are using Vector2s as keys in your altitude dictionary. When you start your second iteration of the outer for loop, x equals 1 (y will equal 0 in the first inner loop), so the key you create is Vector2(1, 0) (which godot prints as (1,0)).
The error you get means your dictionary doesn’t have such a key.
It’s actually pretty easy to check (if the dictionary is not too big), since the debugger will stop at this line, you can check the stored keys and values of your altitude dictionary (right hand side of the debugger panel at the bottom).

Indeed. You appear to have a design issue with your dictionary, where the key doesn’t exist but your code expects the key exists. To avoid your code bugging out, you could add a check to make sure the key exists, e.g.: if altitude.has(pos): before fetching the value, and printing out an error if they key doesn’t exist. You will still need to fix the design issue and make sure that the keys exist first before calling your function

godot_dev_ | 2023-06-08 13:35