Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- Less-like program to view a file in pages
- local function less(filename)
- -- Try to open the file
- local file = fs.open(filename, "r")
- if not file then
- error("File not found: " .. filename, 0)
- return
- end
- -- Constants for display
- local width, height = term.getSize()
- local lines = {}
- local scrollPosition = 1
- -- Read the file content into lines
- local line = file.readLine()
- while line do
- table.insert(lines, line)
- line = file.readLine()
- end
- file.close()
- -- Function to display a portion of the file
- local function display()
- term.clear()
- term.setCursorPos(1, 1)
- for i = scrollPosition, math.min(scrollPosition + height - 1, #lines) do
- print(lines[i])
- end
- end
- -- Main loop to handle scrolling
- while true do
- display()
- local event, key = os.pullEvent("key")
- -- Scrolling down
- if key == keys.down or key == keys.pageDown then
- if scrollPosition + height - 1 < #lines then
- scrollPosition = scrollPosition + 1
- end
- -- Scrolling up
- elseif key == keys.up or key == keys.pageUp then
- if scrollPosition > 1 then
- scrollPosition = scrollPosition - 1
- end
- -- Exit on "q" key
- elseif key == keys.q then
- break
- end
- end
- end
- -- Main program execution
- local tArgs = { ... }
- if #tArgs > 0 then
- -- If a filename is passed, try to open the file
- local filename = tArgs[1]
- less(filename)
- else
- -- Ask the user for a filename if no argument is passed
- print("Enter filename: ")
- local filename = read()
- less(filename)
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement