Advertisement
neilpopham

LUA Inheritance

Oct 17th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.87 KB | None | 0 0
  1. parent={
  2.  create=function(self,o)
  3.   o=o or {}
  4.   o.baz=12
  5.   setmetatable(o,self)
  6.   self.__index=self
  7.   return o
  8.  end,
  9.  foo=function(self)
  10.   return "foo "..self.x
  11.  end,
  12.  bar=function(self)
  13.   return "bar"
  14.  end
  15. }
  16.  
  17. child={
  18.  create=function(self,o)
  19.   o=parent.create(self,o)
  20.   o.qux=48
  21.   return o
  22.  end,
  23.  bar=function(self)
  24.   return parent:bar().." bar black sheep"
  25.  end
  26. } setmetatable(child,{__index=parent})
  27.  
  28. p=parent:create({x=1,y=2})
  29. c=child:create({x=10,z=30})
  30.  
  31. printh(p:foo())
  32. printh(c:foo())
  33. printh(p:bar())
  34. printh(c:bar())
  35.  
  36. printh(p.x)
  37. printh(c.x)
  38. printh(p.y)
  39. printh(c.y)
  40. printh(p.z)
  41. printh(c.z)
  42. printh(p.baz)
  43. printh(c.baz)
  44. printh(p.qux)
  45. printh(c.qux)
  46.  
  47. --[[ output
  48. INFO: foo 1
  49. INFO: foo 10
  50. INFO: bar
  51. INFO: bar bar black sheep
  52. INFO: 1
  53. INFO: 10
  54. INFO: 2
  55. INFO: [nil]
  56. INFO: [nil]
  57. INFO: 30
  58. INFO: 12
  59. INFO: 12
  60. INFO: [nil]
  61. INFO: 48
  62. ]]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement