How to make a module method call's argument reference the original value

I have this setup here

-- main script
local module = require(script.ModuleScript)

local tab = {value = 1}
module:method(tab)
tab.value += 1
-- module script parented under the main script
local module = {}

function module:method(tab)
    print(tab.value)
    wait(4)
    print(tab.value)
end

return module

When calling “module:method(tab)” in the main script, I increment the value of the passed in table inside of the main script. The behavior I’m trying to get is when I change the state of the table in the main script, it should also change in the module script call. The problem I’m facing is when I call a wait(), the method call will still use the table that was passed in rather than the one in the main script.

What the “module:method()” does

-- Output:
-- 1
-- waits 4 seconds
-- 1

What I want “module:method()” to do

-- Output:
-- 1
-- waits 4 seconds
-- 2

I also want to try and not use an if statement/checker before printing the value a second time since I am going to implement this into bigger projects. This is just an example.

Any solutions?

Since the function yields, both scripts wait for wait(4) before proceeding. Wrap the function in the module script with task.spawn for your effect

1 Like

Use a coroutine.

-- module script
local  module = {current = nil}

function module:method(tab)
    if self.current ~= nil and coroutine.status(self.current) ~= "dead" then
        coroutine.resume(self.current)
    else 
        local co = coroutine.create(function (tab) 
            print(tab.value)
            coroutine.yield()
            print(tab.value)
       end)
       self.current = co
       coroutine.resume(self.current, tab)
    end
end

return module
-- script
local module = require(script.ModuleScript)
local tab = {value = 1}
module:method(tab)
tab.value += 1
module:method()

You can simply use a coroutine and store it in the table, resuming it every time you call module.method until its "dead". That way, you can execute code while the coro is still not finished.

1 Like