Skip to content

Instantly share code, notes, and snippets.

@thelindat
Last active April 22, 2024 20:02
Show Gist options
  • Save thelindat/79ea6d7e13d0764382e47fe12a781cd7 to your computer and use it in GitHub Desktop.
Save thelindat/79ea6d7e13d0764382e47fe12a781cd7 to your computer and use it in GitHub Desktop.
ox_lib class example
-- ref: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Classes_in_JavaScript
-- Person Class
---@class Person : OxClass
---@field name string
local Person = lib.class('Person')
function Person:constructor(name)
print('calling Person constructor for', name)
self.name = name
end
-- Professor Class (extends Person)
---@class Professor : Person
local Professor = lib.class('Professor', Person)
function Professor:constructor(name, teaches)
print('calling Professor constructor for', name)
self:super(name)
self.teaches = teaches
end
function Professor:introduceSelf()
print(("My name is %s, and I will be your %s professor."):format(self.name, self.teaches))
end
function Professor:grade(paper)
local grade = math.random(1, 4)
print(grade)
end
CreateThread(function()
local walter = Professor:new('Walter', 'Chemistry')
walter:introduceSelf()
walter:grade('my paper')
end)
-- Student Class (extends Person)
---@class Student : Person
local Student = lib.class('Student', Person)
function Student:constructor(name, year)
print('calling Student constructor for', name)
self:super(name)
self.private.year = year
end
function Student:introduceSelf()
print(("Hi! I'm %s, and I'm in year %s."):format(self.name, self.private.year))
end
function Student:setYear(year)
-- methods can freely update private fields
self.private.year = year
end
CreateThread(function()
local jesse = Student:new('Jesse', 2)
print(jesse.private.year)
jesse:introduceSelf()
jesse:setYear(3)
jesse:introduceSelf()
-- nil - cannot access outside methods
print(jesse.private.year)
-- empty table
print(json.encode(jesse.private))
-- 'private'
print(getmetatable(jesse.private))
-- throws error when trying to set private value outside a method
jesse.private.year = 4
end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment