"Classes" and "Constructors" in Lua?

Stumbling across some frustrating issues trying to make a script more object-oriented. I’m trying to construct a hierarchy of sorts, but putting “constructors” inside others is resulting in empty tables.

local Subdivisions = {}
function Subdivisions:new(n)
  o = {}
  self.__index = self
  setmetatable(o, self)
  for i=1, n do
    o[i] = {on = true, StepParams = {}}
  end
  return o
end

local Beats = {}
function Beats:new(n)
  o = {}
  self.__index = self
  setmetatable(o, self)
  for i=1, n do
    o[i] = {on = true, subs = Subdivisions:new(1)} 
  end
  return o
end

I’m expecting the line >> b = Beats:new(3) to look like

  • 1 => { on = true, subs = table: 0x… }
  • 2 => { on = true, subs = table: 0x… }
  • 3 => { on = true, subs = table: 0x… }

and each subs would look like

  • 1 => { on = true, StepParams = {} }

Instead, tab.print(b) results in what b.subs should be:

  • 1 => table: 0x… = { on = true, StepParams = {} }

replacing the :new() functions with default tables fixes the structure, but then I have to build the subdivisions externally and change them. I’m just trying to figure out the source of this problem.

variables in lua are global by default, even in functions. nasty surprise if you’re coming from python.

so i think o in the inner construcor is wiping out o in the outer constructor.

this works for me:


Subdivisions = {}
function Subdivisions:new(n)
  local o = {}
  self.__index = self
  setmetatable(o, self)
  for i=1,n do
     o[i] = {on = true, StepParams = {}}
  end
  return o
end

Beats = {}
function Beats:new(n, m)
  local o = {}
  self.__index = self
  setmetatable(o, self)
  for i=1, n do
    o[i] = {on = true, subs = Subdivisions:new(m)} 
  end
  return o
end

local b = Beats:new(10, 5)
print(b[1].subs, #b[1].subs)                            -- a table with 5 entires
print(b[1].subs[1].StepParams, #b[1].subs[1].StepParams)   -- a table with no entries

  • made o local in both c-tors
  • changed count of subdivisions in Beats constructor for illustrative purposes
4 Likes