wip class system

This commit is contained in:
Paul Liverman III 2017-08-14 05:48:36 -07:00
parent f8f9ef53c8
commit 559fa50459
3 changed files with 71 additions and 0 deletions

20
class.lua Normal file
View File

@ -0,0 +1,20 @@
local Class
Class = function(name, parent)
local newClass, base
base = {
__index = base,
__class = newClass
}
newClass = setmetable({
__init = function() end,
__base = base,
__name = name
}, {
__call = function(cls, ...)
local self = setmetable({ }, base)
cls.__init(self, ...)
return self
end
})
end
return Class

39
class.moon Normal file
View File

@ -0,0 +1,39 @@
-- basically, gonna use the knowledge of how MoonScript classes work to make
-- something that does the same thing using syntax similar to MiddleClass
Class = (name) ->
local newClass, base
base = {
__index: base
__class: newClass
}
newClass = setmetable {
__init: ->
__base: base
__name: name
}, {
__call: (cls, ...) ->
@ = setmetable({}, base)
cls.__init(@, ...)
return @
}
return newClass
return Class
-- base obj with an __index to itself, contains functions accepting a self argument,
-- and __class pointing to class obj
--
-- class is obj w __init function, __base linking to base obj, and __name specifying name of class
-- it has metatable, __index is the base table (makes perfect sense),
-- __call is a function that creates a self obj w the base obj as a metatable, then calls __init
-- on it, and returns the self (__init is never meant to get directly called)
--
-- inheritance addtionally does:
--
-- new base obj will have a metatable set to parent.__base (where parent is parent class obj)
-- new class obj will have __parent value linking to parent class obj, and __index metamethod
-- that returns rawget(new base, name) or return parent class[name] if that was nil
-- if parent class had __inherited, then is called w parent class and new class

12
tmp.class.usage.lua Normal file
View File

@ -0,0 +1,12 @@
local class = require "Class"
local Car = class("Car")
function Car:__init(x, y)
self.x = x or 0
self.y = y or 0
end
function Car:print() -- this will be broken
print("I'm a car, at ("..self.x..","..self.y..")")
end