Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --[[
- author: Alundaio (aka Revolucas)
- A function that creates a new class-like table suitable for combining table properties.
- It is very simple, only 20 lines and it is very aesthetically pleasing to define new 'classes'
- ex 1. Class "new_class"
- ex 2. Class "new_class" (inherit)
- ex 3. Class "new_class" (inherit1,inherit2,...)
- The only requirement is that you need to give _G a metatable where 'this' returns the table
- being indexed, which in my opinion is useful on it's own as it will return the current table
- environment.
- example usage:
- Class "human"
- function human:__init(name)
- self.name = name
- end
- function human:printf()
- print(self.name)
- end
- Class "girl" (human)
- function girl:__init(name)
- self.inherited[1].__init(self,name)
- end
- Class "boy" (human)
- Class "transgender" (boy,girl)
- local instance = transgender("bob")
- instance:printf() -- prints 'bob'
- --]]
- -- Set _G metatable where 'this' returns self of __index.
- setmetatable(_G, {__index=function(t,k)
- if (k == "this") then
- return t
- end
- return rawget(_G,k)
- end
- })
- function Class(name)
- this[name] = setmetatable({},{
- __index = getmetatable(_G).__index,
- __call = function(t,...)
- local o = setmetatable({},{__index=t})
- o:__init(...)
- return o
- end
- })
- return function(...)
- local p = {...}
- this[name].inherited = p
- getmetatable(this[name]).__index=function(t,k)
- for i,v in ipairs(p) do
- local ret = rawget(v,k)
- if (ret ~= nil) then
- return ret
- end
- end
- return getmetatable(_G).__index(_G,k)
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment