Search code examples
lualua-table

Trying to build a table of unique values in LUA


I am trying to build a table and add to it at the end each time I get a returned value that is not already in the table. So basically what I have so far is not working at all. I'm new to LUA but not to programming in general.

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

Then later I'm trying to use another function to print the contents of the table:

        local x = 0

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

Any help would be much appreciated


Solution

  • Just store a value in the table using your unique value as a key. That way you don't have to check wether a value already exists. You simply overwrite any existing keys if you have it a second time.

    Simple example that stores unique values from 100 random values.

    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