lua寫入一個不確定是否存在檔案的方法
阿新 • • 發佈:2018-12-24
-- file_path 格式:"./servers/login/a.lua"
-- mode 格式:w / a / 其他
-- data :需要儲存的資料
-- check_file_path :是否格式檢查
使用時,不確定servers資料夾是否存在,login資料夾是否存在,程式碼會判斷路徑是否存在,不存在就建立資料夾
--字串分割函式 --傳入字串和分隔符,返回分割後的table function split_str_other(str, delimiter) if str==nil or str=='' or delimiter==nil then return nil end local t = {} for match in (str..delimiter):gmatch("(.-)"..delimiter) do table.insert(t, match) end return t end function write_data(file_path,mode,data,check_file_path) --#TODO做寫快取 -- 判斷路徑中資料夾是否存在,不存在就建立。耗時2ms,不建議大量使用,如果不需要檢查,直接寫入使用時間不超過1ms if check_file_path then local ts = string.reverse(file_path) local i = string.find(ts, "/") local m = string.len(ts) - i local file_catalog = string.sub(file_path, 3, m) local file_catalog_tab = split_str_other(file_catalog,"/") local detection = "." if file_catalog_tab then for _,v in pairs(file_catalog_tab) do detection = detection .. "/" .. v if not os.execute("cd "..detection) then os.execute("mkdir "..detection) end end end end local file = io.open(file_path,mode) assert(file) file:write(data) file:close() end