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

How to I run functions inside a Table?

So i'm trying to make a function run inside a Table, Here's my table:

Functions = {
[1] = Test("Hello!"),
}

And here's my simple function:

function Test(String)
	print(String)
end

So yeah, how would I do it? I already tried doing this:

Functions[1]

But that didn't work .(Sorry if that's a dumb mistake, i'm not really good at scripting..)

2 answers

✓ Accepted answer

Your first script segment can be evaluated like this:

Functions = {
[1] = Test("Hello!"),
}
--[1] is the same as this:
Functions = {Test("Hello!")}
--Test("Hello!") asks lua to run the function. Test calls 'print' but doesn't return anything, making this line evaluate to:
Functions = {}

Clearly this isn't what you want. If you want Functions[1] to print "Hello!", use an anonymous function:

Functions = {
	[1] = function() Test("Hello!") end,
}
--Usage:
Functions[1]()


--Or don't use an anonymous function:

Functions = {
	[1] = Test		--Notice how we don't call it here, we just assign it to index 1 of the table
}
--Usage:
Functions[1]("Hello!")


--Or use Functions like a dictionary:

Functions = {}
Functions.Test = Test
--Usage:
Functions.Test("Hello!")

--If Functions is just supposed to be a list of functions, you don't need the [1] syntax; just do:
Functions = {
	Test,
	Test2,
	function() print("Anonymous function") end,
	--etc
}
--Functions[1] is Test, Functions[2] is Test2, etc

1 comment

0

Thanks

I setup my functions inside tables like this

local table = {
	func = function()
		print("hey look at me")
	end
}

table.func()

wiki page with examples

2 comments

0

I read the Wiki already... Is there a way to do it without making the actual function inside the table? I just want to call it from the table.

0

Should work then.

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