Posted 15 February 2016 - 05:10 PM
I'm just new on using metatables and methods, can anyone tell me what I'm doing wrong here?
I'm guessing it cannot read the test table in the object.prototype. but whenever I print test.x it prints 4 and not returning nil
It's suppose to print 8 but its not working :(/>
object.prototype.body.x = test.x+5
this code at line 12, always returning an error saying test.x is nilI'm guessing it cannot read the test table in the object.prototype. but whenever I print test.x it prints 4 and not returning nil
--should always be empty to always run newindex and index metamethods
object = {}
--proxy table
test = {}
-- create the prototype with default values
object.prototype = {}
object.prototype.x = 0
object.prototype.y = 0
object.prototype.width = 64
object.prototype.height = 64
object.prototype.body = {}
object.prototype.body.x = 2*test.x
--metatable
object.mt = {}
--if the index is in test return test else return prototype
object.mt.__index = function (table, key)
if test[key] ~= nil then
return test[key]
else
return object.prototype[key]
end
end
--send value to proxy
object.mt.__newindex = function (self, index, value)
test[index] = value
end
function new()
function addMt (o)
setmetatable(o, object.mt)
return o
end
return addMt({})
end
w = new()
w.x = 4 --test.x = 4
print(w.body.x) --nil, suppose to return prototype value which should return 8 (test.x*2)
It's suppose to print 8 but its not working :(/>