Converting Script Source to Table
To convert the source code of a Lua script into a table, you can use the loadstring
function (don’t forget to turn it on because i did!).
local scriptSource = [[
materials = {
["metal"]={
["Material"]= Enum.Material.Metal;
--["Wood"]= {["Level"]=0; ["Color"]=Color3.fromRGB(146,142,133)};
["stone"]= {["Level"]=1; ["Color"]=Color3.fromRGB(146,142,133)};
["brass"]= {["Level"]=2; ["Color"]=Color3.fromRGB(128,74,0)};
["Copper"]= {["Level"]=3; ["Color"]=Color3.fromRGB(0,0,0)};
["Iron"]= {["Level"]=4; ["Color"]=Color3.fromRGB(161,157,148)};
["Steel"]= {["Level"]=5; ["Color"]=Color3.fromRGB(0,0,0)};
["Mothrill"]= {["Level"]=6; ["Color"]=Color3.fromRGB(174,187,219)};
["Adamantine"]= {["Level"]=7; ["Color"]=Color3.fromRGB(0,0,0)};
["Emerald"]= {["Level"]=8; ["Color"]=Color3.fromRGB(0,0,0)};
["Cerussite"]= {["Level"]=9; ["Color"]=Color3.fromRGB(0,0,0)};
};
}
return materials
]]
local func = loadstring(scriptSource)
local materials = func()
print(materials["metal"]["stone"]["Level"]) -- Output: 1
Converting Table to Script Source
To convert a table back into a Lua script source, you can serialize the table into a string. Here’s a simple function to do that:
local function serializeTable(tbl, indent)
indent = indent or 0
local toReturn = "{\n"
local indentStr = string.rep("\t", indent + 1)
for k, v in pairs(tbl) do
local key = type(k) == "string" and string.format("[\"%s\"]", k) or string.format("[%d]", k)
if type(v) == "table" then
toReturn = toReturn .. indentStr .. key .. " = " .. serializeTable(v, indent + 1) .. ",\n"
elseif type(v) == "string" then
toReturn = toReturn .. indentStr .. key .. " = \"" .. v .. "\",\n"
elseif type(v) == "number" or type(v) == "boolean" then
toReturn = toReturn .. indentStr .. key .. " = " .. tostring(v) .. ",\n"
elseif typeof(v) == "Color3" then
toReturn = toReturn .. indentStr .. key .. " = Color3.fromRGB(" .. v.R * 255 .. "," .. v.G * 255 .. "," .. v.B * 255 .. "),\n"
elseif typeof(v) == "EnumItem" then
toReturn = toReturn .. indentStr .. key .. " = Enum." .. tostring(v.EnumType) .. "." .. v.Name .. ",\n"
end
end
toReturn = toReturn .. string.rep("\t", indent) .. "}"
return toReturn
end
local scriptSource = "materials = " .. serializeTable(materials) .. "\nreturn materials"
print(scriptSource)
Using in a plugin
In your plugin, you can use these functions to read the script source, convert it to a table, modify it, and then convert it back to a script source. Here’s a basic example:
local scriptSource = script.Source
local func = loadstring(scriptSource)
local materials = func()
-- Modify the table as needed
materials["metal"]["Copper"]["Color"] = Color3.fromRGB(255, 0, 0)
-- Convert the table back to a script source
local newScriptSource = "materials = " .. serializeTable(materials) .. "\nreturn materials"
script.Source = newScriptSource
Hope it helps!