#Infinite Loop
You have an infinite loop right before line 13. Lua runs code line by line and once it reaches the loop on line 9, it will stay looping forever until there is a break of some sort. There are 2 ways to get around this. The spawn function or coroutines. Both are different ways to have 2 things of code happen simultaneously in one script.
#Spawn
Spawn is the simplest way to start a new thread when coding. The built in roblox function will start a new thread once Roblox's Task Scheduler updates, which can take at least 29 milliseconds.
spawn(function()
wait(5)
print("Bar")
end)
print("Foo")
Foo Bar
Instead of the script yielding at the wait on line 2, the script makes a new thread and prints Bar after 5 seconds while Foo is able to print freely without yielding.
#coroutines
Coroutines are a bit more complicated than spawn. You can use coroutine.create of coroutine.wrap to make a new coroutine. I prefer the latter. The wiki has some good examples.
local newThread = coroutine.create(function()
print("hola")
end)
coroutine.resume(newThread)
Using wrap instead:
local newThread = coroutine.wrap(function()
print("Hola")
end)
newThread()
Both output the same. Coroutines also have many coroutine functions so that you can have them running in exactly the way you want it to.
local newThread = coroutine.wrap(function()
wait(5)
print("Bar")
end)
newThread()
print("Foo")
Foo Bar
##Coroutine > Spawn
You can reference a coroutine, but not a spawn. Meaning that you can put coroutine into a variable, but cannot do the same for spawn.
local myCoroutine = coroutine.create(function() end)
local mySpawn = spawn(function() end)
print(type(myCoroutine), type(mySpawn))
thread nil
You also cannot pass arguments through spawn.
local delayPrint = coroutine.wrap(function(T, message)
wait(T)
print(message)
end)
delayPrint(5, "Hello World!")
vs
local add = function(a,b)
print(a+b)
end
spawn(add(1,2))
local a,b = 1,2
spawn(function()
print(a+b)
end)
#The Solution
I'd use spawn in this case. Yes, it is a lot simpler than coroutines, but in this situation, you aren't doing anything complex other than making a simple timer that adds points every 5 seconds.
game.Players.PlayerAdded:Connect(function(players)
local folder = Instance.new("Folder",players)
folder.Name = "leaderstats"
local Value_1 = Instance.new("IntValue",folder)
Value_1.Name = "Number"
local Value_2 = Instance.new("StringValue",folder)
Value_2.Name = "Rank"
spawn(function()
while wait(5) do
Value_1.Value = Value_1.Value + 1
end
end)
if Value_1 == 3 then
Value_2.Value = "Rank"
end
end)
####Hope it helps! -LordDragonZord