在Lua类中使用表变量 [英] Use table variable in Lua class
问题描述
我需要一个Lua类中的表变量,该变量对于该类的每个实例都是唯一的.在下面列出的示例中,变量self.element似乎是一个静态变量,所有类实例都使用该变量.
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.
如何更改testClass以获得非静态的self.element表变量?
How do I have to change the testClass to get a non static self.element table variable?
示例:
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)
此实现返回:
$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
我需要的最后一个输出
Size: 3
Elements: E1 a
推荐答案
您在:new
函数中犯了一个常见错误.
You are making a common mistake in your :new
function.
您分配了 self.element
,但这应该是 o.element
.此函数中的 self
引用 testClass
表,而不是您正在创建的对象.为了使 element
对每个对象都是唯一的,您需要将其分配给正在创建的对象 o
.
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
这篇关于在Lua类中使用表变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!