Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

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

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 :(

2 comments

0

nil is nothing, basically, not there. but idk of any other methods to detect a value that doesn't exist

0

use ipairs, it is slower but stops looping when it encounters a nil.

1 answer

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

2 comments

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.

0

Weird. Nice answer, though.

This discussion is preserved as it was. New answers, comments, and votes are closed.