soulik icon

Simple object with metatable

soulik | PRO | 07/01/14 08:00:23 PM UTC | 0 ⭐ | 441 👁️ | Never ⏰ | []
Lua |

650 B

|

None

|

0 👍

/

0 👎

local function object()
    local obj = {}
    local variable1 = 5
    local variable2 = "Hello John!"
 
    local mt = {
        -- get a value from this object
        __index = function(obj, name)
            if name=="variable1" then
                return variable1
            elseif name=="variable2" then
                return variable2
            end
        end,
        
        __newindex = function(obj, name, value)
            if name=="variable1" then
                variable1 = value
            elseif name=="variable2" then
                variable2 = value
            end
        end,
    }
 
    setmetatable(obj, mt)
    return obj
end
 
local o1 = object()
print(o1.variable1, o1.variable2)
o1.variable1 = 100
o1.variable2 = "Hi!"
print(o1.variable1, o1.variable2)

Comments