在Lua中,变量意外地为零

时间:2013-05-28 09:10:10

标签: loops lua

我编写了一个' punishbox' (为惩罚玩家破坏规则)我的Crysis Wars服务器mod但由于某种原因我不断收到此错误:

  

[警告] [Lua错误] scripts / functions.lua:340:尝试对全局' t#进行算术运算。 (零值)

但问题是,tme实际上是0到15之间的数字值。以下代码基本上设置了' punishbox'并检查它是否仍然对玩家有效。如您所见,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

1 个答案:

答案 0 :(得分:2)

您的tme在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会给你带来另一个头痛......