Created
August 10, 2013 11:37
-
-
Save stevedonovan/6200113 to your computer and use it in GitHub Desktop.
Alternative simple implementation of classes for Moonscript. This version is compatible with Lua classes created by Moonlight and Penlight.
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
ctor = (C,...) -> | |
obj = setmetatable {}, C | |
init = rawget C, '_init' | |
if init | |
init(obj,...) | |
return obj | |
is_class = (C) -> | |
mt = getmetatable C | |
if mt and C._class -- this is a base class! | |
return C | |
klass = (C) -> | |
if is_class C | |
base = C | |
return (T) -> | |
T._base = base | |
klass T | |
C.__index = C | |
C._class = C | |
base = rawget C, '_base' | |
if base | |
C._base = base | |
for name,fn in pairs base | |
if C[name] == nil -- let class override base! | |
C[name] = fn | |
setmetatable C, __call: (...) => ctor C, ... | |
return klass |
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
klass = require 'klass' | |
A = klass | |
_init: (name) => | |
@name = name | |
greet: => print "hello", @name | |
__tostring: => @name | |
B = klass(A) | |
greet: => print "hola", @name | |
a = B 'Juan' | |
a\greet! | |
print a | |
---> | |
hola Juan | |
Juan |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment