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

Using an argument to call a function?

Asked by 9 years ago

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!

2 answers

Log in to vote
0
Answered by
Shawnyg 4330 Trusted Badge of Merit Snack Break Moderation Voter Community Moderator
9 years ago

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.

0
This works, but only because 'rabbits' in the 12th line points to the function on line 1. If it were a string, this would not work. adark 5487 — 9y
0
Haha yeah we do know each other. Ill test this when I get home later tonight. :) Cubes4Life 20 — 9y
0
Glad I could help! Shawnyg 4330 — 9y
Ad
Log in to vote
0
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
9 years ago

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.
0
Though just passing the function makes more sense for most cases BlueTaslem 18071 — 9y

Answer this question