love.load()
a = 9
table = {}
for i=0, 10, 1 do
table.insert(table, i)
end
end
love.draw()
for i,v in pairs(table) do
if v ~= a then
--print something
end
end
end
so what i want to do here is to print something out only once if the value is not on table, how do i do it ?
You will have to use one extra variable to keep track of table contents. Otherwise the function will be stateless and you won't be able to tell anything about array other than its current element.
local t = {}
for i = 0, 10 do table.insert(t, i) end
local find = 9
local found = false
for index, value in ipairs(t) do
if value == find then
found = true
break
end
end
if not found then
print("something")
end
If you want to know if a value is inside the table, you might as well return the index.
You should probably check if the search value is non-nil to prevent bugs:
--- Finds the first occurrence in a list
-- @param t Table
-- @param s Search value
-- @param o Starting index (optional)
-- @return Numeric index or nil
function table.find(t, s, o)
o = o or 1
assert(s ~= nil, "second argument cannot be nil")
for i = o, #t do
if t[i] == s then
return i
end
end
end
Note that the function works only with numerically indexed tables with no gaps.
Returns the first index in case of duplicates, usage:
Maybe I'm missing something here, but it seems like the simplest (and most efficient) solution would be to just check if that element is nil before or after the loop
local tab = { a = 1, b = 2, c = 3 }
local key = 'testKey'
local notInTable = tab[key] == nil
if notInTable then
print( 'The key "' .. key .. '" is not present in the table' )
end
-- Loop over table
GitHub | MLib - Math and shape intersections library | Walt - Animation library | Brady - Camera library with parallax scrolling | Vim-love-docs - Help files and syntax coloring for Vim
grump wrote: ↑Tue Sep 12, 2017 4:05 am
davisdude, OP wants to check the table for a value, not for some random key.
We are in lua. Any value will evaluate to true, nil to false.
If you return the first key or nothing at all, you can use it for condition checking as if you'd return a bool. Just multiple occurrences of the same value aren't covered.
Returning the value you provide as parameter isn't helpful. Having access to the index and a condition function at once is.
This should work for string index table as well if you use
What? OP wants to know if a specific value is not in a table. If you want to check for a specific value, you have to iterate over the table. The keys have absolutely no relevance here.