Lua Global环境

Lua的全局变量实际上是用environment这个表来存储所有的全局变量,其优点就是简化了lua的内部实现,而且还能像其他类型的表一样去操作这个全局表。

_G

Lua将environment本身存储在全局变量_G中,其中_G._G = _G。如若感兴趣,可以直接用pairs函数打印当前的全局变量名:

Lua 复制代码
A = {1,2,3}

function testMySelf()
end

for n in pairs(_G) do print(n) end
--[[
assert
dofile
...
testMySelf
utf8
A
package
...
pairs
_G
...
]]--

_G的用法其实和直接赋值全局变量差不多,如下两句性质完全一样的代码所示:

Lua 复制代码
_G["a"] = _G["var1"]
a = var1

getfield/setfield

手动写一个getfield函数,用以通过字符串查找相应的域,比如a.b.c.d的值是多少。实际上是从_G开始循环向域内部遍历:

Lua 复制代码
function getfield (f) 
    local v = _G -- start with the table of globals 
    for w in string.gmatch(f, "([%w_]+)") do
     v = v[w]
    end
    return v
end

A = {["a"] = 1}
print(getfield("A.a")) --1

setfield也是一样的道理,只不过需要判断是否是最后一个".",需要独立处理最后一个域并进行赋值,比如A.a = 1:

Lua 复制代码
function setfield (f, v) 
    local t = _G -- start with the table of globals 
    for w, d in string.gmatch(f, "([%w_]+)(.?)") do
        if d == "." then -- not last field? 
            t[w] = t[w] or {} -- create table if absent 
            t = t[w] -- get the table 
        else -- last field 
            t[w] = v -- do the assignment 
        end
    end
end

setfield("A.a",2)
print(A.a) --2

声明全局变量

如若控制全局变量的声明和访问,则直接控制_G的newindex和index即可,但是需要注意一点的是如果在newindex中明确禁止了全局变量的声明操作,那么任何直接赋值都是有问题的,如以下代码:

Lua 复制代码
setmetatable(_G, { 
    __newindex = function (_, n)
        print("attempt to write to undeclared variable "..n)
   end,
    __index = function (_, n)
        print("attempt to read undeclared variable "..n)
   end,
})
A = {} --attempt to write to undeclared variable A

这时候只能通过rawget/rawset来直接进行访问操作。比如声明一个入口函数,所有全局变量的声明都必须经此函数初始化;判断这个域是否存在,也需要用rawget函数直接访问:

Lua 复制代码
function declare (name, initval) 
 rawset(_G, name, initval or false) 
end

...
if rawget(_G, var) == nil then
-- 'var' is undeclared 
 ... 
end

当然需要注意的是上述处理中初始化全局变量如果是nil赋值则默认赋值为false了。

如若不需要这个默认赋值,希望代码支持类似a = nil的声明,那么也可以维护一个注册表并放入newindex元方法中判断,当然这也是官方文档给的一个解决方案(不过对本人来说觉得有点鸡肋,毕竟类似a = nil的代码是可以避免的):

Lua 复制代码
local declaredNames = {}
function declare (name, initval)
    rawset(_G, name, initval)
    declaredNames[name] = true
end
setmetatable(_G, {
    __newindex = function (t, n, v)
    if not declaredNames[n] then
        error("attempt to write to undeclared var. "..n, 2)
    else
        print("newindex")
        rawset(t, n, v) -- do the actual set 
    end
    end,
    __index = function (_, n)
        if not declaredNames[n] then
            error("attempt to read undeclared var. "..n, 2)
        else
            return nil
        end
    end,
})

declare("A",nil)
A = {} --newindex
相关推荐
笨笨马甲22 分钟前
Qt Quick模块功能及架构
开发语言·qt
夜晚回家36 分钟前
「Java基本语法」代码格式与注释规范
java·开发语言
YYDS31440 分钟前
C++动态规划-01背包
开发语言·c++·动态规划
前端页面仔1 小时前
易语言是什么?易语言能做什么?
开发语言·安全
树叶@1 小时前
Python数据分析7
开发语言·python
wydaicls1 小时前
十一.C++ 类 -- 面向对象思想
开发语言·c++
Biomamba生信基地2 小时前
R语言基础| 下载、安装
开发语言·r语言·生信·医药
姜君竹2 小时前
QT的工程文件.pro文件
开发语言·c++·qt·系统架构
奇树谦2 小时前
使用VTK还是OpenGL集成到qt程序里哪个好?
开发语言·qt
VBA63372 小时前
VBA之Word应用第三章第十节:文档Document对象的方法(三)
开发语言