Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How could I call a function using a string, assuming it's possible?

Asked by
Netflixy 126
7 years ago

How would I go about to call a function using only a string, which contains the same letters as the function is named?

The code I require for this to even be useful looks somewhat like this:

function afunction(x) --x is a string "abc"
    local function abc()
        print("Function called")
    end
    x()
end

Thank you for all answers.

1 answer

Log in to vote
1
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
7 years ago
Edited 7 years ago

Perhaps you could create a dictionary for the functions to call?

function afunction(x)
    local functions = { --List of functions
        abc = function()
            print("Function abc called");
        end
    }
    local f = functions[x]; --Find the potential function
    if f then
        return f(); --If it exists, return the call.
    else
        warn("No function found"); --Otherwise, warn the output.
    end
end

afunction("abc"); --> Function abc called
afunction("nonexistent"); --> No function found
Ad

Answer this question