如何向表类型添加方法? [英] How do I add a method to the table type?

查看:84
本文介绍了如何向表类型添加方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为表类型添加方法?我正在尝试编写一种搜索表值的方法.到目前为止,我有.

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(value)
  for _, v in ipairs(self) do
    if v == value then return true end
  end
  return false
end

但是,当我尝试执行以下操作时.

Yet when I try to do the following.

t = {'four', 'five', 'six'}
t:contains('five')

我得到了错误.

stdin:1: attempt to call method 'contains' (a nil value)

有什么建议吗?

推荐答案

对于所有没有单个元表.与字符串和数字不同,每个表都有其自己的单独的元表.

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.

这篇关于如何向表类型添加方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆