Replacing Characters in Strings

Heya! I’m currently working on a guessing game, simillar to to Scribbl.io
I’m trying to work out a hint system. There’s a “_” for every character and as the game goes on more of the word is revealed. I haven’t messed much with strings before and the way I have it doesn’t work very well.

Is there a better way I could script this?

function GameFunction.Hint(Prompt)
	local Status = ReplicatedStorage.Values:WaitForChild("Status")
	local HintPos = math.random(1, string.len(Prompt))
	local HintVal = string.sub(Prompt, HintPos, HintPos)
	
	Status.Value = ""
	
	for i = 1, #Prompt, 1 do
		-- Check For Hint Pos
		if i == HintPos then
			Status.Value = Status.Value .. HintVal
		else
			Status.Value = Status.Value .. " _ "
		end
		task.wait(0.025)
	end
end

You could use a table with all the letters of the word stored in it like

Table {h,e,l,l,o} and use a math.random to randomly replace the _ with the characters

1 Like

This belongs in #help-and-feedback:code-review category.

function GameFunction.Hint(Prompt)
	local Status = ReplicatedStorage.Values:WaitForChild("Status")
	local HintPos = math.random(Prompt:len())
	local HintVal = Prompt:sub(HintPos, HintPos)
	
	Status.Value = string.rep("_", Prompt:len())
	
	-- Splits and recombines the string
	Status.Value = string.rep("_", Prompt:len())
	Status.Value = Status.Value:sub(1, HintPos-1) .. HintVal .. Status.Value:sub(HintPos-Prompt:len())
end

Please let me know if there is a problem!

1 Like

Sorry about that. Anyways, this works well! However, I’d like to reveal more letters as the game goes on, and when the function is called it’ll remove the old hint. Is there a way I can filter the _?

Sorry for the late reply.

This is pretty easy to do. There are multiple ways to set it up like this, but the base concept remains the same. In some way, you have to have a way to check the current prompt and see if it’s the same as the previous.

local previousPrompt = ""

function GameFunction.Hint(Prompt)
	local Status = ReplicatedStorage.Values:WaitForChild("Status")
	local HintPos = math.random(Prompt:len())
	local HintVal = Prompt:sub(HintPos, HintPos)
	
	Status.Value = if (Prompt == previousPrompt) then Status.Value else string.rep("_", Prompt:len())
	previousPrompt = Prompt
	
	-- Splits and recombines the string
	Status.Value = string.rep("_", Prompt:len())
	Status.Value = Status.Value:sub(1, HintPos-1) .. HintVal .. Status.Value:sub(HintPos-Prompt:len())
end

Please let me know if you have any questions!

1 Like