summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRoberto Ierusalimschy <roberto@inf.puc-rio.br>2018-10-23 13:57:25 -0300
committerRoberto Ierusalimschy <roberto@inf.puc-rio.br>2018-10-23 13:57:25 -0300
commit0a9aca56caa925c42aaa683b43560357ab736ea4 (patch)
treefccde4e8cf00c6b7e3563ef3f75c3a28a3f13c64
parentea1322ef5438aa38f16fa00d3ab377811bba5a76 (diff)
downloadlua-github-0a9aca56caa925c42aaa683b43560357ab736ea4.tar.gz
Added a '__close' metamethod to file handles
-rw-r--r--liolib.c1
-rw-r--r--testes/files.lua57
2 files changed, 36 insertions, 22 deletions
diff --git a/liolib.c b/liolib.c
index 21305b8c..3dc509bd 100644
--- a/liolib.c
+++ b/liolib.c
@@ -743,6 +743,7 @@ static const luaL_Reg flib[] = {
{"setvbuf", f_setvbuf},
{"write", f_write},
{"__gc", f_gc},
+ {"__close", f_gc},
{"__tostring", f_tostring},
{NULL, NULL}
};
diff --git a/testes/files.lua b/testes/files.lua
index c3e42235..9aae5913 100644
--- a/testes/files.lua
+++ b/testes/files.lua
@@ -120,31 +120,45 @@ io.output(io.open(otherfile, "ab"))
assert(io.write("\n\n\t\t ", 3450, "\n"));
io.close()
--- test writing/reading numbers
-f = assert(io.open(file, "w"))
-f:write(maxint, '\n')
-f:write(string.format("0X%x\n", maxint))
-f:write("0xABCp-3", '\n')
-f:write(0, '\n')
-f:write(-maxint, '\n')
-f:write(string.format("0x%X\n", -maxint))
-f:write("-0xABCp-3", '\n')
-assert(f:close())
-f = assert(io.open(file, "r"))
-assert(f:read("n") == maxint)
-assert(f:read("n") == maxint)
-assert(f:read("n") == 0xABCp-3)
-assert(f:read("n") == 0)
-assert(f:read("*n") == -maxint) -- test old format (with '*')
-assert(f:read("n") == -maxint)
-assert(f:read("*n") == -0xABCp-3) -- test old format (with '*')
-assert(f:close())
+
+do
+ -- closing file by scope
+ local F = nil
+ do
+ local scoped f = assert(io.open(file, "w"))
+ F = f
+ end
+ assert(tostring(F) == "file (closed)")
+end
+assert(os.remove(file))
+
+
+do
+ -- test writing/reading numbers
+ local scoped f = assert(io.open(file, "w"))
+ f:write(maxint, '\n')
+ f:write(string.format("0X%x\n", maxint))
+ f:write("0xABCp-3", '\n')
+ f:write(0, '\n')
+ f:write(-maxint, '\n')
+ f:write(string.format("0x%X\n", -maxint))
+ f:write("-0xABCp-3", '\n')
+ assert(f:close())
+ f = assert(io.open(file, "r"))
+ assert(f:read("n") == maxint)
+ assert(f:read("n") == maxint)
+ assert(f:read("n") == 0xABCp-3)
+ assert(f:read("n") == 0)
+ assert(f:read("*n") == -maxint) -- test old format (with '*')
+ assert(f:read("n") == -maxint)
+ assert(f:read("*n") == -0xABCp-3) -- test old format (with '*')
+end
assert(os.remove(file))
-- testing multiple arguments to io.read
do
- local f = assert(io.open(file, "w"))
+ local scoped f = assert(io.open(file, "w"))
f:write[[
a line
another line
@@ -171,9 +185,8 @@ three
-- second item failing
l1, n1, n2, dummy = f:read("l", "n", "n", "l")
assert(l1 == "a line" and n1 == nil)
- assert(f:close())
- assert(os.remove(file))
end
+assert(os.remove(file))