Advertisement
theoriginalbit

Dynamic Invocation on Lua Objects

Nov 21st, 2013
297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.91 KB | None | 0 0
  1. --# obj is the OO table. do not define functions in here, they must be defined after this declaration for the __newindex metamethod to be invoked
  2.  
  3. local obj = setmetatable({}, {
  4.   __newindex = function(self, key, value)
  5.     if type(value) == "function" then
  6.       local func = setmetatable({}, {
  7.         __call = function(_, ...)
  8.           if rawequal(self, ({...})[1]) then
  9.             return value(...)
  10.           end
  11.           return value(self, ...)
  12.         end;
  13.       })
  14.       rawset(self, key, func)
  15.     else
  16.       rawset(self, key, value)
  17.     end
  18.   end;
  19. })
  20.  
  21. --# so add functions to your object here, define them like detailed below
  22.  
  23. function obj:foo()
  24.   print(self)
  25. end
  26.  
  27. function obj.bar(self)
  28.   print(self)
  29. end
  30.  
  31. --# from now on the above functions can be invoked in one of three ways
  32.  
  33. obj:foo()
  34. obj.foo(obj)
  35. obj.foo() --# this is not normal OO, yet it still works due to the metatable magic.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement