[Help] How can I loop through a string?

Hey! So I am trying to make a script that will loop through a string and add each letter of the string to a table how can I do that? I keep on getting this error:

Players.polarisprog.PlayerGui.LocalScript:17: invalid argument #1 to ‘pairs’ (table expected, got string)

Here is my script:

local number = math.random(1000, 1500)


local abriviations = {
	K = 4,
	M = 7,
	B = 10
}

local abriviatedNumber = {}

local text = tostring(math.floor(number))
print(text)

for i, v in pairs(abriviations) do
	if v == #text then
		for i, v in pairs(text) do -- here is where i get the error
			table.insert(abriviatedNumber, v)
			print(v)
		end
	end
end

Thank you!

3 Likes

Do you want v to be each individual character of the string ?

1 Like

Yeah I want v to be each individual character of the string.

There are 2 ways to do this then, 1 way is using string.gmatch, and using a period so that it returns the next character on each iteration, or just splitting by an empty string and using that table so you get an array of all the characters

for v in text:gmatch(".") do

end

for _, v in ipairs(text:split("")) do

end
18 Likes

Thank you so much, it worked really well !

1 Like

there is also another way, but i think its worse

local s = ""
for i = 1, #text do
	s = text:sub(i,i)
	-- Code
end
6 Likes