Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Using an argument to call a function?

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

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.

3 comments

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.

0

Haha yeah we do know each other. Ill test this when I get home later tonight. :)

0

Glad I could help!

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.

1 comment

0

Though just passing the function makes more sense for most cases

This discussion is preserved as it was. New answers, comments, and votes are closed.