Hi! I want to turn the string like the one shown below into a dictionary. I am trying to make the ID to be the key in the dictionary and the name to be the value. I’ve tried using string formatting to accomplish this but got a little lost. Are there any specific methods that can help me accomplish this?
Example string:
local str = [[1402432199 Violet Valkyrie
16630147 Beautiful Hair for Beautiful People
6005325038 Blonde Celebrity Ponytails
96079043 Extreme Headphones
6377689712 Cute Lil' Black Goth Bunny Hood 🐰
6100039044 Bow Braids & Wispy Bangs]]
Can’t you just use a dictionary? You can also convert the IDs into strings if you’d like might be better performance wise…
local table = {
[tostring(1402432199)] = "Violet Valkyrie",
...
}
MAIN ISSUE
If using dictionaries isn’t possible, then you can split all of the strings by the newline character, aka \n. Afterwards, you can split the substrings by a space, then get the ID. After that, you’d have to do some string.sub trickery to get the item’s name.
If this string is divided by the new line operator (\n), then you could use string.split(String, Separator) like string.split(str, "\n") to split all lines into an array, then split the id by the name between the first space.
You could accomplish this by using string patterns - I wrote up a script just now.
local String = [[12345 Hello World!
67890 How are you?
567 ABC 123!]]
local Temp = {} -- Temp holder for lines
local Count = 1
local Result = {} -- Resulting dictionary
for Line in String:gmatch("[^\n]+") do -- Get every non-new-line in a set
Temp[1+#Temp] = Line -- Add to Temp
end
for _, Line in ipairs(Temp) do -- Iterate through Temp
local Index, Value = Line:match("(%d+) (.*)") -- Get the Number and Value from Line
Result[Index] = Value -- Add the Number as the index, and Value as the, well, value :p
end
print("\n")
for Index, Value in next, Result do
print(Index, "-", Value) -- Output dictionary
end
--[[
Output:
12345 - Hello World!
67890 - How are you?
567 - ABC 123!
--]]