Hi all, I have a script that looks like below:
function rabbits() print(1) end) function turtles() print(2) end) function startRound(round) -- I want to call the function that corresponds to 'round' end startRound(rabbits)
Is there an easy way to get the rabbits function called from the startRound function? I know I can make a long if then statement, but I'd have 20 elseifs and that would be annoying.
I tried something like;
function startRound(round) [round]() end
but I knew that wouldn't work when I was writing it, and it didn't. But I want to be able to do something along those lines. Any help would be great, thanks!
Hey, don't I know you? Well, since I'm not home, I wasn't able to test this on ROBLOX, although, I did go on lua.org, and test this out. It appears that your way does work, just remove the square brackets! Here's the lua.org code I tested:
-- hello.lua -- the first program in every language function rabbits() io.write('1') end function turtles() io.write('2') end function startRound(round) -- I want to call the function that corresponds to 'round' round() end startRound(rabbits)
Translated into ROBLOX Lua
function rabbits() print('1') end function turtles() print('2') function startRound(round) round() end startRound(rabbits) -- My only concern could be this erroring. If you put this as a string, it'll error so I left it like that.
Tell me how it works. If I get home before you do it, I'll test it out.
Since ROBLOX uses the same Lua version, just a bit modified, I'd assume it'd work.
Assuming you're meaning for round
to be a String, and not a function reference like it is now, the easiest way is to use a Table:
functionTable = {} function functionTable.rabbits() print(1) end) function functionTable.turtles() print(2) end) function startRound(round) functionTable[round]() end startRound("rabbits") --I *highly* suggest giving these functions more descriptive names.