Advertisement
kreezxil

less for computercraft (more/cat)

Sep 23rd, 2024
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.76 KB | Gaming | 0 0
  1. -- Less-like program to view a file in pages
  2. local function less(filename)
  3.     -- Try to open the file
  4.     local file = fs.open(filename, "r")
  5.     if not file then
  6.         error("File not found: " .. filename, 0)
  7.         return
  8.     end
  9.  
  10.     -- Constants for display
  11.     local width, height = term.getSize()
  12.     local lines = {}
  13.     local scrollPosition = 1
  14.  
  15.     -- Read the file content into lines
  16.     local line = file.readLine()
  17.     while line do
  18.         table.insert(lines, line)
  19.         line = file.readLine()
  20.     end
  21.     file.close()
  22.  
  23.     -- Function to display a portion of the file
  24.     local function display()
  25.         term.clear()
  26.         term.setCursorPos(1, 1)
  27.         for i = scrollPosition, math.min(scrollPosition + height - 1, #lines) do
  28.             print(lines[i])
  29.         end
  30.     end
  31.  
  32.     -- Main loop to handle scrolling
  33.     while true do
  34.         display()
  35.         local event, key = os.pullEvent("key")
  36.  
  37.         -- Scrolling down
  38.         if key == keys.down or key == keys.pageDown then
  39.             if scrollPosition + height - 1 < #lines then
  40.                 scrollPosition = scrollPosition + 1
  41.             end
  42.         -- Scrolling up
  43.         elseif key == keys.up or key == keys.pageUp then
  44.             if scrollPosition > 1 then
  45.                 scrollPosition = scrollPosition - 1
  46.             end
  47.         -- Exit on "q" key
  48.         elseif key == keys.q then
  49.             break
  50.         end
  51.     end
  52. end
  53.  
  54. -- Main program execution
  55. local tArgs = { ... }
  56.  
  57. if #tArgs > 0 then
  58.     -- If a filename is passed, try to open the file
  59.     local filename = tArgs[1]
  60.     less(filename)
  61. else
  62.     -- Ask the user for a filename if no argument is passed
  63.     print("Enter filename: ")
  64.     local filename = read()
  65.     less(filename)
  66. end
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement