lua - 尝试将数字与 nil 进行比较
问题描述
我遇到以下错误的问题:
esx_glovebox_sv.lua:138:尝试将数字与 nil 进行比较。
第 138 行是下面 RAW 数据中的第三个
RegisterServerEvent("esx_glovebox:getItem")
AddEventHandler(
"esx_glovebox:getItem",
function(plate, type, item, count, max, owned)
local _source = source
local xPlayer = ESX.GetPlayerFromId(_source)
if type == "item_standard" then
local targetItem = xPlayer.getInventoryItem(item)
if targetItem.limit == -1 or ((targetItem.count + count) <= targetItem.limit) then
TriggerEvent(
"esx_glovebox:getSharedDataStore",
plate,
function(store)
local coffres = (store.get("coffres") or {})
for i = 1, #coffres, 1 do
if coffres[i].name == item then
if (coffres[i].count >= count and count > 0) then
xPlayer.addInventoryItem(item, count)
if (coffres[i].count - count) == 0 then
table.remove(coffres, i)
else
coffres[i].count = coffres[i].count - count
end
break
else
TriggerClientEvent(
"pNotify:SendNotification",
_source,
{
text = _U("invalid_quantity"),
type = "error",
queue = "glovebox",
timeout = 3000,
layout = "bottomCenter"
}
)
end
解决方案
如果我正确理解您的帖子,“第 138 行”指向您发布的代码片段中的第三行,即:
if targetItem.limit == -1 or ((targetItem.count + count) <= targetItem.limit) then
该错误意味着您正在使用的值之一是nil
因此无法与数字进行比较。在您的情况下,这只能是targetItem.limit
.
如果每个都targetItem
应该有一个limit
和count
值,那么问题就出在代码的其他地方。
您可以通过添加额外的检查来简单地检查值的存在,而不是抛出错误:
if type == "item_standard" then
local targetItem = xPlayer.getInventoryItem(item)
-- Make sure that targetItem and targetItem.limit aren't nil.
if targetItem and targetItem.limit then
if targetItem.limit == -1 or ((targetItem.count + count) <= targetItem.limit) then
简短说明:在 Lua 中nil
,布尔值和布尔值都false
表示false
逻辑表达式中的值。任何其他值都将被视为true
。在这种情况下,您将跳过嵌套的 if 语句 iftargetItem
或targetItem.limit
are nil
。
推荐阅读
- spring - 无法为 Spring @Scheduler 编写单元测试
- youtube-livestreaming-api - 使用 api 在 Youtube Live Broadcast 上禁用实时聊天
- python - 提交后如何使Django表单字段为空?
- azure-cosmosdb - Cosmos DB - 5 RU 写入可能吗?
- azure - 无法使用客户端 ID/机密 Azure AD B2C 登录
- c - 用 C 语言优化井字游戏
- jquery - $.ajax 不会触发成功
- python - 多处理和 scipy (dblquad)
- javascript - 按字母顺序排列争论并根据顺序打印一个数字
- go - 如何在运行前通过 gin 合并多个路由器