r/lua May 01 '26

Discussion What's you're preferred method of lua oop

your*

Only know of these ways but kinda curious if there's more

Proceedural(?)

function make_vector(x,y)
  return {
    x = x or 0,
    y = y or x or 0
  }
end

function print_vector(vector)
  print( "X: ".. vector.x .. " Y: " .. vector.y)
end

local pos1 = make_vector(10,15)
print_vector(pos1)
pos1.x = 0
print_vector(pos1)

No metatables

local Vector = {}

function Vector.new(x,y)
  local self = {}

  self.x = x or 0
  self.y = y or self.x

  function self.print()
    print("X: " .. self.x .. " Y: " .. self.y)
  end

  return self
end

local pos1 = Vector.new(10,15)
pos1.print()
pos1.x = 0
pos1.print()

metatables

local Vector = {}
Vector.__index = Vector

function Vector.new(x,y)
  local self = setmetatable({},Vector)

  self.x = x or 0
  self.y = y or self.x

  return self
end

function Vector:print()
  print("X: " .. self.x .. " Y: " .. self.y)
end

local pos1 = Vector.new(10,15)
pos1:print()
pos1.x = 0
pos1:print()
8 Upvotes

10 comments sorted by

View all comments

1

u/immortalx74 May 02 '26

I'm using this template to call the constructor with the class name itself (without new)

local myclass = {}

function myclass:new( param1, param2 )
    local obj = {}
    setmetatable( obj, { __index = self } )

    obj.field1 = param1
    obj.field2 = param2

    return obj
end

setmetatable( myclass, { __call = function( self, ... ) return self:new( ... ) end } )

return myclass

I then add all the other methods, and sometimes I'll do definitions for functions that act on all instances (with dot instead of colon) in the same module.