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

Script doesn't print outcome, it just stops when it detects a nil value and won't print anything?

--[[ I need to write a function to test whether a given table is a valid sequence.
I thought about using a for loop and check if there is a nil value in the table,
and if there is then it will stop and it will print that the sequence is not valid. --]]


a ={"Test","Hello",2,"Testing",nil,"Okay","WHAT",'3<4'}
function test()
	for i,v in ipairs(a) do
		if i == nil or v == nil then
			print(i.." - "..v.." is not a valid sequence.")
			 
		else
			print(i.." - "..v.." is a valid sequence.")
			
		end
	end
		
end

test()

-- Would this work?


1 comment

0

ipairs means it will stop when it gets a nil value.

1 answer

✓ Accepted answer

Hello there Wizard, I know how to fix your problem. (I posted an answer earlier, but I didn't test it and it wasn't working, but now it is fixed here)

ipairs stops looping through the table once it detects a nil value, in your case it will loop through the table and stop at the string "Testing" because there is a nil value after that.

pairs continues throughout the table and ignores nil values and in fact skips right over them

Though for your case, ipairs would be much more easier to detect if a table is valid or not.

You can just loop through the table and detect if the index reaches the length of the table or not like so:

local a = {"Test", "Hello", 2, "Testing", nil, "Okay", nil, "WHAT", '3<4'}

local num 

function validateTable(tab)
	for i, v in ipairs(tab) do
		num = i
	end

	if num == #a then
		return 'Valid Table!'
	else
		return 'Invalid Table!'
	end
end

print(validateTable(a))
	 

I hope I could help!

1 comment

0

Thanks.

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