如何检查表是否包含 Lua 中的元素? [英] How to check if a table contains an element in Lua?

查看:31
本文介绍了如何检查表是否包含 Lua 中的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有检查表是否包含值的方法?我有自己的(天真的)功能,但我想知道是否存在官方"的东西?或者更有效的东西......

Is there a method for checking if a table contains a value ? I have my own (naive) function, but I was wondering if something "official" exists for that ? Or something more efficient...

function table.contains(table, element)
  for _, value in pairs(table) do
    if value == element then
      return true
    end
  end
  return false
end

顺便说一下,我使用这个函数的主要原因是将表格用作集合,即没有重复的元素.还有什么我可以用的吗?

By the way, the main reason I'm using this functions is to use tables as sets, ie with no duplicate elements. Is there something else I could use ?

推荐答案

您可以将值作为表的键.例如:

You can put the values as the table's keys. For example:

function addToSet(set, key)
    set[key] = true
end

function removeFromSet(set, key)
    set[key] = nil
end

function setContains(set, key)
    return set[key] ~= nil
end

此处有一个功能更齐全的示例.

There's a more fully-featured example here.

这篇关于如何检查表是否包含 Lua 中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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