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!!!
3
Adding to table only if it isn't already in the table
Started by nateracecar5, Mar 30 2014 03:14 PM
4 replies to this topic
#1
Posted 30 March 2014 - 03:14 PM
#2
Posted 30 March 2014 - 03: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] = truenow 1 will always be in the table provided i don't change it to nil or false.
Edited by CometWolf, 30 March 2014 - 03:24 PM.
#3
Posted 30 March 2014 - 04: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" ) endI made it a function since I felt it would be easier
Edited by Hellkid98, 30 March 2014 - 04:01 PM.
#4
Posted 30 March 2014 - 07:10 PM
Hellkid98, on 30 March 2014 - 04:00 PM, said:
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" ) endI 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.
#5
Posted 30 March 2014 - 08:21 PM
nateracecar5, on 30 March 2014 - 07:10 PM, said:
Hellkid98, on 30 March 2014 - 04:00 PM, said:
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" ) endI 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.
1 user(s) are reading this topic
0 members, 1 guests, 0 anonymous users