【问题标题】:Editting Roblox module execute err编辑 Roblox 模块执行错误
【发布时间】:2016-07-26 03:54:21
【问题描述】:

-- 这是 Roblox 自己编写的一些代码:

-- Setup table that we will return to scripts that require the ModuleScript.
    local PlayerStatManager = {}

    -- Table to hold all of the player information for the current session.
    local sessionData = {}

    -- Function the other scripts in our game can call to change a player's stats. This
    -- function is stored in the returned table so external scripts can use it.
    function PlayerStatManager:ChangeStat(player, statName, changeValue)
        sessionData[player][statName] = sessionData[player][statName] + changeValue
    end

    -- Function to add player to the sessionData table.
    local function setupPlayerData(player)
        sessionData[player] = {Money = 0, Experience = 0}
    end

    -- Bind setupPlayerData to PlayerAdded to call it when player joins.
    game.Players.PlayerAdded:connect(setupPlayerData)

    -- Return the PlayerStatManager table to external scripts can access it.
    return PlayerStatManager
--------------------------------------------------------------------------------

-- Require ModuleScript so we can change player stats
local PlayerStatManager = require(game.ServerStorage.PlayerStatManager)

-- After player joins we'll periodically give the player money and experience
game.Players.PlayerAdded:connect(function(player)
    while wait(2) do
        PlayerStatManager:ChangeStat(player, 'Money', 5)
        PlayerStatManager:ChangeStat(player, 'Experience', 1)
    end
end)

当我运行这两个脚本时,它运行完美,在ChangeStat 函数中添加了print(sessionData[player][statName]),但是当我删除模块脚本中的game.Players.PlayerAdded:connect(setupPlayerData) 部分时,它停止工作。我虽然模块脚本在没有被调用的情况下不会执行代码,如果是这种情况,game.Players.PlayerAdded:connect(setupPlayerData) 部分不应该是延迟而不是功能,因为玩家已经添加,因此它不会触发?

【问题讨论】:

  • 您删除了:connect(setupPlayerData) 行,发生了什么?究竟是什么停止了工作?你有没有得到任何错误?否则,我希望对 ChangeStat 的调用会引发错误,因为它们尝试修改的表将不会被正确创建。
  • 那么当新玩家进入时模块将运行而无需调用设置函数?
  • 模块代码(函数外等)在模块加载时运行。这就是它设置回调函数以在其他事件发生时调用的方式。您删除了为 PlayerAdded 事件设置的回调设置,该事件设置了添加到 PlayerAdded 事件的 other 回调需要正常工作的内部数据结构。从本质上讲,您从三步流程中删除了第一步,因此您打破了第二步和第三步。
  • 这是有用的信息,谢谢。

标签: lua roblox


【解决方案1】:

require 执行所需的代码。 如果不是这种情况,您将无法通过require 获取表,因为您的return PlayerStatManager 语句将不会被执行。

因此删除

 -- Bind setupPlayerData to PlayerAdded to call it when player joins.
    game.Players.PlayerAdded:connect(setupPlayerData)

将导致添加的播放器无法正确初始化。这基本上是说:添加新玩家时,请致电setupPlayerDatasetupPlayerData 说:给player 提供一组新的统计数据

当您删除该行时,没有球员有统计数据。如果你没有统计数据,你就无法增加它们的价值......

所以很明显,在您更改代码之前,您并不了解代码做了什么。因此,您无法理解为什么您的更改会导致问题。

如果你改变一个你不了解的系统,你可能会很幸运,但在大多数情况下,你会彻底失败。

【讨论】:

  • 很好的回答,直到不必要的关于不理解代码的问题。
猜你喜欢
  • 1970-01-01
  • 2021-11-16
  • 1970-01-01
  • 2016-05-29
  • 1970-01-01
  • 1970-01-01
  • 2016-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多