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

How do I assign a function with parameters to a table?

Ok, so I've been trying to figure out how I would call a function with parameters on a table, like this:

local Test = {1,2,3}

function Test.Find(Element)
	for _,v in pairs(Test) do
		if v == Element then
			return v
		end
	end
	return nil
end

print(Test:Find(2))

It kept printing nil and I eventually troubleshooted and found out that no matter what I put Element as, Element would still end up being table Test. How would I edit this so that it does what it's supposed to do?

1 answer

✓ Accepted answer

You are using a : (method call) instead of a . (normal property)

Use the dot, and it will work as you expect!

But...


The colon would let you make a slightly better version of your function, but a slightly different one.


a:b(x) is the same as a.b(a,x).

So you are getting Test as the first parameter to your function! (Test:Find(2) is Test.Find(Test, 2))

We can change your function to look like this:

function TableFind(Table, Element)
	for _,v in pairs(Table) do
		if v == Element then
			return v
		end
	end
	return nil
end

Test.Find = TableFind

Now we can use the same TableFind on any table, not just Test, as long as we use : (which is why : is useful)

2 comments

0

Thanks again! I've been having a little trouble with tables recently and I just wanted to clear things up

0

People usually neglect to explain methods in Lua explanations, so it tends to confuse people when they come up

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