Skip to content

Instantly share code, notes, and snippets.

@omidahourai
Created November 27, 2012 20:02
Show Gist options
  • Save omidahourai/4156666 to your computer and use it in GitHub Desktop.
Save omidahourai/4156666 to your computer and use it in GitHub Desktop.
Enemy Class (example for OO-Lua)
--Enemy.lua
local scene = scene
local Enemy = {Instances={}}; scene.Enemy = Enemy
--STATIC CLASS FUNCTIONS (self refers to Enemy, not enemy)
function Enemy:New()
--creates an enemy instance
local enemy = display.newImage('image_name')
enemy.show = self.show
enemy.hide = self.hide
enemy.attack = self.attack
enemy.move = self.move
table.insert(self.Instances, enemy)
return enemy
end
function Enemy:Get() --Gets an available enemy instance
local Instances = self.Instances
if (not Instances[1]) then self:New() end
return table.remove(Instances, 1)
end
function Enemy:Dispose(obj) --Makes an enemy-in-use available again
table.insert(self.Instances, obj)
end
function Enemy:Show(config) --Gets/ shows an enemy in one call
local obj = self:Get()
obj:show(config)
return obj
end
--NON-STATIC/ INSTANCE FUNCTIONS (self refers to enemy, not Enemy)
function Enemy:show(config)
--each enemy can show itself
self.x, self.y = config.x, config.y
self.isVisible = true
end
function Enemy:hide()
--each enemy can hide/ return itself to the Instances array
self.isVisible = false
Enemy:Dispose(self)
end
function Enemy:attack()
--each enemy can attack
end
function Enemy:move()
--each enemy can move
end
--Pool 10 enemies at load-time
for i=1,10 do Enemy:New() end
return Enemy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment