Hey there,
I made a quick module called ‘DictionaryTools’, it’s sort of like the table
library, but for dictionaries. Here is the module:
-- // Basic Types //
type table = {any}
type dictionary = {[string]: any}
type array = {[number]: any}
-- // Custom Types //
-- // Package Configuration //
local Package = {}
local PackageAssets = script.Parent:WaitForChild("Assets")
local PackagePlugins = script.Parent:WaitForChild("Plugins")
local Settings = require(script.Parent:WaitForChild("PackageConfiguration"):WaitForChild("Settings"))
-- // Variables //
-- // Functions //
--[[
Package.removekey()
Removes the `k` key from `d` and returns the new dictionary with `k` removed.
--]]
function Package.removekey(d: dictionary, k: string): dictionary?
if d[k] ~= nil then
d[k] = nil
return d
else
error(string.format("'%s' key does not exist.", k))
return
end
end
--[[
Package.insertkey()
Inserts a new key to `d` with the name of `k` and value of `v`, and returns the new dictionary.
--]]
function Package.insertkey(d: dictionary, k: string, v: any): dictionary
d[k] = v
return d
end
--[[
Package.unpack()
Unpacks `d` into a tuple. The tuple will contain keys or values based on `returnKeys`, and returns the tuple.
--]]
function Package.unpack(d: dictionary, returnKeys: boolean?): ...any
returnKeys = returnKeys or false
local tuple = { }
for key, value in pairs(d) do
if returnKeys then
table.insert(tuple, key)
else
table.insert(tuple, value)
end
end
return table.unpack(tuple)
end
--[[
Package.convert()
Converts `d` to a regular table, containing tables of each key and it's value, and returns the new table.
For example, this:
local myDictionary = {
["Key"] = 1;
["Key2"] = 2;
}
will become this:
local myConvertedDictionary = {
{"Key", 1};
{"Key2", 2};
}
--]]
function Package.convert(d: dictionary): table
local defaultTable = { }
for key, value in pairs(d) do
table.insert(defaultTable, {key, value})
end
return defaultTable
end
return Package
Thanks!