*Luaで良く作る関数 ~io編~ [#tfd3313e] -[[printf>#printf]] -[[io.file_exists>#io_file_exists]] -[[io.file_size>#io_file_size]] &aname(printf); **printf [#g9826bb5] #sh(lua){{ -- いわゆるprintf。 function printf(...) local function wrapper(...) io.write(string.format(...)) end local status, result = pcall(wrapper, ...) if not status then error(result, 2) end end }} &aname(io_file_exists); **io.file_exists [#n77e5715] #sh(lua){{ -- 対象のfilenameのファイルが存在するかどうか。 -- 対象のファイルのフルパス。もしくは、カレントからの相対パス。 function io.file_exists(path) local fh = io.open(path, "rb") localif fh then fh:close() end localreturn fh ~= nil if fh then fh:close() end return fh ~= nil end }} &aname(io_file_size); **io.file_size [#r91987fc] #sh(lua){{ -- 対象のfilenameのファイルのファイルサイズを得る -- ファイルが存在しなければ、エラーとなる。 function io.file_size(filename) local fh = assert(io.open(filename, "rb")) local len = assert(fh:seek("end")) fh:close() return len end }}