Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Alternative simple implementation of classes for Moonscript. This version is compatible with Lua classes created by Moonlight and Penlight.
ctor = (C,...) ->
obj = setmetatable {}, C
init = rawget C, '_init'
if init
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
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'
print a
hola Juan
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.