Re: checking if a value is not on table ?
Posted: Tue Sep 12, 2017 9:09 am
Ah sorry dude
thxivan wrote: ↑Mon Sep 11, 2017 3:31 pm 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:Note that the function works only with numerically indexed tables with no gaps.Code: Select all
--- 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
Returns the first index in case of duplicates, usage:Code: Select all
local t = {} for i=1, 10 do t[i] = i - 1 end local intable = (table.find(t, 0) ~= nil)
Code: Select all
load()
tableq = {}
for i=0, 10, 1 do
table.insert(tableq, i)
end
a = 99
b = 0
end
update()
for i,v in pairs(tableq) do
if v ~= a then
b = b + 1
end
end
if b ~= #tableq then
b = 0
end
end
function love.draw()
if b == #tableq then
lg.print("a is not in table")
b = 0
end
end
Code: Select all
function love.load()
tableq = {}
for i=0, 10, 1 do
table.insert(tableq, i)
end
a = 9
b = 0
end
function love.update()
for i,v in pairs(tableq) do
if v ~= a then
b = b + 1
end
end
if b ~= #tableq then
b = 0
end
end
function love.draw()
if b == #tableq then
lg.print("a is not in table")
b = 0
else
lg.print("a is in table")
end
end
Code: Select all
--- Counts the number of occurrences of a given value
-- @param t Table
-- @param v Value
-- @return Number of occurrences
-- @return Total number of elements
function table.vcount(t, s)
assert(s ~= nil, "second argument cannot be nil")
local n = 0
local d = 0
for _, v in pairs(t) do
if v == s then
d = d + 1
end
n = n + 1
end
return d, n
end
Code: Select all
local _cache = {}
--- Removes all values
-- @param t Table
function table.clear(t)
for i in pairs(t) do
t[i] = nil
end
end
--- Counts the number of unique elements
--- The number of duplicate elements can be calculated
--- by subtracting the first return value from the second
-- @param t Table
-- @return Number of unique values
-- @return Total number of elements
function table.ucount(t)
-- clear the cache
table.clear(_cache)
local n = 0
local d = 0
for _, v in pairs(t) do
if _cache[v] then
d = d + 1
else
_cache[v] = true
end
n = n + 1
end
return n - d, n
end