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

How do you add or delete a certain character in a string?

I thought Lua also have some basic string manipulation like that, but no, it seems to have more complicated stuff than basic stuff

1 answer

✓ Accepted answer

Strings in Lua are immutable. To modify them, you must create a new string. This new string can be based on the one we want to modify.

Let's say we want to remove the second character from "Hello". How might we go about doing this? Let's try to use the string.sub() function.

local TargetString = "Hello"
local NewString = TargetString:sub(1, 1) .. TargetString:sub(3)

string.sub()'s first argument is the string to substring. The second argument is the position in the character index to start at (1 is the first character's index in the string). The third, optional argument, is the finishing character index to end the substring at. So string.sub(OurString, 1, 1) gets the first character. If the third argument (ending character index) is not present, the substring goes from the starting character index to the end of the string. So string.sub(OurString, 2) is the substring of every character after the first one.

Remember that a:b(c) is sugar syntax for a.b(a, c), so TargetString:sub(1, 1) is equal to TargetString.sub(TargetString, 1, 1).

We use the concatenation operator .. to create a new string with the two stringsconcatenated (glued together).

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