Useful but suspiciously specific coding tips

Small idea I got not so long ago, count it as something funny that you would usually see on YouTube Shorts:

  1. if you have a whole bunch of waits in your loop and you want to pause the loop midway if some certain condition met, you can just simply trap the code before the wait() in repeat function:
plr.Chatted:Connect(function(Message)
   paused = true
   --do stuff
end)

while true do
   --stuff
    if paused == true then
		repeat wait(2) until paused == false
	end
    wait(1)
   --other stuff
end
  1. If you have night/day cycle in your game and you want certain things to happen at night for example, you can compare lowest values of “ClockTIme” in lighting, then if a number is out of range create another check if the number is higher than something, otherwise, if none of the requirements are met, then it’s day:
if game.Lighting.ClockTime > 0 and game.Lighting.ClockTime < 6 then
		script.owl:Play()
		script.Crickets.Playing = true
	elseif game.Lighting.ClockTime > 18 then
		script.owl:Play()
		script.Crickets.Playing = true
	else
		local birdrng = math.random(1,3)
		if birdrng == 1 then
			script.bd1:Play()
		elseif birdrng == 2 then
			script.bd2:Play()
		elseif birdrng == 3 then
			script.bd3:Play()
		end
	end
	script.Crickets.Playing = false
end
  1. if you have a loop that executes another loop midway and the player leaves, no matter how many checks you will add to make sure that the player is here, it won’t work, so it’s better to put that another loop in pcall() function (which stops function from erroring):
--you need local player though, ill just call it "player", whetever the way you'll get them

local function numbersUp()
   pcall(function()
      for i,v = 1, 5 do
         -- stuff, for example, player.leaderstats.Cash.Value += i
      end
   end)
end

while true do
   numbersUp() -- if player will leave, nothing will happen so other people will be able to execute the code
end
5 Likes

you could also do pcall(numbersUp) instead of doing the pcall inside the function :+1:

2 Likes

Another tip: use task.wait() since wait() is deprecated.

2 Likes

This is bad code. It’s better to use event based coding.

while true do
	--stuff
	plr.Chatted:Wait()
	--do stuff
	task.wait(1)
	--other stuff
end

loop polling is always bad. Ie. if you have a loop which only waits until something happened, that is bad. Use event based coding instead.


You should rather do. Also the for loop is invalid. This is a better version \/

local function numbersUp()
	for i = 1, 5 do
		-- stuff, for example, player.leaderstats.Cash.Value += i
	end
end

while true do
	pcall(numbersUp) -- if player will leave, nothing will happen so other people will be able to execute the code
end
2 Likes