How to check if a table reference is nil

There is a major issue with luau where you can’t check if a table is nil by its reference.

See below:

Local inventory = {{name = “axe”, cool = “yes”}}
Local item = inventory[1]

Inventory[1] = nil

print(inventory[1])  —>  nil
print(item)  —>  {name = “axe”, cool = “yes”}

As you can see the reference “item” shows the value before the actual table became nil.

Is there any way to check if a table is nil just by its reference?

What do you mean “check if a table is nil by its reference”???
A table becomes nil if it has zero non-nil indexes or keys.

wrong, tables do not become nil.
they simply become an empty table.

print(not not inventory[1])
This will print true of it’s nil, and false else.

1 Like

Actually it’s because dictionaries / hashmaps don’t use number indexs, so Inventory[1] isn’t a index, do Inventory["YOURVALUE"] = nil instead.

When you declare a variable as a table’s index, that variable is stored (cached) even after said index no longer exists in the table.
To set it to nil, simply set said variable to nil.

local table = {
  ["item"] = "axe",
  ["rarity"] = "common"
}

local rarity = table["rarity"]
print(rarity) -- "common"
print(table["rarity"]) -- "common"

table["rarity"] = nil
print(rarity) -- "common", because it's cached
print(table["rarity"]) -- nil, because we removed it

rarity = nil
print(rarity) -- nil, since we set the variable to nil
2 Likes

Actually, tables are pass by reference and not pass by value. The way it works is intended. You need to erase all references by pointing them all at nil. Treat them as pointers and you will be fine.

Hi, how do i copy a table without referencing the original, so that the copy is indepentent?

That’s probably a question that should be in a separate post, but you need to copy everything in the table to a new table:

local deep_copy function deep_copy(tab)
    local copy = {}
    for k, v in tab do
        if type(v) == "table" then
            copy[k] = deep_copy(v)
        else
            copy[k] = v
        end
    end
    return copy
end


local table1 = {1, 2, 3, 4, 5}
local table2 = deep_copy(table1)

Why in the world is that not a table function like table.deepcopy()?
Anyways, ill try that piece of code. Thanks alot!

1 Like