9

Lua 5.4 新特性概览

 3 years ago
source link: https://blog.csdn.net/tkokof1/article/details/107205357
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Lua 5.4 新特性概览

本文简单介绍了一些 Lua 5.4 的新特性

Lua 5.4 正式发布了,很多朋友应该会比较好奇 Lua 5.4 与之前版本的区别,本文就此简单介绍一些 Lua 5.4 的新特性.

完整的 Lua 5.4 变更列表可以在这里找到,本文我们仅简单概览下其中主要的几点变化:

之前 Lua 采用的是 分步 GC 算法来进行垃圾回收, Lua 5.4 加入了 分代 GC 算法,值得注意的一点是, Lua 5.4 仍然支持 分步 GC 算法(并且目前 分步 GC 算法仍然是默认的 GC 算法),我们可以通过调用 collectgarbage 来切换当前使用的 GC 算法:

-- convert to generational gc
collectgarbage("generational")
-- convert to incremental gc
collectgarbage("incremental")

之前 collectgarbage 方法支持的两个设置 “setpause” 和 “setstepmul”,在 Lua 5.4 中已经不再支持,目前我们需要借助 “incremental” 来完成相关变量的设置:

collectgarbage("incremental", pause, stepmul, stepsize)

to-be-closed (局部)变量

Lua 5.4 引入了 to-be-closed (局部)变量,机制上可类比 C# 中的 using 语句,实现了类似于 Dispose 的编程模式,只是 C# 中的 Dispose 编程模式通过 Dispose 方法来进行资源的释放,而 Lua 5.4 中的 to-be-closed (局部)变量 则是使用 __close 元方法.

下面是一段示例代码,其中 tbcv 元表的 __close 元方法会在 tbcv 离开作用域的时候被调用:

local tbcmt = { 
    __close = function() 
        print("close to-be-closed var")
    end
}

local function create_tbcv()
    local tbcv = {}
    setmetatable(tbcv, tbcmt)
    return tbcv
end
    
do
    local tbcv <close> = create_tbcv()
end

const (局部)变量

const (局部)变量只能在初始化时赋值,之后对该变量的赋值操作都会被认为是不合法的:

local cv <const> = {}
cv.name = "name" 
-- error: attempt to assign to const variable
cv = {}

math.random 的重新实现

之前 Lua 中的 math.random 是基于 C 语言库函数 rand() 来实现的, 这给跨平台开发带来了一些问题,因为不同平台的 C 语言运行时 对 rand() 的实现并不相同,所以会造成 rand() 返回结果不一致的问题(在各个平台间), Lua 5.4 基于 xoshiro256** 重新实现了 math.random, 继而解决了该问题.

Lua 5.4 新添加了一个警告系统,我们可以通过 warn 函数来触发一个警告:

warn("this is a warn")

但是在 Lua 5.4 的 default 实现中,警告系统是默认关闭的,想要开启的话,需要在 C 语言侧调用 lua_warning 来进行开启:

lua_warning(L, "@on", 0);

当然,我们也可以通过调用 lua_setwarnf 来替换 Lua 5.4 的 default 实现:

void lua_setwarnf (lua_State *L, lua_WarnFunction f, void *ud);

undef ?

Lua 5.4 初期还支持 undef 关键字,用以解决不能给 table 元素进行 nil 赋值的问题(有兴趣的朋友可以自行搜索相关细节),该特性引起了不少争论,后面 Lua 5.4 去除了对该特性的支持.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK