Created
January 12, 2018 12:46
-
-
Save maritaria/64d9422763b105681019d3637faa7cc5 to your computer and use it in GitHub Desktop.
Lua multiple views solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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