This repository has been archived by the owner on Nov 20, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
--[=[ | ||
@within Dictionary | ||
Retrieves a value from a dictionary using a key. If the key is a dot-separated string and the `separated` parameter is `true`, the function will traverse the dictionary using the parts of the string as keys. If `separated` is a string, it'll be used as the separator. If the key is not found, the function will return `nil`. | ||
```lua | ||
local dictionary = { | ||
foo = { | ||
bar = { | ||
baz = "qux" | ||
} | ||
} | ||
} | ||
get(dictionary, "foo.bar.baz") -- nil | ||
get(dictionary, "foo.bar.baz", true) -- "qux" | ||
get(dictionary, "foo$bar$baz", "$") -- "qux" | ||
``` | ||
]=] | ||
local function get<K, V>(dictionary: { [K]: V }, key: K, separated: (string | boolean)?): V? | ||
if not separated then | ||
return dictionary[key] | ||
end | ||
|
||
local separator = type(separated) == "string" and separated or "." | ||
local parts: { string } = (key :: any):split(separator) | ||
local value: any = dictionary | ||
|
||
while #parts > 0 do | ||
local part = table.remove(parts, 1) | ||
value = value[part] | ||
|
||
if value == nil then | ||
return nil | ||
end | ||
end | ||
|
||
return value | ||
end | ||
|
||
return get |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters