Table Of Tables To String With String Values being Strings

I was wondering how I would go about converting a Table of Tables into a string but still keeping values that are strings, strings. The reason I need to make the table into a string is so that I can update the source code of a module.

My current code:

local function tableToString(_table, depth)
		local completedString = ""
		for index, value in pairs(_table) do
			local tabs = string.rep("\t", depth)
			local combinedString = "%s = %s;\n"
			if type(value) == "table" then
				combinedString = tabs .. ("[%q] = {\n%s"):format(index, tableToString(value, depth+1)) .. ("\n%s%s\n"):format(tabs, "};")
			else
				combinedString = tabs .. combinedString:format(index, value)
			end
			completedString = completedString .. combinedString
		end
		return completedString
	end

Input and output of the function:

---Input
local Mytable = { 
	["Default"] = {
		["Cards"] = {
			["1"] = {
				["Owner"] = "Username";
				["CardValue"] = 5;
			};
		}
	}
}

tableToString(Mytable, 1)

--Output
local Mytable = { 
	["Default"] = {
		["Cards"] = {
			["1"] = {
				Owner = Username;
				CardValue = 5;
			};
		}
	}
}

Perhaps next time treat serialization data as matricies ;/ but for real I would transpose it to a matrix. If you don’t know how to do that I have written a very thorough tutorial on it but what u are basically doing is looking through the keys then assigning that key the opposite of it. Since they need to be represented as integers I suppose create a identity matrix then. Matrices - What Are They And How To Code With Them

Not sure that would work since it’s going from a string to the source of the module.

Agh, I see what you mean now. I am kind of stumped then, sorry.

1 Like

Found what I needed. Repr

That is one solution. However you can also use HttpService | Documentation - Roblox Creator Hub
Like game:GetService(“HttpService”):JSONEncode(Mytable)

I don’t known what is your application for converting tables to strings but I suggest you use the JSON method because then you can convert strings back to tables with HttpService | Documentation - Roblox Creator Hub

Of course if you are just using this for debug output or some other stuff which requires you to preserve how it would be written as Lua then definetly use Repr but otherwhise the JSON method might do.

Actually, you can’t. Not for what I’m doing at least. JSONEncode turns all = into : so the table doesn’t actually work within a script, and since the objective of making the table into a string is so that I can update the source code of a module I can’t use that.

Oh didn’t known you needed to put the table in a script.

It’s alright. I should have mentioned that.