Lua教程(十): 全局变量和非全局的环境

这篇文章主要介绍了Lua教程(十): 全局变量和非全局的环境,本文讲解了老的全局变量环境和Lua5中新的非全局环境相关知识,需要的朋友可以参考下

Lua将其所有的全局变量保存在一个常规的table中,这个table被称为“环境”。它被保存在全局变量_G中。

1. 全局变量声明:

Lua中的全局变量不需要声明就可以使用。尽管很方便,但是一旦出现笔误就会造成难以发现的错误。我们可以通过给_G表加元表的方式来保护全局变量的读取和设置,这样就能降低这种笔误问题的发生几率了。见如下示例代码:

复制代码 代码如下:

--该table用于存储所有已经声明过的全局变量名
local declaredNames = {}
local mt = {
    __newindex = function(table,name,value)
        --先检查新的名字是否已经声明过,如果存在,这直接通过rawset函数设置即可。
        if not declaredNames[name] then
            --再检查本次操作是否是在主程序或者C代码中完成的,如果是,就继续设置,否则报错。
            local w = debug.getinfo(2,"S").what
            if w ~= "main" and w ~= "C" then
                error("attempt to write to undeclared variable " .. name)
            end
            --在实际设置之前,更新一下declaredNames表,下次再设置时就无需检查了。
            declaredNames[name] = true
        end
        print("Setting " .. name .. " to " .. value)
        rawset(table,name,value)
    end,
   
    __index = function(_,name)
        if not declaredNames[name] then
            error("attempt to read undeclared variable " .. name)
        else
            return rawget(_,name)
        end
    end
}   
setmetatable(_G,mt)

a = 11
local kk = aa

--输出结果为:
--[[
Setting a to 11
lua: d:/test.lua:21: attempt to read undeclared variable aa
stack traceback:
        [C]: in function 'error'
        d:/test.lua:21: in function
        d:/test.lua:30: in main chunk
        [C]: ?
--]]

以上就是Lua教程(十): 全局变量和非全局的环境的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » Lua