mirror of
https://github.com/fortressforever/fortressforever-scripts.git
synced 2025-02-11 22:57:38 +00:00
Merge pull request #26 from fortressforever/lua-class
Add standard Lua Class implementation
This commit is contained in:
commit
adbee54a18
2 changed files with 47 additions and 1 deletions
|
@ -6,8 +6,8 @@
|
||||||
-- This file is loaded automatically whenever a map is loaded.
|
-- This file is loaded automatically whenever a map is loaded.
|
||||||
-- Do not change this file.
|
-- Do not change this file.
|
||||||
-----------------------------------------------------------------------------
|
-----------------------------------------------------------------------------
|
||||||
local _G = getfenv(0)
|
|
||||||
|
|
||||||
|
Class = require "util.class"
|
||||||
|
|
||||||
-----------------------------------------------------------------------------
|
-----------------------------------------------------------------------------
|
||||||
-- defines
|
-- defines
|
||||||
|
|
46
maps/includes/util/class.lua
Normal file
46
maps/includes/util/class.lua
Normal file
|
@ -0,0 +1,46 @@
|
||||||
|
-- from http://lua-users.org/wiki/SimpleLuaClasses
|
||||||
|
|
||||||
|
function Class(base, _ctor)
|
||||||
|
local c = {} -- a new class instance
|
||||||
|
if not _ctor and type(base) == 'function' then
|
||||||
|
_ctor = base
|
||||||
|
base = nil
|
||||||
|
elseif type(base) == 'table' then
|
||||||
|
-- our new class is a shallow copy of the base class!
|
||||||
|
for i,v in pairs(base) do
|
||||||
|
c[i] = v
|
||||||
|
end
|
||||||
|
c._base = base
|
||||||
|
end
|
||||||
|
|
||||||
|
-- the class will be the metatable for all its objects,
|
||||||
|
-- and they will look up their methods in it.
|
||||||
|
c.__index = c
|
||||||
|
|
||||||
|
-- expose a constructor which can be called by <classname>(<args>)
|
||||||
|
local mt = {}
|
||||||
|
|
||||||
|
mt.__call = function(class_tbl, ...)
|
||||||
|
local obj = {}
|
||||||
|
setmetatable(obj,c)
|
||||||
|
|
||||||
|
if c._ctor then
|
||||||
|
c._ctor(obj,...)
|
||||||
|
end
|
||||||
|
return obj
|
||||||
|
end
|
||||||
|
|
||||||
|
c._ctor = _ctor
|
||||||
|
c.is_a = function(self, klass)
|
||||||
|
local m = getmetatable(self)
|
||||||
|
while m do
|
||||||
|
if m == klass then return true end
|
||||||
|
m = m._base
|
||||||
|
end
|
||||||
|
return false
|
||||||
|
end
|
||||||
|
setmetatable(c, mt)
|
||||||
|
return c
|
||||||
|
end
|
||||||
|
|
||||||
|
return Class
|
Loading…
Reference in a new issue