【问题标题】:attempt to compare a number with nil尝试将数字与 nil 进行比较
【发布时间】:2020-01-23 14:54:09
【问题描述】:

我遇到以下错误:

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是下面RAW数据中的第三个”,第三个是什么?线?还有一个建议,尝试在使用它们之前临时添加一个打印调用以打印比较中使用的变量,它可以在尝试调试此类问题时真正帮助您。

标签: lua


【解决方案1】:

如果我正确理解您的帖子,“第 138 行”指向您发布的代码 sn-p 中的第三行,即:

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)

  -- 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。在这种情况下,如果 targetItemtargetItem.limitnil,您将跳过嵌套的 if 语句。

【讨论】:

  • 由于targetItem.countcount 是第一次相加,唯一直接与数字比较的变量是targetItem.limit,所以它只能是导致错误的那个变量;)
猜你喜欢
  • 1970-01-01
  • 2017-03-06
  • 1970-01-01
  • 1970-01-01
  • 2014-05-22
  • 2017-03-19
  • 2021-10-13
  • 2018-07-31
  • 2016-04-22
相关资源
最近更新 更多