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

If and elseif fires?

When I touch a part, it prints 'a' and 'b' and I am in the Admin list. Since I am in the Admins list, it suppose to only print 'a' but it also prints 'b'.

local Admins = {
	"Player1",
	"FiredDusk"
}

script.Parent.Touched:connect(function(hit)
	for i,v in pairs(Admins) do
		if v == hit.Parent.Name then
			print'a'
		elseif v ~= hit.Parent.Name then
			print'b'
		end
	end
end)

3 comments

0

Are there multiple people in the Admin list?

0

I am testing in studio, it's only me.

0

The question has already been answered, so I'm gonna give you a small suggestion: Don't use names. User ids are a safer method.

1 answer

✓ Accepted answer

You're iterating over the list, which contains "Player1" and "FiredDusk" - you can't be both of them at the same time, so when it tests "Player" it will print "a" and when, on the next iteration of the loop, it tests "FiredDusk" it will print "b".

I think what you want to do instead is:

script.Parent.Touched:connect(function(hit)
	local found = false
	for i,v in pairs(Admins) do
		if v == hit.Parent.Name then
			found = true
		end
	end

	if found then
		print'a'
	else
		print'b'
end)

Or, equivalently:

script.Parent.Touched:connect(function(hit)
	for i,v in pairs(Admins) do
		if v == hit.Parent.Name then
			print'a'
			return -- exit immediately
		end
	end
	
	print'b'
end)

2 comments

0

I never could understand return, still can't now either. So what does that return do in this script? I did see the comment but does the return make it stop the function??

0

Yes, exactly, return will stop the function so that the print'b' instruction won't be reached, but only if the print'a' statement has been reached - this is one way of enforcing mutual exclusion. Having a 'return' on its own is sort of a special case because, intuitively, return should be followed by some values which the function produces. It is perfectly valid, though, to use it to terminate ear

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