I am trying to turn this timer script into a function, but it makes an error (This is a local script).
The initial script:
repeat
local Minutes = math.floor(TotalSeconds / 60)
--/Seconds Function
if (TotalSeconds % 60) < 10 then
local Seconds = (0 .. TotalSeconds % 60)
else
local Seconds = (TotalSeconds % 60)
end
--Seconds Function end
playerGui.TopText.Time.Text = string.format(Minutes .. ':' .. Seconds)
TotalSeconds = TotalSeconds - 1
wait(1)
until TotalSeconds < 0
Now as a function (where the error is):
function Time()
repeat
local Minutes = math.floor(TotalSeconds / 60)
--/Seconds Function
if (TotalSeconds % 60) < 10 then
local Seconds = (0 .. TotalSeconds % 60)
else
local Seconds = (TotalSeconds % 60)
end
--Seconds Function end
playerGui.TopText.Time.Text = string.format(Minutes .. ':' .. Seconds)
TotalSeconds = TotalSeconds - 1
wait(1)
until TotalSeconds < 0
end
The error is created on the last word second, where the word is underlined in orange and says Unknown global 'seconds’
You are initializing the seconds variable inside two if blocks. Therefore, they can’t be seen by anything outside of the if block. You should intialize the variable and set it to nil right after declaring the function:
local seconds
Also, if your intent is to have one seconds variable, you shouldn’t write “local” multiple times. Only use “local” when you are declaring a variable, not setting it.
-- Function scope
if (TotalSeconds % 60) < 10 then
-- If statement scope
local Seconds = (0 .. TotalSeconds % 60)
else
-- Else statement scope
local Seconds = (TotalSeconds % 60)
end
-- Function scope again
playerGui.TopText.Time.Text = string.format(Minutes .. ':' .. Seconds)
TotalSeconds = TotalSeconds - 1
What’s happening here is that you’re creating a variable inside an if statement which causes it to be visible to your code only inside that statement. You should move the variable to a function scope, just like you did with the Minutes variable, for example like this:
repeat
local Minutes = math.floor(TotalSeconds / 60)
local Seconds = (0 .. TotalSeconds % 60)
--/Seconds Function
if (TotalSeconds % 60) >= 10 then
Seconds = (TotalSeconds % 60)
end
-- Rest of your code