How do I add a method to the table type?

后端 未结 3 604
盖世英雄少女心
盖世英雄少女心 2021-01-05 12:41

How do I add a method to the table type? I\'m trying to write a method that searches through the values of a table. So far I have.

function table:contains(va         


        
相关标签:
3条回答
  • 2021-01-05 12:45

    As was said by others, your t is a simple table, it contains only the following key-value pairs: [1]='four', [2]='five', [3]='six'.

    If you want to "extend" the t to be able to access functions from the table module, you have to set a metatable with __index pointing to the table module. I use the following function to access it easily:

    function T(t)
        return setmetatable(t, {__index = table})
    end
    

    You can then use it as follows (thanks to syntax sugar no parentheses needed):

    t = T{'four', 'five', 'six'}
    t:insert('seven')
    print(t:contains('seven')) --> true
    
    0 讨论(0)
  • 2021-01-05 12:56

    There is no single metatable for all tables. Unlike strings and numbers, each table has its own individual metatable.

    Just make a free function instead of a "member" function for these kinds of things. Not everything needs to be all OOP with : and such.

    0 讨论(0)
  • 2021-01-05 12:58

    You've added a method to the table library but you haven't given any metatable to table t. There is no automatic connection between table and t.

    0 讨论(0)
提交回复
热议问题