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
相关推荐
专注VB编程开发20年1 小时前
javascript的类,ES6模块写法在VSCODE中智能提示
开发语言·javascript·vscode
黄雪超8 小时前
JVM——函数式语法糖:如何使用Function、Stream来编写函数式程序?
java·开发语言·jvm
ThetaarSofVenice8 小时前
对象的finalization机制Test
java·开发语言·jvm
思则变8 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
lijingguang9 小时前
在C#中根据URL下载文件并保存到本地,可以使用以下方法(推荐使用现代异步方式)
开发语言·c#
¥-oriented9 小时前
【C#中路径相关的概念】
开发语言·c#
CoderCodingNo9 小时前
【GESP】C++四级考试大纲知识点梳理, (7) 排序算法基本概念
开发语言·c++·排序算法
恋猫de小郭10 小时前
Meta 宣布加入 Kotlin 基金会,将为 Kotlin 和 Android 生态提供全新支持
android·开发语言·ios·kotlin
JosieBook10 小时前
【Java编程动手学】使用IDEA创建第一个HelloJava程序
java·开发语言·intellij-idea
Thomas_YXQ10 小时前
Unity3D DOTS场景流式加载技术
java·开发语言·unity