Advertisement
theoriginalbit

Method Chaining Example with Lua

May 12th, 2013
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.63 KB | None | 0 0
  1. -- method chaining example with Lua
  2. -- what is method chaining? http://en.wikipedia.org/wiki/Method_chaining
  3. -- 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!
  4.  
  5. ----------------------------------------------------------------
  6. -- just some object setup code                                --
  7. -- an important thing to note is the returns in the functions --
  8. ----------------------------------------------------------------
  9.  
  10. local obj = {name='unknown', age='unknown', gender='unknown', __tostring = function(self) return 'Name: '..self.name..', Age: '..self.age..', Sex: '..self.gender end}
  11.  
  12. function new()
  13.   return setmetatable(obj, obj)
  14. end
  15.  
  16. function obj:setName(n)
  17.   self.name = n
  18.   return self -- you must return self, or it wont work
  19. end
  20.  
  21. function obj:setAge(n)
  22.   self.age = n
  23.   return self -- you must return self, or it wont work
  24. end
  25.  
  26. function obj:setGender(n)
  27.   n:lower()
  28.   if n ~= 'male' and n ~= 'female' then
  29.     n = 'confused'
  30.   end
  31.   self.gender = n
  32.   return self -- you must return self, or it wont work
  33. end
  34.  
  35. ---------------------------------
  36. -- THE METHOD CHAINING EXAMPLE --
  37. ---------------------------------
  38.  
  39. -- create it
  40. local p = new()
  41. print(p)
  42.  
  43. -- method chaining on an already created object
  44. p:setName('Bob'):setAge(21):setGender('male')
  45. print(p)
  46.  
  47. -- method chaining and creation on the same line
  48. local p2 = new():setName('Janet'):setAge(18):setGender('female')
  49. print(p2)
  50.  
  51. -- a more readable method chaining
  52. local p3 = new():setName('Jose')
  53.                 :setAge(34)
  54.                 :setGender('other')
  55. print(p3)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement