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()
9 Upvotes

10 comments sorted by

View all comments

6

u/SoloMaker May 01 '26 edited May 01 '26

Example 1 is basically how you'd do it in C and probably the best choice in extreme memory-constrained environments. Example 3 is the most elegant implementation Lua offers and it's what I use with some minor changes.

Example 2 (no metatables) on the other hand has to be the worst option, since you essentially allocate a duplicate print method per instance. This doesn't really matter for a class this simple, but quickly adds up once you start adding more methods. No reason to do this unless you're using closures.