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

How could you call a function from an array using a string?

Asked by
jtefurd 50
8 years ago
Edited 8 years ago

Is there a way to call functions from an array using strings? This is what I've tried and it hasn't been working out.

GameModeModule:

local GameModes = {};

GameModes.SingleBattle = function()
    print("Single battle!");
end

GameModes.DoubleBattle = function()
    print("Double battle!");
end

function GameModes:Run(gameMode)
    local func = module[gameMode];
    return function()
        func();
    end
end
return GameModes;

server-script:

local GameModes = require(script.GameModeModule);
local GameModeTypes = 
{
    SingleBattle = "SingleBattle",
    DoubleBattle = "DoubleBattle"
}

module:Run(GameModeTypes.SingleBattle);

1 answer

Log in to vote
1
Answered by 8 years ago
Edited 8 years ago

Yes

Sure, this is completely possible. You have the right idea in your module script (by the way, I'm assuming 'module' is your 'GameModes' table), the only thing you're missing is the actual function call (line 8 of your server script)

Returning functions

When you return a function, you're still returning something that needs to be called. It doesn't get executed during the return process. To fix your problem, you could just call it on the same line as your "Run" method with two parenthesis ()

local GameModes = require(script.GameModeModule);
local GameModeTypes = 
{
    SingleBattle = "SingleBattle",
    DoubleBattle = "DoubleBattle"
}

GameModes:Run(GameModeTypes.SingleBattle)() -- Calling the returned function

However

While this does solve your problem, it also isn't very necessary (not in this case, that is). Instead of returning a function, you should just execute the function you pass as the argument as soon as it's called. Here'd be a better example:

local GameModes = {};

GameModes.SingleBattle = function()
    print("Single battle!");
end

GameModes.DoubleBattle = function()
    print("Double battle!");
end

function GameModes:Run(gameMode)
    local func = GameModes[gameMode]
    if func then -- Maybe just check if it exists as well
        return func() -- Return whatever 'func' returns, while also executing it
    else
        print(tostring(gameMode) .. " is not valid") -- error message to help us know if something went wrong
    end
end

return GameModes;
local GameModes = require(script.GameModeModule);
local GameModeTypes = 
{
    SingleBattle = "SingleBattle",
    DoubleBattle = "DoubleBattle"
}

GameModes:Run(GameModeTypes.SingleBattle)

Hope this helped, let me know if you have any questions.

Ad

Answer this question