简体   繁体   中英

attempt to compare a number with nil

I'm having issues with the below error:

esx_glovebox_sv.lua:138: attempt to compare number with nil.

Line 138 is third in RAW data below

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

If I understand your post correctly "line 138" points to the third line in your posted code snippet, which would be:

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

The error means, that one of the values you are working with is nil and therefore can't be compared to a number. In your case this can only be targetItem.limit .

If each targetItem should have a limit and count value, the issue is somewhere else in your code.

Instead of throwing an error you can simply check for the existance of the value by adding additional checks:

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

Short explanation: In Lua both nil and the boolean value false represent a false value inside of a logical expression. Any other value will be treated as true . In this case you'll skip the nested if-statement if either targetItem or targetItem.limit are nil .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM