Getting module to run code twice

First time it’s run, it runs the for loop, cool, but second time it doesn’t and it just skips over everything.

print('Starting gamemode')
require(Gamemode) -- gamemode module
print('Gamemode finished')
-- Module
local Gamemode = {}

for i = 10, 0, -1 do
    print(i)
end

return Gamemode

Please note, this a generalised script, my actual script is too long and tedious to post

I also tried like this

return function()
for i = 10, 0, -1 do
    print(i)
end
end

But this just returned too quickly (printed Starting and gamemode finished straight after each other)

3 Likes

I don’t understand by what you say “second time”. To me, you require it once and it executes the code. There isn’t a second call to that. Can you elaborate?

Cause i call it twice, I havent shown my full code cause it’s too long. Basically its called, gamemode runs, cool. Then the game loops back, and the gamemode is called again, but it doesn’t work

1 Like

I wouldn’t require it twice. I would put it inside a function in that module and call that function in the code.

1 Like

This is because require caches the return value of a module. You can verify this by doing require(module) == require(module) assuming it returns a table or function.

To work around this, you could simply have a function within your module (or even have the module return a function) which can be invoked as many times as you like. Like so:

return function()
    -- code here
end

Then call it anywhere:

require(module)()
-- maybe like this
local mod = require(module)
mod()
-- ...
mod()
-- etc

Require caches because it’s unnecessary to re-run your code if it’s required from a different script. It’ll simply return the first value it returned.

4 Likes