jesterxl

Updated Lua class closure example

Jan 5th, 2013
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.16 KB | None | 0 0
  1. -- BaseObject.lua
  2.  
  3. BaseObject = {}
  4.  
  5. function BaseObject:new(x,y,width,height,world)
  6.  
  7.     local allYourBase = {}
  8.     allYourBase.x = x
  9.     allYourBase.y = y
  10.     allYourBase.width = width
  11.     allYourBase.height = height
  12.  
  13.     function allYourBase:move(x, y)
  14.         self.x = x
  15.         self.y = y
  16.     end
  17.  
  18.     -- etc
  19.  
  20.     return allYourBase
  21. end
  22.  
  23. return BaseObject
  24.  
  25. -- OrganicObject.lua
  26.  
  27. require "BaseObject"
  28.  
  29. OrganicObject = {}
  30.  
  31. function OrganicObject:new(x,y,width,height,world)
  32.     local organic = BaseObject:new(x,y,width,height,world)
  33.     organic.type = "organic"
  34.     organic.growth = 0
  35.  
  36.     function organic:init()
  37.         self.skinScale = (self.diagSize/self.diagStartSize)
  38.     end
  39.  
  40.     return organic
  41. end
  42.  
  43. return OrganicObject
  44.  
  45. -- Player.lua
  46.  
  47. require "OrganicObject"
  48.  
  49. Player = {}
  50.  
  51. function Player:new(x,y,width,height,world)
  52.     local player = OrganicObject:new(x,y,width,height)
  53.  
  54.     player.oldInit = player.init
  55.     function player:init()
  56.         -- additional overwrode logic
  57.         self:oldInit() -- call the super class' method
  58.     end
  59.  
  60.     player:init()
  61.  
  62.     return player
  63. end
  64.  
  65. return Player
  66.  
  67. -- main.lua
  68.  
  69. require "Player"
  70. local player = Player:new(0, 0, 100, 100, someWorld)
  71. player:move(100, 300)
Advertisement
Add Comment
Please, Sign In to add comment