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
相关推荐
Rhys..7 分钟前
Python&Flask 使用 DBUtils 创建通用连接池
开发语言·python·mysql
土了个豆子的18 分钟前
04.事件中心模块
开发语言·前端·visualstudio·单例模式·c#
@菜菜_达44 分钟前
Lodash方法总结
开发语言·前端·javascript
GISer_Jing1 小时前
低代码拖拽实现与bpmn-js详解
开发语言·javascript·低代码
@areok@1 小时前
C++mat传入C#OpencvCSharp的mat
开发语言·c++·opencv·c#
小王C语言1 小时前
【C++进阶】---- map和set的使用
开发语言·c++
Elnaij2 小时前
从C++开始的编程生活(8)——内部类、匿名对象、对象拷贝时的编译器优化和内存管理
开发语言·c++
yb0os12 小时前
RPC实战和核心原理学习(一)----基础
java·开发语言·网络·数据结构·学习·计算机·rpc
liuyao_xianhui2 小时前
内存管理(C/C++)
java·开发语言·c++
饭碗的彼岸one3 小时前
C++设计模式之单例模式
c语言·开发语言·c++·单例模式·设计模式·饿汉模式·懒汉模式