【问题标题】:Setting __index of current environment in Roblox在 Roblox 中设置当前环境的 __index
【发布时间】:2015-09-19 07:40:42
【问题描述】:

在 Roblox Studio 中,我有一个 ModuleScript 对象,它实现了一个类似于 Programming In Lua 第一版第 16 章中所示的类,如下所示:

local h4x0r = { }

local function setCurrentEnvironment( t, env )
    if ( not getmetatable( t ) ) then 
        setmetatable( t, { __index = getfenv( 0 ) } )
    end

    setfenv( 0, t )
end

do
    setCurrentEnvironment( h4x0r );

    do
        h4x0r.Account = { };
        setCurrentEnvironment( h4x0r.Account );
        __index = h4x0r.Account;

        function withdraw( self, v )
            self.balance = self.balance - v;
            return self.balance;
        end

        function deposit( self, v )
            self.balance = self.balance + v;
            return self.balance;
        end

        function new( )
            return setmetatable( { balance = 0 }, h4x0r.Account )
        end

        setCurrentEnvironment( h4x0r );
    end
end

return h4x0r

然后我尝试使用以下脚本访问 Account 类,假设第二个 do-end 块的所有成员都将分配给 h4x0r.Account:

h4x0r = require( game.Workspace.h4x0r );
Account = h4x0r.Account;

account = Account.new( );
print( account:withdraw( 100 ) );

上面的脚本失败,错误为Workspace.Script:5: attempt to call method 'withdraw' (a nil value),所以这一定是我设置h4x0r.Account__index字段的行的问题。

谁能解释一下我哪里出错了?

【问题讨论】:

    标签: lua roblox


    【解决方案1】:

    尝试使用getfenv(2)setfenv(2, t) 而不是getfenv(0)setfenv(0, t)。您实际上想更改 封装函数 的环境,这将是堆栈级别 2。

    0 是一个特殊的参数,它将获取或设置 thread 的环境,在某些情况下用作 默认环境,但这并不影响已经在线程中实例化的各个闭包,因此在这种情况下不起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-11
      • 1970-01-01
      • 2020-08-26
      • 2017-02-01
      • 2017-10-12
      • 1970-01-01
      • 2014-10-12
      • 1970-01-01
      相关资源
      最近更新 更多