32. Lua 全局環(huán)境

--[[
-- 全局變量保存在 _G 中
-- 遍歷當(dāng)前的全局變量
for n in pairs (_G) do
    print(n)
end

-- 新增全局變量
huangMP = "huangMP"
for n in pairs (_G) do
    print(n)
end

--]]

--[[
-- 具有動(dòng)態(tài)名字的全局變量
-- value = loadstring( "return " .. varname )
-- value = _G(varname)
-- _G(varname) = value

function getfield(f)
    local v = _G  -- 從全局變量的table開始
    for w in string.gmatch( f , "[%w_]+") do
        v = v[w]
    end
    return v
end

-- a.b.c.d = v  --> local temp = a.b.c; temp.d = v

function setfield( f, v )
    local t = _G  -- 從全局變量的table開始
    for w,d in string.gmatch( f , "([%w_]+)(%.?)" ) do
        if d == "." then  -- 是最后一個(gè)字段嗎
            t[w] = t[w] or {}  -- 如果不存在就創(chuàng)建 table
            t = t[w]  -- 獲取該table
        else
            t[w] = v
        end
    end
end

setfield("t.x.y" , 10)
print(t.x.y)

--]]

setmetatable( _G , {
    __newindex = function(t, n , v )
        local w = debug.getinfo(2,"S").what
        if w~="main" and w~="C" then  -- 是否是主程序 或者 是否是c程序
            error("attempt to write to undeclared vaiable " .. n , 2 )
        end
        rawset(t,n,v)
    end ,
    __index = function( _ , n )
        error("attemp to read undeclared variable " .. n , 2 )
    end
})
-- prinf(a)  -- attemp to read undeclared variable prinf
a = "HK"
print(a)
print( _G["a"])

-- 聲明全局變量 1
function declare( name , initval )
    rawset( _G , name , intival or false )
end

-- 聲明全局變量 2
a = 10 -- 這種方法要在主程序中才有效

-- debug.getinfo(2,"S").what 可查看當(dāng)前是否是主程序塊

function f(a)
    -- b = a
    return a
end

s = f("OK")
print(s)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容