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

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

Asked by 9 years ago

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

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

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)

0
Thanks again! I've been having a little trouble with tables recently and I just wanted to clear things up TurboFusion 1821 — 9y
0
People usually neglect to explain methods in Lua explanations, so it tends to confuse people when they come up BlueTaslem 18071 — 9y
Ad

Answer this question