我试图用字典制作一个战斗系统,但有一个错误使整个系统停止。这是脚本
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
错误显示在标题中所以是
看起来你是在尝试创建一个系统来检查是否有一个动作映射到每个玩家。但是问题来自于初始检查键是否存在于嵌套表中。
if not Dictionary[action][player] then
从左到右阅读代码,Dictionary[action]
可能不存在,因此计算结果为nil
,然后您尝试索引nil[player]
并抛出错误。你的每一个功能都有这个问题。
因此,您需要首先仔细检查Dictionary[action]
是否存在,或者您需要确保它总是解析为一个空表。
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