Can you call functions using a string?

Hiya! One of the questions that has been going through my mind recently is: "Is there any way of calling a function or variable using a string, for example (Pseudo Code):

local function test()
    print("Hello!")
end

toFunction("test")()

I’ve had a quick look through the forum and couldn’t see anything similar to this. The easiest way of doing it would be something like:

local function test()
    print("Hello!")
end

local functionString = "test"

if functionString == "test" then
    test()
end

but I really don’t want to do it that way since it would take a lot of space doing elseif statements for each function and also looks messy and unprofessional!

Thank you so much for reading! Any help would be appreciated! :grin:

1 Like

This seems impractical and unnecessary.

What you can do is write a function to a dictionary’s key, and then call that dictionary key.

1 Like

Yes you can. You have a few options. You can put it in a dictionary and call it

local funcs = {
    ["name"] = function()
        -- code
    end
}

funcs["name"]() -- or funcs.name() if it doesn't have spaces

Or you can make use of getfenv():

function x()
	print("Hello world")
end

getfenv()["x"]()
3 Likes

This is not recommendable, as the use of global variables in itself is already discouraged, and the use of getfenv disables some of Luau optimizations.

5 Likes

Oh thank you! I’ll certainly check that out!

Ah I see, is there a better way I could do it?

The first option that Steven provided

1 Like