尝试在LUA中构建唯一值表

尝试在LUA中构建唯一值表,lua,lua-table,Lua,Lua Table,我正在尝试构建一个表,并在每次得到表中尚未存在的返回值时将其添加到表中。所以基本上到目前为止我所做的根本不起作用。我是LUA的新手,但一般来说不熟悉编程 local DB = {} local DBsize = 0 function test() local classIndex = select(3, UnitClass("player")) -- This isn't the real function, just a sample local cifound

我正在尝试构建一个表,并在每次得到表中尚未存在的返回值时将其添加到表中。所以基本上到目前为止我所做的根本不起作用。我是LUA的新手,但一般来说不熟悉编程

local DB = {}
local DBsize = 0

function test()
  local classIndex = select(3, UnitClass("player")) -- This isn't the real function, just a sample
  local cifound = False

  if classIndex then
    if DBsize > 0 then
      for y = 1, DBsize do
        if DB[y] == classIndex then 
          cifound = True
        end
      end
    end

    if not cifound then 
      DBsize = DBsize + 1
      DB[DBsize] = classIndex
    end
  end
end
然后,稍后我尝试使用另一个函数来打印表的内容:

        local x = 0

        print(DBsize)
        for x = 1, DBsize do
            print(DB[x])
        end 

任何帮助都将不胜感激

只要使用您的唯一值作为键在表中存储一个值即可。这样,您就不必检查值是否已经存在。如果第二次使用任何现有密钥,只需覆盖它即可

存储100个随机值中的唯一值的简单示例

local unique_values = {}

for i = 1, 100 do
  local random_value = math.random(10)
  unique_values[random_value] = true
end

for k,v in pairs(unique_values) do print(k) end
*