3

我为我的《孤岛危机》服务器模组编写了一个“惩罚箱”(惩罚违反规则的玩家),但由于某种原因,我不断收到此错误:

[警告] [Lua 错误] scripts/functions.lua:340: 尝试对全局 'tme' 执行算术运算(一个 nil 值)

但问题是,tme实际上是一个介于 0 和 15 之间的数值。下面的代码基本上设置了“惩罚框”并检查它是否对玩家仍然有效。如您所见,tme实际上是一个值(如果不是,则代码根本不会运行)。我在这里做错了吗?

由于这是一种特定情况,我在互联网上找不到那么多。tme引用自time,通过聊天命令转发给函数,绝对是一个数字。

另外,有没有更简单的方法可以做到这一点?

代码:

function XPunishPlayer(Name, time, reason)
    if (time > 5) then
        System.LogAlways("[SYSTEM] Punished by administrator: "..Name:GetName().."");
    end
    if (not Msg) then
        local tme = math.floor(time*60);
        Msg = true;
        XMessageChatToPlayer(Name, "[!punish] You were punished for "..time.." minutes:    "..reason.."");
        g_gameRules.game:RenamePlayer(Name.id, "[PUNISH]"..Name:GetName().."");
        XMessageChatToPlayer(Name, "[!punish] You can use !pm to dispute this punishment.");
        g_gameRules:KillPlayer(Name);
    end
    Script.SetTimer( 1000,function()
        local tme = tme+1;
        XPunishPlayer(Name, time, reason);
        Name.actor:SetNanoSuitEnergy(0);
        local punish = math.floor(timeleft-1);
        g_gameRules.onClient:ClStepWorking(g_gameRules.game:GetChannelId(Name.id), tme);
        if (tme == math.floor(time*60)) then
            g_gameRules.onClient:ClStepWorking(g_gameRules.game:GetChannelId(Name.id), false);
            XMessageChatToPlayer(Name, "[!punish] Released from the punishbox.");
            XMessageInfoToAll("Unpunished "..Name:GetName()..", was punished for "..time.."     minutes: "..reason.." (Server Administration)");
            return;
        end
    end);
end
4

1 回答 1

2

Yourtme是在 if 块中定义的,在 Lua 中,每个块都会创建自己的闭包,因此 的值tme是该块的本地值。

您可以通过简单地删除local关键字来使其成为全局变量(这通常不是一个好主意),或者在块之前定义它,如下所示:

function XPunishPlayer(Name, time, reason)
    if (time > 5) then
        System.LogAlways("[SYSTEM] Punished by administrator: "..Name:GetName().."");
    end
    local tme;
    if (not Msg) then
        tme = math.floor(time*60);
        [...]
    end
    Script.SetTimer( 1000,function()
        tme = tme-1;
        [...]
    end);
end

我也很确定local tme你里面的第二个SetTimer会让你再次头疼......

于 2013-05-28T09:23:00.113 回答