I am pretty new to lua so please excuse me if this question is too basic. I was wondering if there is a good way to check if a value is not in a lua table. Something like:
if 5 ~= t[1] or 5 ~= t[2] or 5 ~= t[3] ... then end
but less stupid.
This
for i,v in ipairs(t) do
if 5 ~= v then
end
end
does not really work because I want to check if it does not show up anywhere in the table rather than if it equals to any given value.
Probably the only somewhat viable solution I could think of so far would be something like
check = 0
for i,v in ipairs(t) do
if 5 == v then
check = 1
end
end
if check == 0 then end
but that still looks kind of cumbersome...
Thanks so much!
If you need to check whether an item exists in array, you better keep a hash map to that array. This is obviously ineffective to go through the whole (or part of the) array for each check. I'll suggest you to create the mapping and only after, do your checks. Example:
local function array_map(array)
local map = {}
for _, item in ipairs(array) do
map[item] = true
end
return map
end
local array = {1,2,3,4,5,6,7}
local arr_map = array_map(array)
if arr_map[1] then
print("The array has item 1")
end
if not arr_map[10] then
print("Item 10 is not part of the array")
end
This is how you get your tests in constant time of ϑ(1)
+ n
once for the map build.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加