Use table variable in Lua class

送分小仙女□ 提交于 2021-02-13 17:02:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!