while the title may not be really understandable, what i mean is that i want a function that can work in other functions, even though it is listed after them
so lets just say i want a function called function 2 be used during function 1
function function1()
function2()
end
function function2()
-- something here i dunno
end
now this will obviously give an error since, well, the function2 is still not made during function1, so… how would i go about making it usable during function1?
sorry for the unreadableness of this lol!! really dont know how to explain it.
It still does work if the function2 is initialized.
Example:
function function1()
function2()
end
function1() -- errors: "Attempt the index nil"
function function2()
print("Hello World!")
end
function1() -- prints "Hello World!"
If you do not use the local keyword when creating the function, it will become a global function. This means it can be used from anywhere in the script.
When something is local, it is only relevant to that stack of code. For example:
local function something()
local name = "Bob"
print(name) --> "Bob"
end
print(name) --> "nil"
Now, since we used the local keyword, name will only be local to that function “something”, hence why it would output nil when printed outside of it.
However, if we made name global:
local function something()
name = "Bob"
end
print(name) --> "Bob"
it can be used from anywhere in the script, even outside of that particular function it was defined in.
So, if you want to make a function callable from anywhere in the script, just make it global.
foo() --this will not error as "foo" is global
bar() --this will error as "bar" is not global and is relative to where it was defined, in this case anywhere below its definition
function foo()
end
local function bar()
end
foo() --this will not error
bar() --this will not error as it is calling a function below where it is defined
Basically, the example you gave would work, because function2 is a global function. You just didn’t realise it.
But, it might just be best to put that function at the top of the script, in your functions category, and make it local (however you organise your scripts).