diff --git a/behave.lua b/behave.lua index e931b44..ed71c74 100644 --- a/behave.lua +++ b/behave.lua @@ -665,6 +665,43 @@ do end RunOnce = _class_0 end +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 + }) + if parent then + setmetable(base, { + __parent = parent.__base + }) + newClass.__parent = parent + newClass.__index = function(cls, name) + local val = rawget(base, name) + if val == nil then + return parent[name] + else + return val + end + end + if parent.__inherited then + parent:__inherited(newClass) + end + end + return newClass, base +end local behave = { Node = Node, Sequence = Sequence, @@ -679,11 +716,17 @@ local behave = { RunOnce = RunOnce, success = success, running = running, - fail = fail + fail = fail, + Class = Class } behave.clone = function(object) + local new local cls = getmetatable(object).__class.__name - local new = behave[cls](object) + if cls == "Repeat" then + new = behave[cls](object.cycles, object) + else + new = behave[cls](object) + end if object.nodes then local nodes = { } for k, v in pairs(object.nodes) do diff --git a/behave.moon b/behave.moon index c597f3f..9b6594f 100644 --- a/behave.moon +++ b/behave.moon @@ -241,6 +241,43 @@ class RunOnce extends Node else return fail +-- A MoonScript-compatible class implementation for creating your own classes. +Class = (name, parent) -> + local newClass, base + base = { + __index: base + __class: newClass + } + + newClass = setmetable { + __init: -> + __base: base + __name: name + }, { + __call: (cls, ...) -> + @ = setmetable({}, base) + cls.__init(@, ...) + return @ + } + + if parent + setmetable base, { + __parent: parent.__base + } + + newClass.__parent = parent + newClass.__index = (cls, name) -> + val = rawget(base, name) + if val == nil + return parent[name] + else + return val + + if parent.__inherited + parent\__inherited newClass + + return newClass, base + behave = { -- Leaf Node :Node @@ -263,6 +300,9 @@ behave = { :success :running :fail + + -- Utility Fns + :Class } behave.clone = (object) ->