Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- wengwengweng
- local int = {}
- local function class(specs)
- local struct = {}
- local types = {}
- local fns = {}
- local super = specs.__super
- if type(super) == "table" then
- local super_types = super.__types
- local super_fns = super.__fns
- if type(super_types) == "table" then
- for k, v in pairs(super_types) do
- types[k] = v
- end
- end
- if type(super_fns) == "table" then
- for k, v in pairs(super_fns) do
- fns[k] = v
- end
- end
- end
- for k, v in pairs(specs) do
- if type(v) == "table" then
- if v == string then
- types[k] = "string"
- elseif v == int then
- types[k] = "number"
- end
- elseif type(v) == "function" then
- fns[k] = v
- else
- error("expected type or function")
- end
- end
- struct.__types = types
- struct.__fns = fns
- setmetatable(struct, {
- __call = function()
- local obj = {}
- local proxy = {}
- for k, v in pairs(fns) do
- obj[k] = function()
- v(obj)
- end
- end
- setmetatable(obj, {
- __index = function(self, k)
- return proxy[k]
- end,
- __newindex = function(self, k, v)
- local expected_type = types[k]
- local actual_type = type(v)
- if not expected_type then
- error("failed to set " .. k)
- else
- if actual_type ~= expected_type then
- error("expected " .. expected_type .. ", found " .. actual_type)
- end
- end
- proxy[k] = v
- end,
- })
- return obj
- end,
- })
- return struct
- end
- local A = class {
- name = string,
- age = int,
- foo = function(self)
- print("from A", self.name, self.age)
- end
- }
- local B = class {
- __super = A,
- foo = function(self)
- print("from B", self.name, self.age)
- end
- }
- local a = A()
- a.name = "hanmeimei"
- a.age = 17
- a:foo()
- local b = B()
- b.name = "lilei"
- b.age = 18
- b:foo()
- a.name = 20
- a.age = "20"
- b.foo = "x"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement