In my table, I got a few Fruits that are already part of the table. Now I want to add another Fruit to the table, I would need to check if that Fruit Exist in the table or not. If the Fruit does not Exist in the table then I would add it in.
In my script, It’s checking for all the Fruits, but sense 3 of the items do not equal the ItemName its adding Orange in 3 times. How do I Make it add only once?
local ItemName = "Orange"
Table = {"Apple","Pear","Bannana"}
for i,v in pairs(Table) do
if v.Name ~= ItemName then
table.insert(Table,ItemName)
end
end
local ItemName = "Orange"
Table = {"Apple","Pear","Bannana"}
local function exists(value)
for i,v in pairs(Table)do
if v == value then return v end
end
end
local function addElement(name)
if not exists(name) then
table.insert(Table,name)
print("adding")
else
warn(name .. " exists in table")
end
end
addElement("Strawberry")
for i,v in pairs(Table)do
print(i,v)
end
Too much work just for verifying a value in an array.
local item = "Pear"
local t = {"Apple","Pear","Banana"}
local index = table.find(t, item)
if index then print("Item exists")
return t[index]
end
-- and to shorten the other one
if not table.find(t, item) then t[#t+1] = item end
@ffancyaxax12 Your code is almost correct:
local ItemName = "Orange"
Table = {"Apple","Pear","Bannana"}
for _,v in ipairs(Table) do
if v ~= ItemName then -- the v here is the corresponding value for the associated index that the placeholder variable '_' will hold on each iteration, it's not an object that has a 'Name' property or 'Name' element either.
table.insert(Table, ItemName)
end
end
In your code, just removing the Name part from v.Name and just changing it to v should seal the deal, ipairs is just canonical for arrays.