NDui

NDui

143k Downloads

可以考虑这样来避免开头的一堆local

YorigamiShion opened this issue · 2 comments

commented
-- init.lua
local _, ns = ...
local function BuildEnv(env, module)
    if module then
        if not env[module] then env[module] = {} end
        setfenv(2, setmetatable(env[module], {__index = function(self, key)
                if key == "_G" then return _G end
                local value = rawget(env, key)
                if value == nil then
                    value = _G[key]
                    rawset(self, key, value)
                end
                return value
            end
        }))
    else
        setfenv(2, setmetatable(env, {__index = function(self, key)
                if key == "_G" then return _G end
                rawset(self, key, _G[key])
                return _G[key]
            end
        }))
    end
end

BuildEnv(ns)
ns._meta = getmetatable(ns)
ns._meta.__call = BuildEnv

ns()

-- 其他文件
select(2, ...)("chat")
-- balabala

这样用过的全局变量就自动缓存了,稍微改一下还能避免拼错引用到空值

commented

效果是什么?这个我看不懂,metatable对我来说是空白区

commented
-- 文件A
local _, ns = ...
ns()  -- 不local的变量会定义在ns里
print('one')  -- ns.print == _G.print
print('two')  -- 调用 ns.print('two')
C_Timer.After(1, print)  -- ns.C_Timer == _G.C_Timer
x = '1'  -- ns.x == '1', _G.x == nil

-- 文件B
local _, ns = ...
ns('chat') -- 变量定义在ns.chat里
print(strfind('123', x)) -- 调用 ns.print(strfind('123', ns.x)),  ns.chat.strfind == _G.strfind
f = CreateFrame('Frame') -- 定义为 ns.chat.f, _G.f == ns.f == nil
local y = 2

-- 文件C
select(2, ...)('chat')  -- 等价于上面的前两行
print(f) -- 调用 ns.print(ns.chat.f)
print(y, chat.y) -- nil, nil

-- 文件D
select(2, ...)('info')
chat.f:SetScript(......)  -- 调用 ns.chat.f:SetScript

大概就是这样了