Code: Select all
--************************************************
-- Class.lua by Andy 'Soul Rider' Wilson
--
-- This file creates a basic class inheritance
-- structure. Class is intialized with an OnInit()
-- function.
--
--*************************************************
function Class(base, OnInit)
local c = {} -- a new class instance
if not OnInit and type(base) == 'function' then
OnInit = 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 class_tbl.OnInit then
class_tbl.OnInit(obj,...)
else
-- make sure that any stuff from the base class is initialized!
if base and base.OnInit then
base.OnInit(obj, ...)
end
end
return obj
end
c.OnInit = OnInit
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
Code: Select all
--************************************************
-- Team.lua by Andy 'Soul Rider' Wilson
--
-- This file creates a base team class.
-- It contains basic team functionality and can
-- be extended to create PlayingTeam for example
-- by using the following code:
-- PlayingTeam = Class(Team)
--*************************************************
Team = Class()
function Team:OnInit(teamName, teamNumber)
Team.teamName = teamName
Team.teamNumber = teamNumber
Team.teamPlayerIDs = {}
end
function Team:GetTeamNumber()
return Team.teamNumber
end
function Team:AddPlayer(player)
local id = player.GetID()
table.insert(Team.teamPlayerIDs, id)
end
function Team:RemovePlayer(player)
local id = player.GetID()
table.remove(Team.teamPlayerIDs, id)
end
One of my plans is to extend the class to make it so entity scripts can be subclassed, so specific player types could be constructed by sub-classing the HumanPlayer script for example. I haven't tested, but in theory, a call like:
RobotPlayer = Class(PlayerScript)
Could be made to work, as long as PlayerScript was a global, as the script files already define an OnInit() function. The function may need a lua version, but I am sure it could be made to work with a little experimentation.