Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- method chaining example with Lua
- -- what is method chaining? http://en.wikipedia.org/wiki/Method_chaining
- -- i think its funny that the quick example that I thought of to type here also turns out to be a similar example in that article!
- ----------------------------------------------------------------
- -- just some object setup code --
- -- an important thing to note is the returns in the functions --
- ----------------------------------------------------------------
- local obj = {name='unknown', age='unknown', gender='unknown', __tostring = function(self) return 'Name: '..self.name..', Age: '..self.age..', Sex: '..self.gender end}
- function new()
- return setmetatable(obj, obj)
- end
- function obj:setName(n)
- self.name = n
- return self -- you must return self, or it wont work
- end
- function obj:setAge(n)
- self.age = n
- return self -- you must return self, or it wont work
- end
- function obj:setGender(n)
- n:lower()
- if n ~= 'male' and n ~= 'female' then
- n = 'confused'
- end
- self.gender = n
- return self -- you must return self, or it wont work
- end
- ---------------------------------
- -- THE METHOD CHAINING EXAMPLE --
- ---------------------------------
- -- create it
- local p = new()
- print(p)
- -- method chaining on an already created object
- p:setName('Bob'):setAge(21):setGender('male')
- print(p)
- -- method chaining and creation on the same line
- local p2 = new():setName('Janet'):setAge(18):setGender('female')
- print(p2)
- -- a more readable method chaining
- local p3 = new():setName('Jose')
- :setAge(34)
- :setGender('other')
- print(p3)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement