Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Why can I not check if there is a nil in this table?

Asked by 6 years ago
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 :(

0
nil is nothing, basically, not there. but idk of any other methods to detect a value that doesn't exist Subaqueously 11 — 6y
0
use ipairs, it is slower but stops looping when it encounters a nil. hiimgoodpack 2009 — 6y

1 answer

Log in to vote
1
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
6 years ago

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
  • etc...

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!)

0
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`. User#18718 0 — 6y
0
Weird. Nice answer, though. CootKitty 311 — 6y
Ad

Answer this question