Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Replacing characters with gsub, corresponding to position?

Is it possible, when using string.gsub, to replace a character oat one position in a string with a different character from another string at the same location as the original?

For example, here's what I have


Cake = workspace.Cake -- Cake is a StringValue

----Many lines later..
		local RealCake = Cake.Value
		local FakeCake1 = string.gsub(RealCake, "%w", "-") --Changes every letter in 'Cake' to be a Hyphen, only in the FakeCake1 Variable.

		function Randomizer(thing)
			FakeCake1 = string.gsub(RealCake, "-", (       --Where I've hit a wall in the script creating process.
			
		end

What I'm trying to get it to do is every time the function 'Randomizer' is called, it will look for the position of a letter/number in RealCake, and replace a hyphen in that same position in FakeCake1 with that letter from RealCake.

Is it possible to use gsub for this? Or should I approach this using a different method? Any help is appreciated, ad if I need to clarify anything please let me know. Thanks! :)

4 comments

0

Trying to make hangman?

0

Something of the sort.

0

Don't add `.Value' to RealCake. Instead place it on line 05 'RealCake.Value' or Cake.Value.

0

RealCake and FakeCake are in a function. I'm not defining the Value globally because it can change. If I did it globally, it would forever stay one value.

1 answer

✓ Accepted answer

The trick is to not.

Assuming something like Hangman, you're going to want to try something like this.

Hangman

TryRevealed = function(FullString, Chars)
	return FullString:gsub("[^"..table.concat(Chars,'').."]","-");
end;

How does this work?
Given an origin string and a table of characters to reveal, it subs out every single character that is not the ones you're looking for.

Reveal

RevealRandom = function(Current, Origin, RevealChar)
	if not Current:match("["..RevealChar.."]") then return Current end;
	local get = math.random(#Current);
	while Current:sub(get,get) ~= RevealChar do get = math.random(#Current); end;
	if get == 1 then
		return Origin:sub(1,1)..Current:sub(get+1,-1);
	elseif get == #Current then
		return Current:sub(1,get-1)..Origin:sub(-1,-1);
	else
		return Current:sub(1,get-1)..Origin:sub(get,get)..Current:sub(get+1,-1)
	end;
end;

I couldn't think of an elegant solution for this one.

6 comments

0

Would this maintain the Character's position though?

0

Good lord, that's flippin brilliant. 0_0

0

Thanks!

0

Current is the current string, correct?

0

Yeah

0

Ok, just making sure. :)

This discussion is preserved as it was. New answers, comments, and votes are closed.