The code attached is a simplified version of the problem I’m trying to find a nice solution to. Suppose I have two functions that I want to call each other under some very specific circumstances. In the script shown, which would be the “ideal” way to define both functions, the script will not run because A()'s definition references B() before B() has been defined. How can I overcome this?
Normally, this would be as simple as putting one function inside the other, but A() and B() are complicated in the actual game and do not call each other directly (only through a chain of other functions) so putting them all together would be a mess and a chore.
I also cannot put both functions in a loop for similar reasons, with with lots of complexity of both the functions and the conditions making it annoying to try and put everything together (I am also told that using while true loops is bad practice generally)
I imagine using a BindableEvent would work (fired by A() and Connected to B()) but this feels a bit clunky and unnecessary. Does anyone know of a better way? If not I will use the BindableEvent, but I thought I would ask first.
You could make them global functions (remove the local). I’m not sure if this would cause issues though.
If you send your actual code though, there’s probably a workaround that doesn’t have to involve this.
Edit: Just tested and this method works,
local runA = false
local runB = true
function A()
print("A")
if runB then
print("A running B")
B()
end
end
function B()
print("B")
if runA then
print("B running A")
A()
end
end
A()
Output:
> A
> A running B
> B
Just make sure that A and B can never both be run at the same time or they will start looping and cause a crash.
Yup, just tested too and can confirm, will test in the actual game in a minute. It’s interesting, because I’ve become used to always defining functions as local, again as “good practice”. Do you know what difference it makes other than B() being able to be referenced earlier in the script?
Yeah, I usually try to avoid global variables mainly because in complex scripts it can cause issues (loops, functions changing them, …). If you do this infrequently you should be fine though.
You can also do an OOP/module like approach which makes them a little more “local”:
local functions = {}
function functions.A()
end
function functions.B()
end
I honestly do not know the performance impact of global variables but it should be fine I think.