How to run module scripts again?

Hey all!

What I’m currently trying to do is get the total number of objects in a playerfolder in a string, in a table, in a module. Here’s some example code of this:

This is the module script:

local player = game.Players.LocalPlayer

local function getObjects()
    local count = 0
    for i,v in pairs(player.Objects:GetChildren()) do
        count = count + v.Value
    end
    return count
end

return {
	
    [1] = "Hello again, "..player.Name.." I see you have "..getObjects().." parts in your 
inventory"

}

Player script:

local module = require(game.Workspace.Module)

while wait(5) do
    print(module[1])
end

Essentially what happens, since module scripts are only ran once, the output will ALWAYS print that you have 0 parts, even if you have more. Any ideas on what I can I do to get around this? I have tried re-requiring the module script, but this does not change the result.

1 Like

ModuleScripts cache their result, so the table is always the same. Return a factory function instead:

return function()
    return {
        "Hello again, "..player.Name.." I see you have "..getObjects().." parts in your 
inventory"
    }
end

So this becomes

while true do
    print(module()[1])
    wait(5)
end

Although I don’t see the necessity of a module here, all it is doing is returning a table with 1 string in it.

2 Likes

Thank you-- this is exactly what I was looking for!

The actual module has a lot more to it than just 1 line, I simply wrote that so people would easier understand what’s going on.