Call Function Before Being Made

Hey, I have a problem, I’d like to call a function before it is known, is that possible?
Pretty much if they both get indexed is it possible to call a functionB that doesn’t exist but will exist whenever the functionA is called?

See this excerpt from StackOverflow

Lua is a dynamic language and functions are just a kind of value that can be called with the () operator. So you don’t really need to forward declare the function so much as make sure that the variable in scope when you call it is the variable you think it is.

This is not an issue at all for global variables containing functions, since the global environment is the default place to look to resolve a variable name. For local functions, however, you need to make sure the local variable is already in scope at the lexical point where you need to call the value it stores, and also make sure that at run time it is really holding a value that can be called.
Forward define a function in Lua? - Stack Overflow

Basically what this is saying is that functions need to be in scope before you can call them. What you are essentially asking to do here is use a variable before it has been declared which is not possible (unless you have a time machine).

There’s no perfect solution as what I’m aware of. I have done this:

local functionB

function functionA()
print(functionB())
end

function functionB()
return "Hello World!"
end

I have done this countless times.

However, if you are referring to directly calling a function before being made, you should pay attention to post #2.

1 Like

You can do this simply using a module.

local modulescript = require(themodule) or nil
local t = {}

function t.f1()
	t.f2("Hello world!") --t.f1 calls t.f2 before it has been defined (in the script).
end

function t.f2(a)
	print(a)
end

The simplest way to achieve this is via tables (global functions would technically be simpler but their use is discouraged).

3 Likes

I will try this in a little seems the most promising