soulik

Simple object with metatable

Jul 1st, 2014
375
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.65 KB | None | 0 0
  1. local function object()
  2.     local obj = {}
  3.     local variable1 = 5
  4.     local variable2 = "Hello John!"
  5.  
  6.     local mt = {
  7.         -- get a value from this object
  8.         __index = function(obj, name)
  9.             if name=="variable1" then
  10.                 return variable1
  11.             elseif name=="variable2" then
  12.                 return variable2
  13.             end
  14.         end,
  15.        
  16.         __newindex = function(obj, name, value)
  17.             if name=="variable1" then
  18.                 variable1 = value
  19.             elseif name=="variable2" then
  20.                 variable2 = value
  21.             end
  22.         end,
  23.     }
  24.  
  25.     setmetatable(obj, mt)
  26.     return obj
  27. end
  28.  
  29. local o1 = object()
  30. print(o1.variable1, o1.variable2)
  31. o1.variable1 = 100
  32. o1.variable2 = "Hi!"
  33. print(o1.variable1, o1.variable2)
Advertisement
Add Comment
Please, Sign In to add comment