方法有效时方法无效

时间:2013-08-11 10:46:41

标签: function lua

我刚刚开始使用名为InfinityX的新版Crysis Wars服务器端修改版。为了更好的管理,我把函数放在表中,因为它看起来更整洁,我可以将函数组合在一起(比如Core.PlayerHandle:GetIp(播放器)),但是我遇到了一个问题。 问题是指定的方法来获取玩家'当方法实际上完全有效时,名称player:GetName()被视为无效方法。

我想知道是否使用以下结构导致问题,如果是,如何解决它。这是我第一次将这个结构用于函数,但它已经证明比我使用的旧方法更容易。

代码:

Event = 
{
    PlayerConnect = function(player)
        Msg.All:CenteredConsole("$4Event$8 (Connect)$9: $3"..player:GetName().." on channel "..player.actor:GetChannel());
        System.LogAlways(Default.Tag.."Incoming Connect on Channel "..player.actor:GetChannel());
        Event:Log("Connect", player);
    end;
};

当我绕过该功能并将代码直接放在需要的地方时,以下代码有效:

Msg.All:CenteredConsole("$4Event$8 (Connect)$9: $3"..player:GetName().." on channel "..player.actor:GetChannel());

System.LogAlways(Default.Tag.."Incoming Connect on Channel "..player.actor:GetChannel());

错误:

[警告] [Lua错误] infinityx / main / core.events.lua:23:尝试调用方法' GetName' (零值)

  

PlayerConnect,(infinityx / main / core.events.lua:23)   ConnectScript,(infinityx / main / core.main.lua:52)   OnClientEnteredGame,(scripts / gamerules / instantaction.lua:511)   (null)(scripts / gamerules / teaminstantaction.lua:520)

任何澄清将不胜感激。 谢谢:))

2 个答案:

答案 0 :(得分:2)

好吧,因为PlayerConnect在表Event中,并且你用“:”调用,所以在函数中添加self作为第一个arg,如:

PlayerConnect = function(self, player)

答案 1 :(得分:0)

显然,第一个代码块中的player与第二个代码块中的player不同。问题必须是Event.PlayerConnect的调用者没有传递相同的值。

要测试您的Event.PlayerConnect功能是否有效,请在与第二段代码相同的位置尝试此操作:

Event.PlayerConnect(player)

这应该像你期望的那样工作。

因此,问题归结为如何在没有第二个代码块的情况下调用Event.PlayerConnect。我不熟悉那个游戏引擎所以我不知道它是如何完成的。也许查看文档和/或调试该区域会有所帮助。如果你print(player)或在两种情况下调用等效的日志函数,你会发现它们是不同的。如果无法在调试器中运行,仍可以使用print(debug.traceback("Accessing player, who's value is: "..player))获得堆栈跟踪。如果在这两种情况下确实存在某种基于表的player对象,您可以尝试比较它们的字段以查看它们的不同之处。您可能需要编写一个简单的转储函数来帮助解决这个问题。

相关问题