The problem is with your data structure. When it comes to tables in Lua, there are two data structures:
(there is technically a third data structure if you count mixed tables, but that's another topic)
A general rule of thumb when it comes to structuring your data:
If you care about order, use an array. If you care about keys, use a dictionary. If you care about both, use both!
What's the Difference?
Arrays and dictionaries work fundamentally differently under the hood. I'll spare the details of the technicalies, but here's the rundown:
Array
- Cares about order (preserves the order of values in the table).
- Easy to compute size (such as using the
#
operator)
- Access to most of the functions in the
table
library (as they're geared towards manipulating arrays)
Dictionary
- Doesn't care about order, cares about key/value pairs.
- No intrinsic way to compute size (you have to manually loop over the table and count iterations)
- Only holds unique keys (you can guarantee each key in a dictionary table will be unique)
How can I use Both?
As long as you're consistent with how you create keys in your table, then you're structure will remain the same. The values in your table do not determine the data structure of the parent table.
For example, you can have a dictionary that holds arrays:
2 | keyA = { "a" , "b" , "c" } , |
3 | keyB = { "d" , "e" , "f" } , |
...and you can have an array that holds dictionaries:
You will often see examples of the second structure mentioned above in numerous places. This is a popular method of storing dynamic data while preserving order.
Your Solution
In your case however, I don't see a reason to nest dictionaries in arrays or vise-versa. The only way to practically achieve what you're looking for is to create an array of arrays.
For example, instead of doing this and having no control over the order of your key/values:
...you could create an array of child arrays, where each child array stores the key in the first index and the value in the seocnd index:
7 | { "WeldToPart" , false } |
if you really care about keeping this structure as a dictionary, then you could simply convert it back into a dictionary by doing:
07 | { "WeldToPart" , false } |
10 | local convertDataArrayToDict = function (array) |
14 | local data = array [ i ] ; |
15 | dict [ data [ 1 ] ] = data [ 2 ] ; |
now calling convertDataArrayToDict(dataArray)
will return something like this:
Just remember that the returned dictionary will still not be in any particular order. This is only if you want to preserve the original structure.
Hope this helps, let me know if you have any questions!