Lua: 尝试对全局变量“mapfinishes”执行算术操作(值为“nil”)。

我正在尝试在运行Lua的游戏中设置某些东西,当玩家完成地图时,将触发此特定的本地函数。以下是代码:

local function setDrRanks( ply )
    local name = SQLStr( ply:Nick() )
    local sid = ply:SteamID()

    drsql:query( "SELECT MapFinishes from dr_exp WHERE SteamID = '"..sid.."'", function( q, data )
        local row = data[1]

        if ( row ) then
            mapfinishes = row["Mapfinishes"]
        end

        drsql:query( "REPLACE into dr_exp (`SteamID`, `PlayerName`, `MapFinishes`) VALUES('"..sid.."', "..name..", '"..(mapfinishes+1).."');" );
    end )
end

这个函数是通过Lua函数插入到SQL中的,第一次运行时它成功了,因为玩家完成次数为0。一旦他们达到了1,它就拒绝对mapfinishes值进行简单的+1操作。奇怪的是,当玩家完成次数为0时,这似乎 100 % 工作,并将其放在1上,但一旦他们达到1,它就不再增加。收到的错误是:

attempt to perform arithmetic on global 'mapfinishes' (a nil value)

有人有想法吗?先谢谢了。

点赞
用户183120
用户183120

问题在于表达式 mapfinishes+1mapfinishes 没有被设置时被执行了。这意味着上面的 if 循环没有执行,因为 rownilfalse。请记住,在 Lua 中,零和空字符串都是真值。

另一个可能性是 row["Mapfinishes"] 本身就是 nil,导致 mapfinishes 仍然是 nil

通常最好尽量少或不使用全局变量。如果你只在这个函数内部使用 mapfinishes,把它声明为 local 是合适的。

local row = data[1]

if (row) then
    local mapfinishes = row["Mapfinishes"]
end

drsql:query("REPLACE into dr_exp (`SteamID`, `PlayerName`, `MapFinishes`) VALUES('"..sid.."', "..name..", '"..(mapfinishes+1).."');")
2015-08-14 02:34:29