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

Kal*_*Zen 5 lua

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

问题1)在使用using调用函数时io.popen(),我看到很多Lua程序员在usingpopen()函数后写了一个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)
Run Code Online (Sandbox Code Playgroud)

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

handle = io.popen("ls -a")
handle = io.popen("date")
output = handle:read("*all")
Run Code Online (Sandbox Code Playgroud)

问题2)从 中的代码来看,从内存占用的角度来看,最后的语句question 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)
Run Code Online (Sandbox Code Playgroud)

你可以看到,我在使用时没有从第一个语句中关闭它,io.popen而是在最后关闭它,这会导致程序变慢,因为我只在最后用一个 close 语句关闭它吗?

Nif*_*fim 4

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

Lua手册5.4:文件:关闭

关闭文件。请注意,当文件句柄被垃圾收集时,文件会自动关闭,但这需要花费不可预测的时间。

但是,最好的做法是在使用完句柄后立即关闭句柄,这是因为 GC 需要花费未知的时间来完成此操作。

这不是内存问题,而是打开文件句柄资源更加有限的问题,类似于 Windows 计算机上的 512,是运行在其上的所有应用程序的一个小池。


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