Skip to content

Instantly share code, notes, and snippets.

@capr
Created December 20, 2021 02:52
Show Gist options
  • Save capr/5f78e61759dbf97f45d427131f8a0d5f to your computer and use it in GitHub Desktop.
Save capr/5f78e61759dbf97f45d427131f8a0d5f to your computer and use it in GitHub Desktop.
classic.lua with getters & setters
--
-- classic
--
-- Copyright (c) 2014, rxi
--
-- This module is free software; you can redistribute it and/or modify it under
-- the terms of the MIT license. See LICENSE for details.
--
local Object = {}
Object.__index = Object
function Object:new()
end
local function __index(self, k)
local cls = getmetatable(self)
local get = rawget(cls, 'get_'..k)
if get then
return get(self, k)
else
local super = rawget(cls, 'super')
if super then
return super[k]
end
end
end
local function __newindex(self, k, v)
local cls = getmetatable(self)
local set = rawget(cls, 'set_'..k)
if set then
set(self, k, v)
else
rawset(self, k, v)
end
end
function Object:extend()
local cls = {}
for k, v in pairs(self) do
if k:find("__") == 1 then
cls[k] = v
end
end
cls.__index = __index
cls.__newindex = __newindex
cls.super = self
setmetatable(cls, self)
return cls
end
function Object:implement(...)
for _, cls in pairs({...}) do
for k, v in pairs(cls) do
if self[k] == nil and type(v) == "function" then
self[k] = v
end
end
end
end
function Object:is(T)
local mt = getmetatable(self)
while mt do
if mt == T then
return true
end
mt = getmetatable(mt)
end
return false
end
function Object:__call(...)
local obj = setmetatable({}, self)
obj:new(...)
return obj
end
if not ... then --demo
Foo = Object:extend()
local private_x
function Foo:get_x()
print('getting x', private_x)
return private_x
end
function Foo:set_x(x)
print('setting x to', x)
private_x = x
end
local foo = Foo()
foo.x = 5
print(foo.x)
end
return Object
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment