How to Communicate between Two Threads in the Same Script?

I would like to make it so a coroutine can call a function that runs in the main script (non-coroutine thread), so the coroutine can still continue its loop as before.

I ideally want these to run at the same time, however they aren’t…

This is the code

local function testFunc()
	while true do
		print("hi")
		wait()
	end
end

local function rayCast()
	testFunc()
	while true do
		print("ray")
		wait()
	end
end
local testRayCoroutine = coroutine.create(rayCast)
coroutine.resume(testRayCoroutine)

This is the output
image

I’ve thought about using events, but I think that would just over-complicate things, especially since they are in the same script.

Any ideas will be greatly appreciated :slight_smile:

task.spawn(testFunc)

Or

coroutine.wrap(testFunc)()
1 Like

So, this would make testFunc in its own coroutine?

Why don’t you just use 2 threads? One for your testFunc and one for your ray cast?

1 Like
local function testFunc()
	while true do
		print("hi")
		wait()
	end
end

local function rayCast()
	task.spawn(testFunc)
	while true do
		print("ray")
		wait()
	end
end
local testRayCoroutine = coroutine.create(rayCast)
coroutine.resume(testRayCoroutine)
3 Likes

Ah, I think I understand that I need to make a new thread for testFunc to run in, thanks :+1:

1 Like