file.lua 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. -- primitives for saving to file and loading from file
  2. function file_exists(filename)
  3. local infile = App.open_for_reading(filename)
  4. if infile then
  5. infile:close()
  6. return true
  7. else
  8. return false
  9. end
  10. end
  11. function load_from_disk(State)
  12. local infile = App.open_for_reading(State.filename)
  13. State.lines = load_from_file(infile)
  14. if infile then infile:close() end
  15. end
  16. function load_from_file(infile)
  17. local result = {}
  18. if infile then
  19. local infile_next_line = infile:lines() -- works with both Lua files and LÖVE Files (https://www.love2d.org/wiki/File)
  20. while true do
  21. local line = infile_next_line()
  22. if line == nil then break end
  23. table.insert(result, {data=line})
  24. end
  25. end
  26. if #result == 0 then
  27. table.insert(result, {data=''})
  28. end
  29. return result
  30. end
  31. function save_to_disk(State)
  32. local outfile = App.open_for_writing(State.filename)
  33. if not outfile then
  34. error('failed to write to "'..State.filename..'"')
  35. end
  36. for _,line in ipairs(State.lines) do
  37. outfile:write(line.data)
  38. outfile:write('\n')
  39. end
  40. outfile:close()
  41. end
  42. -- for tests
  43. function load_array(a)
  44. local result = {}
  45. local next_line = ipairs(a)
  46. local i,line = 0, ''
  47. while true do
  48. i,line = next_line(a, i)
  49. if i == nil then break end
  50. table.insert(result, {data=line})
  51. end
  52. if #result == 0 then
  53. table.insert(result, {data=''})
  54. end
  55. return result
  56. end
  57. function is_absolute_path(path)
  58. local os_path_separator = package.config:sub(1,1)
  59. if os_path_separator == '/' then
  60. -- POSIX systems permit backslashes in filenames
  61. return path:sub(1,1) == '/'
  62. elseif os_path_separator == '\\' then
  63. if path:sub(2,2) == ':' then return true end -- DOS drive letter followed by volume separator
  64. local f = path:sub(1,1)
  65. return f == '/' or f == '\\'
  66. else
  67. error('What OS is this? LÖVE reports that the path separator is "'..os_path_separator..'"')
  68. end
  69. end
  70. function is_relative_path(path)
  71. return not is_absolute_path(path)
  72. end