I am trying to convert a dictionary into a string, but I can’t seem to figure out how to do the string patterns. I feel as if I am so close, but I just can’t figure out the string patterns.
My system has two functions: tableToString & stringToTable. What I could do with my current scripting abilities is as follows:
function tableToString(oldTable)
local newString = ""
for index, value in pairs(oldTable) do
newString = newString..string.format("['%s']='%s',\n", index, value)
end
newString = string.sub(newString, 1, #newString-2)
return newString
end
function stringToTable(oldString)
local newTable = {}
local splitString = string.split(oldString, "\n")
for index, value in pairs(splitString) do
-- :P
end
return newTable
end
Where I put the little emoticon is where I am having the most trouble. Can anyone help me with the string patterns?
What you are looking for is called regular expressions, or regex for short. If you want the easy solution, you can use encode and decode from HTTP service, but if you insist on using your script, look up some regex patterns, that will be able to help you.
As I said in my post, I can’t figure out the string patterns to make this work and was wondering if someone can help me out. I’ve already read the documentation several times, but I just don’t know how to do it for my situation.
local pattern = "%[%'(.+)%'%]=%'(.+)%'"
-- each % is an escape to literally look for a bracket or single quote, and since values could be anything, we use .+ captured by parenthesis.
for index, str in pairs(splitString) do
local key, value = string.match(str, pattern)
if key and value then
newTable[key] = value
end
end
This is a small sample I wrote from your function to test it out.
local Game = game
local HttpService = Game:GetService("HttpService")
local Dictionary = {a = 1, b = 2, c = 3, xyz = {1, 2, 3}}
local Success, Result = pcall(HttpService.JSONEncode, HttpService, Dictionary)
if Success then
print(Result)
else
warn(Result)
end
--{"a":1,"xyz":[1,2,3],"c":3,"b":2}