How would you do vice versa tho? Making a module script change a value in the main code instead?? Bindable events? What’s the most proper way to do this?
what you mean with changing an varible in the main script?
you could have 1 varible and then the script will check for it everytime. and once it changes the main changes that varible aswell.
Note: if you are planning to let client change stuff be aware of exploiters. because they can send aswell information events and that could ruwen other people thier gameplay.
--main
local Module = require(script.Module)
local Variable = true
Module.Initiate()
--module
Module.Initiate = function()
--do some things
--some time later
--I want 'Variable' in main script to be setted to false
end
This type of dependence between two pieces of code is known as content coupling. This is pretty much always bad and a sign you should rethink your code structure. A module should be completely independent to the script which requires it (otherwise the script requiring is required to conform to some predesigned structure).
The easiest solution to this would probably be to provide the module script with a callback (a function which it can call) which modifies the variable. For example:
--main
local Module = require(script.Module)
local Variable = true
local function modifyVariable(newValue)
Variable = newValue
end
Module.Initiate(modifyVariable)
--module
Module.Initiate = function(callback)
--do some things
--some time later
--I want 'Variable' in main script to be setted to false
callback(false)
end
This is a somewhat quick and dirty solution but is perfectly fine unless you start doing it excessively (if you have more than about 3-4 callbacks you should probably start being careful).
A more complete solution is to use custom data structures to pass data around (in Lua this means just a table you pass to functions which modify it). In the example above you could pass a table containing a single value which the module script can then directly edit. This is much more scalable just make sure you note down what the data structures should contain!
You could return false in the module and do something like this.
local Module = require(script.Module)
local Variable = true
Variable = Module.Initiate()
----- Module
Module.Initiate = function()
--- code
return false
end
EDIT:
If you want it to return the opposite of ‘Variable’ each time, do this.
local Module = require(script.Module)
local Variable = true
Variable = Module.Initiate(Variable)
----- Module
Module.Initiate = function(var)
--- code
return not var
end
local module = {}
function module.load()
local env = getfenv(0)
env.Var = 1
end
return module
So, in the Script the Variable “Var” will exists and the value will be 1.
I used this in a TableUtil Module, that when using requires(module) replaces the variable “table” by one with more functions. and in another that creates a variable called “Class” that allows you to create classes easily, like Class.new()