Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
685 views
in Technique[技术] by (71.8m points)

oop - Use table variable in Lua class

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 = {}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...