Bad Scripter
Bad Scripter

Reputation: 3

Attempt to index nil with Instance

I'm trying to make a combat system with a dictionary but there's this one error that stops the whole entire system. This is the script

local Dictionary = require(script.Dictionary)
 
local DictionaryHandler = {}

function DictionaryHandler.find(player, action)
    return Dictionary[action][player]
end

function DictionaryHandler.add(player, action)
    if not Dictionary[action][player] then
        Dictionary[action][player] = true
    end
end

function DictionaryHandler.remove(player, action)
    if Dictionary[action][player] then
        Dictionary[action][player] = nil
    end
end

return DictionaryHandler

The error says it in the title so yeah

Upvotes: 0

Views: 607

Answers (1)

Kylaaa
Kylaaa

Reputation: 7188

It looks like you are trying to make a system for checking whether there is an action mapped to each player. But the problem comes from the initial check whether the key exists in the nested tables.

if not Dictionary[action][player] then

Reading the code from left to right, Dictionary[action] likely doesn't exist, so that evaluates to nil, and then you try to index nil[player] and it throws the error. And each of your functions have this issue.

So you need to double check that Dictionary[action] exists first, or you need to ensure that it always resolves to an empty table.

function DictionaryHandler.find(player, action)
    if not Dictionary[action] then
        return nil
    end
    return Dictionary[action][player]
end

function DictionaryHandler.add(player, action)
    if not Dictionary[action] then
        Dictionary[action] = {}
    end
    if not Dictionary[action][player] then
        Dictionary[action][player] = true
    end
end

function DictionaryHandler.remove(player, action)
    if Dictionary[action] then
        if Dictionary[action][player] then
            Dictionary[action][player] = nil
        end
        if next(Dictionary[action]) == nil then
            Dictionary[action] = nil
        end
    end
end

Upvotes: 2

Related Questions