我为我的 Crysis Wars 服务器模组编写了一个“惩罚框”(惩罚违反规则的玩家),但出于某种原因,我不断收到此错误:
[Warning] [Lua Error] scripts/functions.lua:340: attempt to perform arithmetic on global 'tme' (a nil value)
但问题是,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
最佳答案
tme
是在 if block 中定义的,在 Lua 中,每个 block 都创建自己的闭包,因此 tme
的值是该 block 的本地值。
您可以通过简单地删除 local
关键字(这通常不是一个好主意)使其成为全局变量,或者像这样在 block 之前定义它:
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
我也很确定你的 SetTimer
中的第二个 local tme
会让你又头疼......
关于loops - 在 Lua 中,变量意外地为 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16788139/