I have modulescript(b) thats required by another modulescript(a). But I want to call a function in modulescript(a) from inside an event on modulescript(b).
Im curious if im formatting my game and scripts properly and if this is an issue that shouldnt be happening. Thanks!!
You can’t directly call a function in a from b if a has required b (as this will cause an error).
A workaround is to use BindableEvents and/or BindableFunctions, with b triggering the event and a running the function when the Event or OnInvoke event is triggered.
e.g.
-- B
local BindableFunction = game.Workspace.ReplicatedStorage.BindableFunction
-- To call it:
local ReturnVal = BindableFunction:Invoke(1,2,3) -- you can include arguments
Then
-- A
local BindableFunction = game.Workspace.ReplicatedStorage.BindableFunction
BindableFunction.OnInvoke = function(a,b,c)
print(a,b,c)
return a + b + c
end
-- OR
local function FunctionInA(a,b,c)
print(a,b,c)
return a + b + c
end
BindableFunction.OnInvoke = FunctionInA
In general this does imply a problem but it’s not necessarily always a problem. It does usually mean there is a better more direct architecture though.
That said, you can always inject the function into module b to solve this. So like make it so module b doesn’t start until you call some initialize function and pass your module or function into it directly. Still, unless you explicitly are trying to do dependency injection, you may want to reconsider your structure.
It’s pretty tricky to reason in the abstract about cases like this. Dependency injection can be the answer. A lot of these types of problems though come from missing some type of system that should be initializing both A and B though. This may just lead to still injecting A into B or it may not. But if it does ownership is more clear.