Hello there, I’ve run into some curious behaviour with numbered dictionaries that are used really often in a game I’m working on, a quick example is this dictionary here:
local InputTable:{[number]:number} = {--this table can be found in the "test2" script
[1] = 2,
[5] = 1
}
this works well within the script but as soon as it’s saved in a datastore or sent to another script through an event, remoteevent, bindablefunction or remotefunction it only comes back as this:
{--from Server - Test2Rec:2
[1] = 2
}
this is true even for this table
local InputTable = {--this table can be found in the "test5" script
[-1] = 0,
[1] = 2,
[5] = 1
}
however when you take away the [1] key like this
local InputTable = {--this table can be found in the "test6" script
[3] = 0,
[11] = 2,
[5] = 1
}
you end up with this both server and clientside
{
["11"] = 2,
["3"] = 0,
["5"] = 1
}
if anyone knows if there is any way to just get the numbers as keys and have every key returned please let me know, the test scripts are in this game dictionary test - Roblox (copying is enabled)
That’s because with json, you can only have a dictionary where each key/index is a string. Roblox will save your data either as a list or as a dictionary, and it has to convert all of its keys to strings so it can properly save.
Roblox internally also has trouble with tables like what you’re doing. It sees that the first index (the number 1) exists, so it iterates through the table until it finds a nil value, and saves your table as a list.
For your first table, it’s converted to '[2]' when saved (which is a list in JSON)
However, if the index number 1 does not exist, Roblox treats your table as if you would do for key, value in Pairs do ... end.
For your last table, this is converted to '{"3": 0, "11": 2, "5": 1}' (which is a dictionary in JSON)
You can have a fix for this though, if you want Roblox to save the data with numbered indexes instead of strings. You can represent an invalid value (such as -1 or 0) in each index that isn’t being used.
You can test these out for yourself with roblox’s HttpService:JSONEncode method, which shows you how your tables will be parsed.
This is also the reason why you can’t actually send cyclic-reference tables. JSON has no format or descriptor for saying “This value references itself,” because JSON wasn’t made for luau/Roblox’s implementation (of course, roblox can just implement workarounds for it, but that would probably conflict with a lot of internal traffic)
Ah ok thx, too bad then, I sadly can’t fill up invalid values as I’m hyperoptimising storage space but the JSON explaination makes sense, weird that Roblox never really states this anywhere in the documentation