How to call a function whose name is in a string variable?

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
5 Likes

Use getfenv()

getfenv()['Func1']()
1 Like

yeahhhhhhhhh… don’t do that. Using getfenv() disables some of Luau’s optimizations and isn’t good practice to begin with.

1 Like

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 that getfenv deoptimizes the environment even if it’s only used to read values from the environment.

source
1 Like

Why?
In the same source:

When appending elements to tables, it’s recommended to use table.insert

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.

1 Like

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.

3 Likes