Reputation: 967
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
Upvotes: 2
Views: 3087
Reputation: 1
This could work, but one thing you could do (which is an extra step, but works) is that if you're trying to store only unique values, you can create a "table contains" function.
Here's teh gist of what I did:
tablecontains(table2process, valuetosearch)
if next(table2process) == nil then
return false
else
for i = 1, #table2process do
if table2process[i] == value then
return true
end
end
return false
end
end
Explanation:
Code Checks to see if table you're passing is empty. If so, return false
Code then checks every value in the table to ensure the value you're searching for isn't in each element in the table.
2a. If it DOES exist, the function returns true
The for loop exits, and an unconditional return false
is provided (this ensures that if NO value is found in the table, it's safe to be inserted as a unique value).
Usage: Here's how I use it in my code:
if not tablecontains(tabletouse, searchquery) then
table.insert(tabletouse, searchquery)
end
This allows you to only insert what exists within your table beit strings, or other types of values (im using strings!)
Upvotes: 0
Reputation: 28950
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
Upvotes: 6