Skip to content

Instantly share code, notes, and snippets.

@katsaii
Last active September 13, 2019 23:51
Show Gist options
  • Save katsaii/5d78d01aa7c1e9aaed5bcfb97d1255fe to your computer and use it in GitHub Desktop.
Save katsaii/5d78d01aa7c1e9aaed5bcfb97d1255fe to your computer and use it in GitHub Desktop.
Finds the nested data structure type from a Game Maker map.
/// @desc Returns the type of data structure nested at a key of a ds_map.
/// @param id {Integer} The id of the ds_map to consider.
/// @param key {String} The key of the ds_map to inspect.
/// @author Kat @katsaii
if (is_real(argument0[? argument1])) {
// copy the ds_map into a duplicate map that can be manipulated freely
var clone = ds_map_create();
ds_map_copy(clone, argument0);
// delete all records other than what's required
var key = ds_map_find_first(clone);
repeat (ds_map_size(clone)) {
var key_next = ds_map_find_next(json_map,json_map_key);
if (key != argument1) {
clone[? key] = noone;
/* This prevents nested structures from being deleted when we remove
* the record from the cloned map.
*/
ds_map_delete(clone, key);
}
key = key_next;
}
// encode the final json and free dynamic structures
var context = json_encode(clone);
clone[? argument1] = noone; // see above
ds_map_destroy(clone);
// actual inspection occurs here
context = string_replace(context, "\"" + string(argument1) + "\"", "");
var trim_start = string_pos(":", context) + 2;
var trim_end = string_length(context) - 1;
var trimmed = string_copy(context,
trim_start,
trim_end - trim_start);
switch (string_char_at(trimmed, 1)) {
// the first character is enough information to infer the type of structure
case "[":
return ds_type_list;
break;
case "{":
return ds_type_map;
break;
}
}
// if the key is not real, there is no chance of it being a data structure
return -1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment