gpt4 book ai didi

Lua 最佳实践关闭变量与 popen()

转载 作者:行者123 更新时间:2023-12-02 19:08:41 26 4
gpt4 key购买 nike

我是 Lua 的新手,我对 Lua 中的内存管理有疑问。

问题1)当使用io.popen()调用函数时,我看到很多Lua程序员在使用popen()函数后写了一个close语句。我想知道这是什么原因?例如,要演示请看这段代码:

handle = io.popen("ls -a")
output = handle:read("*all")
handle:close()
print(output)

handle = io.popen("date")
output = handle:read("*all")
handle:close()
print(output)

听说Lua可以自己管理内存。那么我真的需要像上面那样写 handle:close 吗?如果我忽略 handle:close() 语句并像这样写它,内存会发生什么情况?

handle = io.popen("ls -a")
handle = io.popen("date")
output = handle:read("*all")

问题2)从问题1的代码来看,在内存占用方面,是否可以把handle:close()语句写在最后一行,只写一行而不是像这样的两个?:

handle = io.popen("ls -a")
output = handle:read("*all")
-- handle:close() -- dont close it yet do at the end
print(output)
handle = io.popen("date") -- this use the same variable `handle` previously
output = handle:read("*all")
handle:close() -- only one statement to close all above
print(output)

你可以看到当我使用 io.popen 时我没有从第一条语句中关闭它但是我在最后关闭它,这会使程序变慢因为我只关闭它最后一个结束语?

最佳答案

Lua 会在垃圾收集器开始收集它时自动关闭文件句柄。

Lua Manual 5.4: file:close

Closes file. Note that files are automatically closed when their handles are garbage collected, but that takes an unpredictable amount of time to happen.

但是,最好的做法是在处理完句柄后立即自行关闭句柄,这是因为 GC 将花费未知的时间来完成它。

这不是内存问题,而是打开文件句柄的资源更为有限,例如 Windows 机器上的 512,一个用于运行其上所有应用程序的小池。


至于第二个问题,当您重新分配一个变量AND时,没有其他剩余的对先前值的引用,该值最终将被 GC 收集。

关于Lua 最佳实践关闭变量与 popen(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64681420/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com