Is there a way to loop through each individual character of a string to see if it is a certain letter/number/symbol? I have tried looking on the wiki but I cannot find anything.
Yes there is!
local word = "pizza"
for w in string.gmatch(word, "(%w)") do
print(w)
end
Thanks so much, is there a way to then remove that character?
Wait forget this post I misread what you wanted to do, this is how you add that string to something else. I’ll answer your question in the next post.
local originalword = "ILIKE"
local add word = "pizza"
for w in string.gmatch(word, "%w") do
originalword = originalword..w. ---take that letter and add it to the other word
end
print(originalword) --should print ILIKEpizza
I am basing it off of this post, so you might need to tweak my script:
local word = "pizza is good"
for w in string.gmatch(word, "%w") do
if w == " " then --check if it's a space
word = string.gsub(word, w, "")
end
end
print(word) ---should return pizzaisgood because I took out the spaces
Incorrect, that script will not take out any spaces. %w
is an alphanumeric character; a letter or number, not whitespace. Here is an article on String Patterns for further reference.
Also, there is no reason to use string.gmatch()
if you are replacing characters. You can do string.gsub()
without the loop.
@SilentsReplacement
You should be using %s
since it refers to whitespace or a space character.
local word = "t ab"
for char in word:gmatch("%s") do
word = word:gsub(char, "ab") if a space exists, replace it with ab
end
That is just an example looping and finding a whitespace^. You can instead just use gsub
and replace the string as follows.
local str = "aa bb"
str = str:gsub("%s+", "123") -- using s+ and not s so it will replace all the whitespace in the string, not just one
That was just an example, originally, OP wanted to loop through a string.
Thanks so much, is there a way to then remove that character?
Also note that strings have metatables attached to them too. You can also call a string method directly without having to pass the string as self, there is no point of using string.method()
when you can just do string:method()
local str = "a"
str:match("a")
I wrote it as string.method()
for general reference.
So it does work, but not with commas, do you know why?