93 posts
Posted 30 March 2014 - 04:14 PM
First off, sorry for all the questions.
Now, I have a table, and I want my function only to add a value to the table if it isn't already in the table.
So, say I have a function, and I type in the number 1. The number 1 isn't already in the table, so it adds it. Now I type in the number 1 again. It's already in the table, so it doesn't add it to the table at all. Please help!!!
1281 posts
Posted 30 March 2014 - 04:24 PM
There's 2 reasonable approaches to this problem, one would be to loop the table everytime you add a value. The other, which i would use, is to use the table keys to store variables, instead of the values themselves.
local t = {}
t[1] = true
now 1 will always be in the table provided i don't change it to nil or false.
Edited on 30 March 2014 - 02:24 PM
1852 posts
Location
Sweden
Posted 30 March 2014 - 05:00 PM
Too show what CometWolf meant with loops, Here's an example
local t = {}
local function checkTable( t, value )
for i, v in ipairs( t ) do
if v == value then
return true
end
end
return false
end
table.insert( t, "Hello World" )
local bool = checkTable( t, "Hello World!" )
if bool then
print( "The value is already in the table" )
else
print( "The value is not in the table" )
end
I made it a function since I felt it would be easier
Edited on 30 March 2014 - 03:01 PM
93 posts
Posted 30 March 2014 - 08:10 PM
Too show what CometWolf meant with loops, Here's an example
local t = {}
local function checkTable( t, value )
for i, v in ipairs( t ) do
if v == value then
return true
end
end
return false
end
table.insert( t, "Hello World" )
local bool = checkTable( t, "Hello World!" )
if bool then
print( "The value is already in the table" )
else
print( "The value is not in the table" )
end
I made it a function since I felt it would be easier
That's what I thought. I already had created a loop, but I didn't know how to utilize it.
350 posts
Posted 30 March 2014 - 09:21 PM
Too show what CometWolf meant with loops, Here's an example
local t = {}
local function checkTable( t, value )
for i, v in ipairs( t ) do
if v == value then
return true
end
end
return false
end
table.insert( t, "Hello World" )
local bool = checkTable( t, "Hello World!" )
if bool then
print( "The value is already in the table" )
else
print( "The value is not in the table" )
end
I made it a function since I felt it would be easier
That's what I thought. I already had created a loop, but I didn't know how to utilize it.
Just copy that code to yours, and then use checkTable("table","value") whenever you want to test the table values.