Making a function run once in for i,v pairs()

local bad_guys = {"Someone whos bad", "a very bad person", "Bad guy"}

game.Players.PlayerAdded:Connect(function(plr)
	for _,bad_dude in ipairs(bad_guys) do
		if plr.Name ~= tostring(bad_dude) then
			print('he is not bad!!!!!!!!')
		end
	end
end)

So, I made this code for fun. But here’s a thing.
‘he is not bad!!!’ will print 3 times because theres 3 usernames in the table.

I Know i can do if plr.Name ~= "Bad guy or "Some1 whos bad"
But that will be long and boring.

Is there a way to make the print() function run once for i,v pairs()?

2 Likes
local bad_guys = {"Someone whos bad", "a very bad person", "Bad guy"}

game.Players.PlayerAdded:Connect(function(plr)
	for _,bad_dude in ipairs(bad_guys) do
		if plr.Name ~= tostring(bad_dude) then
			print('he is not bad!!!!!!!!')
            return
		end
	end
end)
1 Like

You can also use break if you just want to end the loop but not the scope

2 Likes

Thank you so much char limit

1 Like

Oh I also want to make it print all the strings in the table by doing this

local bad_guys = {"Someone whos bad", "a very bad person", "Bad guy"}

game.Players.PlayerAdded:Connect(function(plr)
	for _,bad_dude in ipairs(bad_guys) do
		print(bad_dude)
		if plr.Name ~= tostring(bad_dude) then
			print('he is not bad!!!!!!!!')
			return
		end
	end
end)

but it only prints 1 of them, and I dont want that to happen

1 Like

You can run another ipairs below the first ipairs

game.Players.PlayerAdded:Connect(function(plr)
	for _,bad_dude in ipairs(bad_guys) do
		print(bad_dude)
		if plr.Name ~= tostring(bad_dude) then
			print('he is not bad!!!!!!!!')
			return
		end
	end

   for _,bad_dude in ipairs(bad_guys) do
		if plr.Name ~= tostring(bad_dude) then
			print('he is not bad!!!!!!!!')
			return
		end
	end
end)

i guess that works for me char limit

Okay nevermind, it just uses one username repeatedly and doesnt work as intended

This code is quite inefficient. You only need one for loop and you do not need to iterate through the entire array. Your code also doesn’t work as intended, as it will not run the second snippet of code if they are not a bad guy.

Just make use of table.find and an else statement.

Players.PlayerAdded:Connect(function(Player)
    if table.find(bad_guys, Player.Name) then
        print("bad")
    else
        print("not bad")
    end
end)
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.