local FuncToCall
function Func1()
print("Hello1")
end
function Func2()
print("Hello2")
end
FuncToCall = "Func1"
FuncToCall = "Func2"
How to call “Func1” or “Func2” using the string stored in the variable “FuncToCall”?
local FuncToCall
function Func1()
print("Hello1")
end
function Func2()
print("Hello2")
end
FuncToCall = "Func1"
FuncToCall = "Func2"
How to call “Func1” or “Func2” using the string stored in the variable “FuncToCall”?
There are a few ways to do this, but I’d suggest treating the functions as variables and storing them in a table.
local FuncToCall
local funcs = {}
function funcs.Func1()
print("Hello1")
end
function funcs.Func2()
print("Hello2")
end
FuncToCall = "Func1"
FuncToCall = "Func2"
local func = funcs[FuncToCall]
if func then
func()
end
Use getfenv()
getfenv()['Func1']()
yeahhhhhhhhh… don’t do that. Using getfenv()
disables some of Luau’s optimizations and isn’t good practice to begin with.
Be more specific then, I’m interested what specifically is the issue with that. Because that answers his direct question without suggesting alternative.
You don’t use it for the same reason you don’t use _G
, and, by doing that you have essentially “tainted” the environment. When you do table.insert
you can’t guarantee you are getting the right thing anymore, and like i mentioned it deoptimizes the env.
The use of any of these functions performs a dynamic deoptimization, marking the affected environment as “impure”. The optimizations are only in effect on functions with “pure” environments - because of this, the use of
loadstring
/getfenv
/setfenv
is not recommended. Note thatgetfenv
deoptimizes the environment even if it’s only used to read values from the environment.
No, that was an example. I see your confusion lol. I am saying you can’t guarantee that in that example table
even refers to the built-in library anymore once the env is tainted.
setfenv and getfenv are some old black magic with lua and are designed to do specifically what this post is asking about, but are not exactly advised.