The table.insert()
function is overwriting all indices in my table. I am trying to append tokens to the table to pass on to a parser, but it isn't working. Here are some code snippets:
Tokenizing, where the problem is happening:
function Lexer:Tokenize()
local Tokens = {}
while self.CC ~= nil do
if string.find(" \t", self.CC) then
self:Advance()
-- Numbers
elseif string.find(C.DIGITS, self.CC) then
table.insert(Tokens, self:MakeNumber())
-- Operators
elseif self.CC == "+" then
table.insert(Tokens, TOK:new(C.TT_PLUS, nil, self.Pos))
self:Advance()
elseif self.CC == "-" then
table.insert(Tokens, TOK:new(C.TT_MINUS, nil, self.Pos))
self:Advance()
elseif self.CC == "*" then
table.insert(Tokens, TOK:new(C.TT_MUL, nil, self.Pos))
self:Advance()
elseif self.CC == "/" then
table.insert(Tokens, TOK:new(C.TT_DIV, nil, self.Pos))
self:Advance()
elseif self.CC == "(" then
table.insert(Tokens, TOK:new(C.TT_LPAREN, nil, self.Pos))
self:Advance()
elseif self.CC == ")" then
table.insert(Tokens, TOK:new(C.TT_RPAREN, nil, self.Pos))
self:Advance()
-- Errors
else
local PosStart = self.Pos:Copy()
local Char = self.CC
self:Advance()
return {}, E.IllegalCharError:new(string.format("'%s'",Char, PosStart, self.Pos))
end
end
for k, v in pairs(Tokens) do
print(k, v:repr())
end
table.insert(Tokens, TOK:new(C.TT_EOF, nil, self.Pos))
return Tokens, nil
end
And here is the code for the token class. Token:repr() is just a way to make the string look nice.
local C = require("constants")
local Token = {
Type = "",
Value = nil,
PosStart = nil,
PosEnd = nil
}
-- Token initializer
function Token:new(Type, Value, PosStart, PosEnd)
Value = Value or nil
PosStart = PosStart or nil
PosEnd = PosEnd or nil
setmetatable({}, Token)
self.Type = Type
self.Value = Value
if PosStart then
self.PosStart = PosStart:Copy()
self.PosEnd = PosStart:Copy()
end
if PosEnd then
self.PosEnd = PosEnd:Copy()
end
return self
end
function Token:repr()
if self.Value ~= nil then
return string.format("%s: %s", self.Type, self.Value)
end
return string.format("%s", self.Type)
end
return Token
Help appreciated :)