Lua class getting overwritten

Viewed 23

So, I have this lua class (really a metatable) that is getting overwritten by one of it's children. Here is the code that makes the class:

--// Class
local Lexer = {
    Text = "",
    Pos = nil,
    CC = nil
}

--// Initializer
function Lexer.new(Text, Fn)
    -- Set metatable
    self = setmetatable({}, Lexer)

    -- Set variables
    self.Text = Text
    self.Pos = POS.new(0, 0, 0, Fn, Text)
    self.CC = nil
    self:Advance()

    -- Return
    return self
end

And here is the code for the POS module, which I am including:

--// Make the module
local Position = {
  Idx = 0,
  Line = 0,
  Col = 0,
  Fn = "",
  Ftxt = ""
}

--// Constructor
function Position.new(Idx, Line, Col, Fn, Ftxt)
  -- Set metatable
  self = setmetatable({}, Position)

  -- Set variables
  self.Idx  = Idx
  self.Line = Line
  self.Col  = Col
  self.Fn   = Fn
  self.Ftxt = Ftxt

  -- Return self
  return self
end

I have a .__index method in both of them. Help is appreciated! Oh, and, POS is defined like: local POS = require("lib/position")

1 Answers

self is not defined and therefore you use the global self as a variable. Since you call the constructor of Pos while initializing Lexer it will cause errors. Prefix both self with local.

self is only automatically defined if using the : syntax, e.g. Lexer:new() and function Lexer:new(Text, Fn).

Related