问题
I need a table variable in a Lua class, which is unique for each instance of the class. In the example listed below the variable self.element seems to be a static variable, that is used by all class instances.
How do I have to change the testClass to get a non static self.element table variable?
Example:
local testClass ={dataSize=0, elementSize=0, element = {} }
function testClass:new (data)
local o = {}
setmetatable(o, self)
self.__index = self
-- table to store the parts of the element
self.element = {}
-- data
self.element[1] = data
-- elementDataSize
self.elementSize = #data
return o
end
function testClass:getSize()
return self.elementSize
end
function testClass:addElement(data)
-- add data to element
self.element[#self.element+1] = data
self.elementSize = self.elementSize + #data
end
function testClass:printElement(element)
-- print elements data
element = element or self.element
local content = ""
for i=1, #element do
content = content .." " .. tostring(element[i])
end
print("Elements: " .. content)
end
function printAll(element)
print("Size: " .. tostring(element:getSize()))
element:printElement()
end
test = testClass:new("E1")
printAll(test)
test:addElement("a")
printAll(test)
test2 = testClass:new("E2")
printAll(test2)
test2:addElement("cde")
printAll(test2)
print("............")
printAll(test)
This implementation returns:
$lua main.lua
Size: 2
Elements: E1
Size: 3
Elements: E1 a
Size: 2
Elements: E2
Size: 5
Elements: E2 cde
............
Size: 3
Elements: E2 cde
For the last output I need
Size: 3
Elements: E1 a
回答1:
You are making a common mistake in your :new function.
You assign self.element but this should be o.element. self in this function refers to the testClass table not to the object you are creating. To make element unique to each object you need to assign it to o, the object being created.
function testClass:new (data)
local o = {}
setmetatable(o, self)
self.__index = self
-- table to store the parts of the element
o.element = {}
-- data
o.element[1] = data
-- elementDataSize
o.elementSize = #data
return o
end
回答2:
In testClass:new() self refers to testClass.
local test = testClass:new()
test.element will refer to testClass.element
Your instance is o, so when you want each instance to have its own element replace self.element = {} with o.element = {}
来源:https://stackoverflow.com/questions/65561981/use-table-variable-in-lua-class