aboutsummaryrefslogtreecommitdiff
path: root/compat53/file_mt.lua
diff options
context:
space:
mode:
authorHisham Muhammad <hisham@gobolinux.org>2024-08-29 17:16:49 -0300
committerGitHub <noreply@github.com>2024-08-29 17:16:49 -0300
commit7a82c38437075cb2beb2fe7c6453aa91e019d6b7 (patch)
tree4b77c7e02eb1e6e5f2b875f7a5947b4fdf23c0f5 /compat53/file_mt.lua
parent1c679a282bf1255cddfbb6b3e8c5c72d9ebe57e8 (diff)
downloadlua-compat-5.3-7a82c38437075cb2beb2fe7c6453aa91e019d6b7.tar.gz
lua-compat-5.3-7a82c38437075cb2beb2fe7c6453aa91e019d6b7.tar.bz2
lua-compat-5.3-7a82c38437075cb2beb2fe7c6453aa91e019d6b7.zip
adjust file metatables even in compat53.module mode (#67)
* adjust file metatables even in compat53.module mode * apply tweaks only to LuaJIT; file:write() only to compat=none
Diffstat (limited to 'compat53/file_mt.lua')
-rw-r--r--compat53/file_mt.lua71
1 files changed, 71 insertions, 0 deletions
diff --git a/compat53/file_mt.lua b/compat53/file_mt.lua
new file mode 100644
index 0000000..6433619
--- /dev/null
+++ b/compat53/file_mt.lua
@@ -0,0 +1,71 @@
1local lua_version = _VERSION:sub(-3)
2
3local M = {}
4
5local unpack = lua_version == "5.1" and unpack or table.unpack
6
7local function addasterisk(fmt)
8 if type(fmt) == "string" and fmt:sub(1, 1) ~= "*" then
9 return "*"..fmt
10 else
11 return fmt
12 end
13end
14
15function M.update_file_meta(file_meta, is_luajit52)
16
17 -- make '*' optional for file:read and file:lines
18
19 local file_lines = file_meta.__index.lines
20 file_meta.__index.lines = function(self, ...)
21 local n = select('#', ...)
22 for i = 1, n do
23 local a = select(i, ...)
24 local b = addasterisk(a)
25 -- as an optimization we only allocate a table for the
26 -- modified format arguments when we have a '*' somewhere
27 if a ~= b then
28 local args = { ... }
29 args[i] = b
30 for j = i+1, n do
31 args[j] = addasterisk(args[j])
32 end
33 return file_lines(self, unpack(args, 1, n))
34 end
35 end
36 return file_lines(self, ...)
37 end
38
39 local file_read = file_meta.__index.read
40 file_meta.__index.read = function(self, ...)
41 local n = select('#', ...)
42 for i = 1, n do
43 local a = select(i, ...)
44 local b = addasterisk(a)
45 -- as an optimization we only allocate a table for the
46 -- modified format arguments when we have a '*' somewhere
47 if a ~= b then
48 local args = { ... }
49 args[i] = b
50 for j = i+1, n do
51 args[j] = addasterisk(args[j])
52 end
53 return file_read(self, unpack(args, 1, n))
54 end
55 end
56 return file_read(self, ...)
57 end
58
59 if not is_luajit52 then
60 local file_write = file_meta.__index.write
61 file_meta.__index.write = function(self, ...)
62 local ret, err = file_write(self, ...)
63 if ret then
64 return self
65 end
66 return ret, err
67 end
68 end
69end
70
71return M