Advertisement
jfmachine

reformat.lua

Jun 24th, 2023
950
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.24 KB | None | 0 0
  1. -- Open the input file
  2. local input_file = io.open("input.txt", "r")
  3.  
  4. -- Read the contents of the file
  5. local input_text = input_file:read("*all")
  6.  
  7. -- Close the input file
  8. input_file:close()
  9.  
  10. -- Set the maximum number of characters per line
  11. local max_chars_per_line = 50
  12.  
  13. -- Split the input text into lines
  14. local lines = {}
  15. for line in input_text:gmatch("[^\r\n]+") do
  16.     table.insert(lines, line)
  17. end
  18.  
  19. -- Format each line to the maximum number of characters per line
  20. for i, line in ipairs(lines) do
  21.     local formatted_line = ""
  22.     local line_length = 0
  23.     for word in line:gmatch("%S+") do
  24.         if line_length + #word > max_chars_per_line then
  25.             formatted_line = formatted_line .. "\n" .. word .. " "
  26.             line_length = #word + 1
  27.         else
  28.             formatted_line = formatted_line .. word .. " "
  29.             line_length = line_length + #word + 1
  30.         end
  31.     end
  32.     lines[i] = formatted_line
  33. end
  34.  
  35. -- Join the formatted lines back into a single string
  36. local output_text = table.concat(lines, "\n")
  37.  
  38. -- Open the output file
  39. local output_file = io.open("output.txt", "w")
  40.  
  41. -- Write the formatted text to the output file
  42. output_file:write(output_text)
  43.  
  44. -- Close the output file
  45. output_file:close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement