local table = {'hello',nil,'world'}
for i,v in pairs(table) do
print('Currently on: '..i)
end
Output:
Currently on: 1
Currently on: 3
How can I check if there is a nil :(
local table = {'hello',nil,'world'}
for i,v in pairs(table) do
print('Currently on: '..i)
end
Output:
Currently on: 1
Currently on: 3
How can I check if there is a nil :(
Tables are maps from keys to values.
If a table doesn't contain a given key, then we say it maps to nil. In Lua, there isn't a way to distinguish having a nil value from not being in the table.
So, in your case, your table has two key-value mappings:
1 => "hello"3 => "world"It doesn't "contain" nil -- there's an infinite number of keys that the table does not map to anything:
"foo" => nil7.732 => nil{} => nilTherefore it doesn't make sense to ask if a table "contains nil".
Maybe you mean to ask, is there a "hole" in the sequence 1, 2, 3, ..., n?
The easiest way to check is to see if key k is in the table, is k-1 also in the table when k isn't 1?
for key in pairs(t) do
if key ~= 1 and not t[key - 1] then
print("table", t, "is missing key", key - 1)
end
end
(Note that I'm assuming the table t doesn't have any non-integer keys in this example!)
Alternatively you can loop through the different possible integer indices with for i = 1,#mytable do and check if it's nil that way without using pairs.
Weird. Nice answer, though.
This discussion is preserved as it was. New answers, comments, and votes are closed.
2 comments
nil is nothing, basically, not there. but idk of any other methods to detect a value that doesn't exist
use ipairs, it is slower but stops looping when it encounters a nil.