I'm new to Lua and I have question regarding to memory management in Lua.
Question 1) When calling function using io.popen(), I saw many Lua programmers wrote a close statement after using popen() function. I wonder what is the reason for that? For example, to demonstrate look at this code:
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)
I heard Lua can manage memory itself. So do I really need to write handle:close like above? What will happen to memory if I just ignore the handle:close() statement and just write it like this?
handle = io.popen("ls -a")
handle = io.popen("date")
output = handle:read("*all")
Question 2) From the code in question 1, in term of memory usage, can we write the handle:close() statement at the end with only one line instead of two like this ?:
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)
You can see that I didn't close this from the first statement when I use io.popen but I close it at the end, will this make the program slow because I close it only with one close statement at the end?
file:close()is not about memory management. You should close an opened file handle as fast as possible because it is a very limited OS resource. You can't have a lot of opened files simultaneously. - Egor Skriptunoffio.popenis a file handler method ? I meanio.popennotio.open- Kalib Zenio.popencreates a pipe and gives you a handle to that pipe. This is a file-like handle. - Egor Skriptunoff