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

Can a for loop skip a certain value?

I'm not quite sure how to explain this but i'll try

--Imagine you had a simple for loop with a table
local _table = {
	1,
	2,
	"gorilla",
	3,
	4,
}
for i,v in pairs(_table) do
print(v)
end
--> Console: 1, 2, gorilla, 3, 4

What I'm asking is if its possible for this script to print all of the numbers but skip the gorilla string. Like below

-->Console: 1,2,3,4

1 comment

0

Is that the real script? or is this script just used as an example? Posting your real script might be better with this question as different Value types can be sifted with numerous ways

1 answer

✓ Accepted answer

The best way to print just numbers is to use either tonumber() or type().

Example:

(Using tonumber())

local _table = {
    1,
    2,
    "gorilla",
    3,
    4,
}

for i,v in pairs(_table) do
	if tonumber(v) then
		print(v)
	end
end

What the above does is this:

tonumber is a function that converts strings to numbers; if it can . By using an if statement, I am testing whether or not the conversion went through. If it did, the statement will be true, and it will print the number; if not, the value will not print.

Note: if you call this function while the value is a number (like, try to convert a number to a number), it will still return true; and the number will print.

(Using type())

local _table = {
    1,
    2,
    "gorilla",
    3,
    4,
}

for i,v in pairs(_table) do
	if type(v) == "number" then
		print(v)
	end
end

What the above does is this:

type is a function that returns the type of value the argument is. If the argument is "gorilla", then it will return string; however, if the argument is 1, then it will return number. type cannot determine, though, the difference between 1 and "1" (the number one and a stringified one) considering the stringified one is a string.

I am using the if statement to ensure that the returned type, is a number. If it is, the statement is true, and the number is printed, if not, then the for loop "skips" (iterates) again.

Resources:

tonumber()

type()

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