Advertisement
Qugurun

OOP Lua

Mar 3rd, 2024
717
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.19 KB | Source Code | 0 0
  1. print("OOP Lua!")
  2.  
  3. -------------------------------------------------------
  4. local mt = {}
  5. -- setter
  6. function mt.__newindex( self, index, value )
  7.     if index == 'name' and type(value) == 'string' then
  8.        self.setName(value)
  9.     else
  10.         rawset( self, index, value )
  11.     end
  12. end
  13.  
  14. -------------------------------------------------------
  15. --getter
  16. function mt.__index( self, index )
  17.     if index == 'name' then
  18.         return self.getName()
  19.     else
  20.         return rawget( self, index )
  21.     end
  22. end
  23. -------------------------------------------------------
  24. local User = {}
  25. function User.new()
  26.     local _name = 'Qugurun'
  27.     local object = {
  28.         setName = function(n)
  29.             _name = n
  30.         end,
  31.        
  32.         getName = function()
  33.             return _name
  34.         end
  35.     }
  36.     return setmetatable(object, mt)
  37. end
  38. --=====================================================
  39.  
  40. local user1 = User.new()
  41. local user2 = User.new()
  42.  
  43. user1.name = "Laimadoo"
  44. print(user1.name) --> Laimadoo
  45. print(user2.name) --> Qugurun
  46. print(user2._name) --> nil
  47.  
  48. for k,v in pairs(user1) do
  49.     print(k,v) --> getName  function: ...
  50.                --> setName  function: ...
  51. end
  52.  
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement