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?
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)