Output pagination

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Output pagination

Redmine CSI Piemonte
Hi all,
Thanks for accepting me!
When I'm reading a long text file with LUA, Can I use pagination for splitting output?

Here the code:

function file_exists(file)
  local f = io.open(file, "rb")
  if f then f:close() end
  return f ~= nil
end

function lines_from(file)
  if not file_exists(file) then return {} end
  lines = {}
  for line in io.lines(file) do 
    lines[#lines + 1] = line
  end
  return lines
end

local file = 'test.lua'
local lines = lines_from(file)

for k,v in pairs(lines) do
  print('line[' .. k .. ']', v)
end

I mean...like Linux command:
$ cat filename | more

Thanks for all
Reply | Threaded
Open this post in threaded view
|

Re: Output pagination

Luiz Henrique de Figueiredo
> When I'm reading a long text file with LUA, Can I use pagination for
> splitting output?

Try the code below. Adjust d to your needs.
Use q to quit, f to page forward, b to page backward, enter to see the next line

-- page.lua
-- usage: lua page.lua file

function page(file)
  local f,err = io.open(file, "r")
  if f == nil then
        print(err)
        return
  end
  local lines = {}
  local n = 0
  for line in f:lines() do
        n = n + 1
        lines[n] = line
  end
  os.execute("stty cbreak </dev/tty >/dev/tty 2>&1")
  local b=1
  local d=10
  while true do
  local e=math.min(n,b+d-1)
        for i=b,e do
  print(i,lines[i])
        end
        io.write(":"); io.flush()
        local key = io.read(1)
        io.write("\n"); io.flush()
        if key == "q"  then break end
        if key == "b"  then b=math.max(1,b-d) end
        if key == "f"  then b=math.min(n,b+d) end
        if key == "\n" then b=math.min(n,b+1) end
  end
  os.execute("stty -cbreak </dev/tty >/dev/tty 2>&1");
end

page(arg[1])

Reply | Threaded
Open this post in threaded view
|

Re: Output pagination

Jay Carlson
On Apr 19, 2017, at 12:03 PM, Luiz Henrique de Figueiredo <[hidden email]> wrote:
>
>  os.execute("stty cbreak </dev/tty >/dev/tty 2>&1")
>  [...]
>        local key = io.read(1)
>  [...]
>  os.execute("stty -cbreak </dev/tty >/dev/tty 2>&1");
> end

In case you break out of this loop, your shell may clean up the terminal settings for you. But you may also end up in a mode where stuff like backspace and return don’t work. Too much Unix software has the same problem. The magic Unix keystrokes to fix it:

  stty sane^J

but now we may return to our regularly scheduled discussion of resource management in the face of non-local control flow.

--
Jay Carlson
[hidden email]