Skip to content

Instantly share code, notes, and snippets.

@balaam
Created July 22, 2016 13:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save balaam/a5489bfeb4ddaac2b083f179c20a7fe7 to your computer and use it in GitHub Desktop.
Save balaam/a5489bfeb4ddaac2b083f179c20a7fe7 to your computer and use it in GitHub Desktop.
#!/opt/local/bin/lua
--
-- Simple parser
--
if not arg[1] then
print "Need a filename as an argument."
return
end
local f = io.open(arg[1], "rb")
local content = f:read("*all")
f:close()
context =
{
content = content,
cursor = 1,
line_number = 1,
column_number = 0,
syntax_tree = {},
Byte = function(self)
return self.content:sub(self.cursor, self.cursor)
end,
AtEnd = function(self)
return self.cursor == #self.content
end,
AdvanceCursor = function(self)
self.cursor = self.cursor + 1
if self.cursor > #self.content then
print("Warning: Trying to advance past the end of the content.")
self.cursor = #self.content
end
self.column_number = self.column_number + 1
if self:Byte() == '\n' then
self.line_number = self.line_number + 1
self.column_number = 0
end
end
}
-- [1] Start by printing out the no lines in the file
-- [2] Make a gist at this point as it's quite a common op
while true do
print(context:Byte())
if context:AtEnd() then
break
else
context:AdvanceCursor()
end
end
print("Number of lines ", context.line_number)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment