r/lua • u/DotGlobal8483 • 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
View all comments
Show parent comment
1
u/AutoModerator May 01 '26
Hi! Your code block was formatted using triple backticks in Reddit's Markdown mode, which unfortunately does not display properly for users viewing via old.reddit.com and some third-party readers. This means your code will look mangled for those users, but it's easy to fix. If you edit your comment, choose "Switch to fancy pants editor", and click "Save edits" it should automatically convert the code block into Reddit's original four-spaces code block format for you.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.