尝试将数字与 nil 进行比较

我遇到下面的错误:

esx_glovebox_sv.lua:138: 尝试将数字与 nil 进行比较.

第138行是下面的原始数据之三

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
点赞
用户12730491
用户12730491

如果我正确理解了你的帖子,“line 138”指的是你发布的代码片段中的第三行,即:

if targetItem.limit == -1 or ((targetItem.count + count) <= targetItem.limit) then

这个错误意味着,你正在使用的值之一是 nil,因此不能与数字进行比较。在你的情况下,这只能是 targetItem.limit

如果每个 targetItem 都应该有一个 limitcount 值,那么问题就在你的代码的其他地方。

不要抛出错误,可以通过添加其他检查来检查值的存在:

if type == "item_standard" then
  local targetItem = xPlayer.getInventoryItem(item)

  -- 确保 targetItem 和 targetItem.limit 不是 nil。
  if targetItem and targetItem.limit then
    if targetItem.limit == -1 or ((targetItem.count + count) <= targetItem.limit) then

简短的解释:在 Lua 中,nil 和布尔值 false 都代表逻辑表达式中的 false 值。任何其他值都将被视为 true。在这种情况下,如果 targetItemtargetItem.limit 任一者是 nil,则将跳过嵌套的 if 语句。

2020-01-23 15:56:08