Skip to content

Instantly share code, notes, and snippets.

@maritaria
Created January 12, 2018 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maritaria/64d9422763b105681019d3637faa7cc5 to your computer and use it in GitHub Desktop.
Save maritaria/64d9422763b105681019d3637faa7cc5 to your computer and use it in GitHub Desktop.
Lua multiple views solution
local classes = {}
local registry = {}
function classes.createClass(classname)
local class = {}
class.__views = {}
registry[classname] = class
return class
end
function classes.createInstance(classname)
local class = registry[classname];
local inst = {}
local meta = {}
meta.__index = function(inst, key)
return classes.indexClass(inst, class, key)
end
setmetatable(inst, meta)
return inst
end
function classes.indexClass(inst, class, key)
local view = getmetatable(inst).__view
if view then
local view = class.__views[view];
if view[key] then
return class[key]
else
error("not in view")
end
else
return class[key]
end
end
function classes.createView(classname, viewname)
local class = registry[classname]
local view = {}
class.__views[viewname] = view
return view
end
function classes.setInstanceView(instance, view)
getmetatable(instance).__view = view
end
return classes
local cls = require("classes")
local myClass = cls.createClass("MyClass")
function myClass:getInfo()
print("MyClass:getInfo()")
return self.info
end
function myClass:setInfo(value)
print("MyClass:setInfo()")
self.info = value
end
local publicView = cls.createView("MyClass", "public")
publicView.getInfo = true
local privateView = cls.createView("MyClass", "private")
privateView.getInfo = true
privateView.setInfo = true
local myInst = cls.createInstance("MyClass")
print("Without view:")
myInst:setInfo("hello world")
print(myInst:getInfo())
print()
print("With private view:")
cls.setInstanceView(myInst, "private")
myInst:setInfo("another world")
print(myInst:getInfo())
print()
print("With public view:")
cls.setInstanceView(myInst, "public")
myInst:setInfo("this will fail")
print("this should not print")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment