Another modulescript question

hello all,

i’ve seen other threads but i haven’t quite been able to understand the fix to my problem. here is what i want to accomplish:

because i do not want the code from my script to be seen/taken, i will provide an example.

local module = {}

function module.test(player)
	local character = player.Character
	print(character.Name)
end

function module.test2(player)
	local character = player.Character
	wait(3)
	print(character.Name)
end

return module

assume that the above is the module.

local testmod = script.parent.testmod
require(testmod).test2(player)
require(testmod).test(player)

the code above is a snippet of how it would be called.

i would need these two functions to work simultaneously. so, it would print the characters name immediately on activation, and then 3 seconds later. not wait 3 seconds, then print it twice in a row.

i’ve tried coroutine, but i haven’t been able to use it correctly. somebody please correct/give a correct example how the code is being called, so they would function as desired. thank you for your time.

1 Like

You could try task.spawn which will spawn in another thread. It’s somewhat similar to coroutines

1 Like

coroutine.create / coroutine.wrap both work for this
you would run test2 like this:
coroutine.wrap(require(testmod).test2)(player)

i think the task library is faster or something though(?)would look into that

1 Like

Honestly, I recommend task.spawn over coroutine if you just want to spawn in an instant-thread. If you want to have controls over it, I’d recommend going for coroutines.

Depending on the scale of your project, you may want to look into the Promise library for a more sophisticated approach.

Promises fix many of the scheduling and throttling issues developers face from the task native task library.

Example from website:

Promise.delay(5):andThen(function()
    print("5 seconds have passed!")
end)

how would i use task.spawn correctly here?

If you save the result of require you can do a nice one liner

local testmod = require(script.parent.testmod)
task.spawn(testmod.test2, player)
testmod.test(player)

Or you could do

task.spawn(function()
    require(testmod).test2(player)
end)
require(testmod).test(player)

Anything that can be done with a single task library function is a terrible use case for promises. Their use case is not complicated enough.

thank you. ive been looking for a solution for a while now. you are a huge help to me.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.