How to check if a function is running

Hey there!

So i was wandering if there is a way to detect if a function is currently running.

Any help is appreciated!

Breakpoints or inserting a print into your function.

3 Likes

You could always create a variable that’s a signal of whether a function is running or not. For example:

local functionRunning = false

local function test()
functionRunning = true
— Do stuff
functionRunning = false
end

Edit 1: If it’s a specific function that you want to call from a different script, you could make the variable global, like:

local _G.functionRunning = false

Edit 2: It was brought to my attention that using _G is a form of bad practice and has some disadvantages. Therefore, I wouldn’t rely on this method too much and would stick to ModuleScripts that can deliver the information more accurately. Here’s more information about it.

3 Likes

I want an if statement (outside the running function) to be able to check if the function is running.

local isRunning 
local function running() print(isRunning) end

local thread = coroutine.create(function() -- coroutine in case your function yields
      isRunning = true 
      --// code
      wait(5)  
      --//
      isRunning = false 
end)
coroutine.resume(thread)

print(running()) -- true
wait(5)
print(running()) -- false

-- better approach
-- or simply, without any other variables or function just:
print(coroutine.status(thread) ~= "dead") -- either suspended (i.e when yielding) or running currently, when all the code has executed within the coroutine the status becomes "dead"
2 Likes