diff --git a/file.lua b/file.lua index 4db2ba0..9c093c8 100644 --- a/file.lua +++ b/file.lua @@ -1,6 +1,6 @@ local dir_delim = ... -- Localize globals -local io, minetest, modlib, string = io, minetest, modlib, string +local assert, io, minetest, modlib, string, pcall = assert, io, minetest, modlib, string, pcall -- Set environment local _ENV = {} @@ -24,6 +24,20 @@ end -- concat_path is set by init.lua to avoid code duplication +-- Lua 5.4 has `` for this, but we're restricted to 5.1, +-- so we need to roll our own `try f = io.open(...); return func(f) finally f:close() end`. +function with_open(filename, mode, func --[[function(file), called with `file = io.open(filename, mode)`]]) + local file = assert(io.open(filename, mode or "r")) + -- Throw away the stacktrace. The alternative would be to use `xpcall` + -- to bake the stack trace into the error string using `debug.traceback`. + -- Lua will have prepended `::` already however. + return (function(status, ...) + file:close() + assert(status, ...) + return ... + end)(pcall(func, file)) +end + function read(filename) local file, err = io.open(filename, "r") if file == nil then return nil, err end