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

How i can use "for index,value in pairs() do" with a string?

Hi guys, sorry for bad english

I have a "password" and this password change for every game. I need check all letters inside this password and run a function for each of them.

For example if the code is "7654" i need run a function for the "7", "6","5" and "4". But... how i can check it? How i can see the code?, something like this

for i,v in pairs("5555") do -- obviusly, this is impossible

--i need this output

1 5
2 5
3 5
4 5

Any idea?

Thanks!

1 answer

✓ Accepted answer

pairs() is a key-value-pairs iterator function, meaning in retrospect it is used to traverse through the attributes of an array. The passphrase you have is a String datatype, meaning this loop will not be suitable in this situation.

Instead, we can use another iterator function that is given by a special method of the String class called gmatch, which we can pass a pattern to define how we interpret this string.

local Passphrase = 123456

for Char in tostring(Passphrase):gmatch("[%w%p]") do
	print(tonumber(Char))
end

The pattern [%w%p] matches a character that is alphanumeric or punctuated. Since we're not using the + quantifier in conjunction with the set, we will only get one character at a time resulting in this output:

1
2
3
4
5
6

If you desperately need to have the index point, you can construct an array with the pieces pulled from our :gmatch iterator:

local Passphrase = 123456

local Characters = {} do
	for Char in tostring(Passphrase):gmatch("[%w%p]") do
		table.insert(Characters, tonumber(Char))
	end
end

for i,v in pairs(Characters) do
	print(i,v)
end

If this helps, don't forget to accept this answer!

1 comment

0

Thank you! :D

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