LUA|MTASA 的 attempt to index field '?' (a nil value) 问题

我在我的 MTA 服务器的 lua 脚本中遇到了问题。当我运行代码时,我会得到以下错误:

attempt to index field '?' (a nil value)

这是代码:

addEvent("bank:transfer", true)
addEventHandler("bank:transfer", root, function(id, amount, to, reason)
    if(transferBank(id, amount, to, reason)) then
         triggerClientEvent(client, "bank:transferRecieve", client, true)
    else
         triggerClientEvent(client, "bank:transferRecieve", client, false)
    end
end)

function transferBank(id, amount, to, reason)
    if(id and amount and to and reason) then
        if(BANK_ACCOUNTS[to]) then
            if(BANK_ACCOUNTS[id].balance >= amount) then
                dbExec(connection, "INSERT INTO bank_records (bank_id, record_type, record_from, reason, amount, date) VALUES(?, ?, ?, ?, ?, NOW())", to, 3, id, reason, amount)
                dbExec(connection, "UPDATE bank_accounts SET balance = balance - ? WHERE id=?", amount, id)
                dbExec(connection, "UPDATE bank_accounts SET balance = balance + ? WHERE id=?", amount, to)
                BANK_ACCOUNTS[to].balance = BANK_ACCOUNTS[to].balance + amount
                BANK_ACCOUNTS[id].balance = BANK_ACCOUNTS[id].balance - amount

                return true
            else
                return false, "Le Compte Bancaire spécifié ne contient pas assez d'argent."
            end
        else
            return false, "Le Compte Bancaire spécifié n'existe pas."
        end
    else
        return false, "Argument Invalide."
    end
end

我搜索了几个小时,但我找不到错误来自哪里的原因。

点赞
用户2858170
用户2858170

造成此错误信息的最小示例:

local BANK_ACCOUNTS = {}
BANK_ACCOUNTS[to].balance = 1

在这种情况下,BANK_ACCOUNTS[to]为nil,因此您无法对其进行索引。 由于to也是nil,Lua没有字段名/键放入错误消息中。

BANK_ACCOUNTS["test"].balance = 1

会给你以下错误消息:

attempt to index field 'test' (a nil value)

因此,在某些时候to或id为nil。

因为如果to为空你就不会输入 if BANK_ACCOUNTS[to] then,所以它一定是id。

2018-04-25 11:30:24