在 Lua 类中使用表变量 [英] Use table variable in Lua class

查看:26
本文介绍了在 Lua 类中使用表变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个 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

对于我需要的最后一个输出

For the last output I need

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆