kikito / middleclass

Object-orientation for Lua
https://github.com/kikito/middleclass
MIT License
1.77k stars 190 forks source link

How to separate the given example into different files? #20

Closed venom1978 closed 10 years ago

venom1978 commented 10 years ago

Hi,

I am trying to use your class, and looking at the example given at https://github.com/kikito/middleclass/wiki/Quick-Example

I want to actually have the Person class in a different file and the AgedPerson in a different file.. and then have a main lua file that creates the classes?

How do you do that?

kikito commented 10 years ago

Hi Venom, the easiest way to do what you want is by using Lua's standard require function. Assuming that the files are called main.lua, person.lua and aged_person.lua, and you have middleclass.lua on the same folder:

On person.lua, make the Person variable local, but return it at the end of the file.

-- person.lua
local class = require 'middleclass'

local Person = class('Person') -- or class.Object:subclass('Person')
function Person:initialize(name)
  self.name = name
end
function Person:speak()
  print('Hi, I am ' .. self.name ..'.')
end

return Person

You can use it with Lua's require by doing local Person = require 'person'. This is how you use it on aged_person.lua. Notice that AgedPerson is also a local variable, and it's also returned at the end of the file:

-- aged_person.lua
local class = require 'middleclass'
local Person = require 'person'

local AgedPerson = class('AgedPerson', Person) -- or Person:subclass('AgedPerson')
AgedPerson.static.ADULT_AGE = 18 --this is a class variable
function AgedPerson:initialize(name, age)
  Person.initialize(self, name) -- this calls the parent's constructor (Person.initialize) on self
  self.age = age
end
function AgedPerson:speak()
  Person.speak(self) -- prints "Hi, I am xx."
  if(self.age < AgedPerson.ADULT_AGE) then --accessing a class variable from an instance method
    print('I am underaged.')
  else
    print('I am an adult.')
  end
end

return AgedPerson

Finally, you can require 'aged_person' on main to access the AgedPerson class. You could do the same with Person, but since main.lua doesn't use it, I'm not including it.

-- main.lua
local AgedPerson = require 'aged_person'

local p1 = AgedPerson:new('Billy the Kid', 13) -- this is equivalent to AgedPerson('Billy the Kid', 13) - the :new part is implicit
local p2 = AgedPerson:new('Luke Skywalker', 21)
p1:speak()
p2:speak()

I hope this solves your doutbs. Regards, and thanks for using my library!