Managing a string through a table of keywords

So what I would like to achieve is something that I can input a string and have it take a dictionary of possible “special characters” that I defined in a different script(obviously using a module script then requiring this from that script).
So if I was given a dictionary of

formatSymbols = {
		timeFormatSymbol = "\&t",
		numPlayersFormatSymbol = "\&p",
		numIterationsFormatSymbol = "\&i"
}

and wanted to replace a string of something like

"Game loop : \&i  || Intermission (\&t) with \&p players"

where the matching symbols found in the message would correspond to variables passed into the function(\&i would be numIterations, \&p would be numPlayers, \&t would be timeLeft, etc.). How would I make a function that would be able to do this in a way where it would replace all of the symbols with their corresponding variables?

I think this is it:

local function calcNumPlrs()
	local num = 0
	for i,v in pairs(game:GetService("Players"):GetPlayers()) do
		num = num+1
	end
	return num
end
print(os.date("*t", os.time()))

function getTime()
	local t = os.date("*t", os.time())
	local s = ""
	s = s.. "year: "..tostring(t.year).. " month: ".. tostring(t.month).. " day: ".. tostring(t.day).. ", "--remove this line if you just want the time of day
	s = s.. tostring(t.hour)..":"..tostring(t.min)..":"..tostring(t.sec)
	return s
end

formatSymbols = {
	timeFormatSymbol = {symbol = "\&t", stringToReplaceWith = tostring(getTime())};
	numPlayersFormatSymbol = {symbol = "\&p",stringToReplaceWith = tostring(calcNumPlrs())};
	numIterationsFormatSymbol = {symbol = "\&i", stringToReplaceWith=tostring(nil)}; -- didn't do this one because i didn't know what you meant by "numIterationsFormatSymbol" with no other context
} -- To add more just put a table with symble being the symbol to use and stringToReplaceWith being some way to get a string
local function formatString(s)
	for i,v in pairs(formatSymbols) do
		s = string.gsub(s, v.symbol, v.stringToReplaceWith)
	end
	return s
end

local veryEpicString = "Game loop : \&i  || Intermission (\&t) with \&p players"

print(formatString(veryEpicString))
local players = game:GetService("Players")

local replacements = {["\&p"] = #players:GetPlayers(), ["\&i"] = os.clock(), ["\&t"] = os.time()}
local s = "Game loop : \&i  || Intermission (\&t) with \&p players."
s = string.gsub(s, "\&%a", replacements)
print(s)

https://developer.roblox.com/en-us/api-reference/lua-docs/string

string.gsub()'s third argument can be a table value of a dictionary structure, where its keys/indices represent matched patterns and its values represent the replacement strings.

image

1 Like