Running a function while a loop is running in the other function issue

Hi, I am beginner scripter and I am learning about OOP and metatables but I have a problem with running a function while a loop is running in the other function.

Module script:

local NPC = {}
NPC.__index = NPC

function NPC:Move() -- When this function is executed by server script and "while true do" loop starts then I can't execute "NPC.New" function :(
	while true do
        -- Code
		wait(5)
	end
end

function NPC.New()
	local objectTable = setmetatable({}, NPC)
	--code
	return objectTable
end

return NPC

Server script:

local SpawnScript = require(ServerScriptService:WaitForChild("ModuleScripts"):WaitForChild("SpawnScript")) -- Spawn script is a module script

for i = 1, 5, 1 do -- It spawns only one "NPC" and moves it every 0.5 second but it should spawn 5 NPCs that would walk at the same time.
    wait(0.5)
	local NPC = SpawnScript.New()
	NPC:Move()
end

I tried using task.spawn() but I don’t understand it and when I used it, it still didn’t worked
And my question is how to fix that? is using task.spawn() a good idea? if yes how to do it?

Sorry if there are any spelling mistakes but I am learning English :smiley:

You can use task.spawn or coroutines to run asynchronous code.
To use task.spawn, you just need to pass in a function or a thread which would be a function in your case. Updated version of your server script code:

local SpawnScript = require(ServerScriptService:WaitForChild("ModuleScripts"):WaitForChild("SpawnScript")) -- Spawn script is a module script

for i = 1, 5, 1 do -- It spawns only one "NPC" and moves it every 0.5 second but it should spawn 5 NPCs that would walk at the same time.
    wait(0.5)
	local NPC = SpawnScript.New()
	NPC:Move()
    task.spawn(NPC.Move, NPC)
end
1 Like

Like this:

function NPC:Move()
    task.spawn(function()
	    while true do
            -- Code
		    wait(5)
	    end
    end)
end
1 Like

That way works but is more tedious since you have to task.spawn it everywhere you use it!

2 Likes

True, but I was just considering it’s specific use. Also, it wouldn’t work if they ever wanted to wait for the function to return. An alternative would be:

local function Move(Npc)
    while true do
       -- Code
       task.wait(5)
     end
end

function NPC:Move(yield:boolean)
   if yield then
      Move(self)
   else
      task.spawn(Move, self)
   end   
end
2 Likes