inputperceptron = {weight = {} -- there will be one weight per hidden p
}
function inputperceptron:new(o)
o = o or {}
setmetatable(o,self)
self.__index = self
-- set weight[1] and [2] and [3] to random values for this perceptron
self.weight[1] = math.random(1,10)
self.weight[2] = math.random(1,10)
self.weight[3] = math.random(1,10)
return o
end
p1 = inputperceptron:new()
p2 = inputperceptron:new()
print(p1.weight[1],p1.weight[2],p1.weight[3])
print(p2.weight[1],p2.weight[2],p2.weight[3])
print(p1.weight[1],p1.weight[2],p1.weight[3])
p1.weight[1] = p2.weight[2] but they should be random.
p2 is overwriting p1 meaning I'm instantiating a single instance of .weight when I should be instantiating a new instance of .weight with each inputperceptron. How to fix? I'm sure it's a simple syntax thing.
inputperceptron = {}
inputperceptron.__index = inputperceptron
function inputperceptron:new(o)
o = o or {}
setmetatable(o,self)
o.weight = {}
-- set weight[1] and [2] and [3] to random values for this perceptron
o.weight[1] = math.random(1,10)
o.weight[2] = math.random(1,10)
o.weight[3] = math.random(1,10)
return o
end
Or alternatively (if you prefer to use the 'self' keyword for the object you're instantiating)
inputperceptron = {}
inputperceptron.__index = inputperceptron
function inputperceptron:new(o)
local self = o or {}
setmetatable(self,inputperceptron)
self.weight = {}
-- set weight[1] and [2] and [3] to random values for this perceptron
self.weight[1] = math.random(1,10)
self.weight[2] = math.random(1,10)
self.weight[3] = math.random(1,10)
return self
end
In your original code, you were basically using the 'self' keyword to modify the class itself, rather than the class instance you were creating. So in the end all objects you would get with :new() had a reference to the exact same 'weight' table.