Table index is nil

I’m trying to make a debounce in this touched by making an index for every character that touches it, but it errors, table index is nil.

script.Parent.Touched:Connect(function(hit)
	local char = hit.Parent:FindFirstChild("Humanoid") 
	if not table.find(db,char) then
		table.insert(db,char)
		print("f")
	end
	if db[char] == nil then
	print(table[1])
	db[char] = false
	for i,v in pairs (mytable) do
		local char = v.Character
		allstats = {}
		table.insert(allstats,char:WaitForChild("Value").Value)
		table.insert(allstats,2,10)
	end
	table.sort(allstats)
	
	print(allstats[1])
	print(allstats[2])
	wait(5)
	db[char] = true
	end
end)
3 Likes

In the case that from the line local char = hit.Parent:FindFirstChild("Humanoid"), char is nil, db[char] == nil evaluates to true and the if block is ran.
In the block,

-- Doing
db[char] = false
-- Is equivalent to doing
db[nil] = false

Which errors since while setting a value, your key cannot be nil.
To fix this throw a simple nil catcher at the top

script.Parent.Touched:Connect(function(hit)
	local char = hit.Parent:FindFirstChild("Humanoid") 
    if not char then return end -- not nil evaluates to true
	if not table.find(db,char) then
		table.insert(db,char)
		print("f")
	end
	if db[char] == nil then
	    print(table[1])
	    db[char] = false
	    for i,v in pairs (mytable) do
		    local char = v.Character
		    allstats = {}
  
   
        table.insert(allstats,char:WaitForChild("Value").Value)
		    table.insert(allstats,2,10)
	    end
	    table.sort(allstats)
	    print(allstats[1])
	    print(allstats[2])
	    wait(5)
	    db[char] = true
	end
end)

Please fix your indentation next time

9 Likes

Thanks! it worked. :smile: :grinning:

Thank you for this. me together with my team encountered the same error. With this solution, i was able to make our jumpscare work without a problem