Skip to content

Instantly share code, notes, and snippets.

@blasti
Last active March 13, 2022 00:31
Show Gist options
  • Save blasti/a1f2fd90f0f6933fe5583ea6777a374a to your computer and use it in GitHub Desktop.
Save blasti/a1f2fd90f0f6933fe5583ea6777a374a to your computer and use it in GitHub Desktop.
Simple tail implementation in lua
#!/usr/bin/env lua
-- Example usage: ./tail.lua logfile -10
local fd=io.open(arg[1],"r")
local lines_to_read=math.abs(tonumber(arg[2]) or 0)
local eof=fd:seek("end",-1)
local pos=eof
local lines_read=0
local buf={}
local buf_len=0
while pos do
local byte=fd:read(1)
if byte=="\n" then
if pos<eof then
lines_read=lines_read+1
end
if lines_read>=lines_to_read then
break
end
end
buf_len=buf_len+1
buf[buf_len]=byte
pos=fd:seek("cur",-2)
end
io.write(table.concat(buf):reverse())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment