How do i change Module scripts from other scripts?

for example i have a module script with code

local Fruits = {
["Banana"] = 1,
["Apple"] = 6,
}
return Fruits

And for example ServerScript wants to change in the module script apple to 9
how do i do that?

2 Likes

just require it and then change its value

local module = require(path.to.module)
module.Apple = 9
2 Likes

you cant change the module script from other scripts, because what module script actually does is just store the code which can only be read, that means that if you require the module from the other script you would basically be copying its content, so any change you make in a script will remain in the script

Cobalt elevators did with control panel

What? I do not understand what you mean by that

Make it a singleton.

if _G.Fruits then
    return _G.Fruits
end
local Fruits = {
["Banana"] = 1,
["Apple"] = 6,
}
_G.Fruits = Fruits
return Fruits
2 Likes

not sure how that will work.
but it works ._. how?
explain pls

It will only create the table if one does not already exist.

oh. well that wont work if theres more tables named Fruits.

ServerScript:

local Fruits = require(moduleScript) -- Require the ModuleScript

Fruits["Apple"] = 9 -- Change value of "Apple" to 9

print(Fruits["Apple"]) -- 9

ModuleScript:

local Fruits = {
  ["Banana"] = 1,
  ["Apple"] = 6,
}
return Fruits
  • _G is bad practice.
  • require caches the result so it always returns the same value (see ModuleScript for more information).

It’s not bad practice by itself. The reason it is discouraged is because of race conditions that can happen with incorrect use. e.g.

Script 1

_G.hi = "comment"

Script 2

print(_G.hi)

Script 2 causes a race condition because it expects _G.hi to be set by another event that is outside it’s control.

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