Saving a Typed Array and Loading it as a Typed Array using FileAccess
Asked Answered
D

2

0

I am trying to save an Array[Switch] to a file using store_var() and FileAccess. However, when loading it back it comes back as an untyped Array.

## Saves switches to the file specified in SAVE_PATH
func save_switches() -> void:
	var file := FileAccess.open(SAVE_PATH, FileAccess.WRITE)
	
	file.store_var(switches)
	file.close()

## Loads switches from the file specified in SAVE_PATH
func load_switches() -> void:
	if (FileAccess.file_exists(SAVE_PATH)):
		var file := FileAccess.open(SAVE_PATH, FileAccess.READ)
		
		var encoded_array : Array = file.get_var()
		
		for encoded_switch : EncodedObjectAsID in encoded_array:
			switches.append(instance_from_id(encoded_switch.object_id))
		
		file.close()
	else: print("Unable to find switches file to load")
Drakensberg answered 28/2, 2024 at 14:33 Comment(0)
E
0

There are no distinct variant type codes for typed Arrays. store_var() can only record that it's an Array. You would have to manually recast the retrieved data when using get_var().

The variant types are listed here (see enum Variant.Type):
https://docs.godotengine.org/en/4.2/classes/class_%40globalscope.html#enum-globalscope-variant-type

Exacting answered 28/2, 2024 at 17:21 Comment(0)
D
0

Exacting

I changed my approach to the issue.

Instead of saving and loading it through store_var() I am using store_text() and get_as_text(), to write to the file I map the array into a Dictionary and JSON.stringify() it, and then to read I just JSON.parse_string() on the file data and map it to the Array I need. Which seems to work.

Drakensberg answered 29/2, 2024 at 5:10 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.