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"
=> nil
7.732
=> nil
{}
=> nil
Therefore 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!)