首页 > 解决方案 > 在 Lua 中实现类的最有效方法是什么?

问题描述

高效,我的意思是性能方面。如果您必须快速访问类成员,例如在绘制 UI 时,索引它们的最佳方法是什么?

我的理解是基于表的类使用更少的内存并且创建实例的速度更快,而基于闭包的类具有更快的函数调用,并且让您拥有可以快速索引的私有字段,因为它们存储为上值。对于像下面的示例类这样的情况,最好的实现是什么?

-- Example of Table-based Class

local class = {}
class.x = 0
class.y = 0
class.w = 0
class.h = 0

-- Draw would be called for potentially dozens of instances many times per second
function class:Draw()
    draw_rect(self.x, self.y, self.w, self.h)
end
-- Example of Closure-based class

local function class(_x, _y, _w, _h)
  -- the new instance
  local self = {
    -- public fields
    visible = false
  }

  -- private fields are locals
  local x, y, w, h = _x, _y, _w, _h

  function self.SetPos(_x, _y)
    x = _x
    y = _y
  end

  function self.GetPos()
    return x, y
  end

  function self.GetVisible()
    return self.visible
  end

  -- return the instance
  return self
end

local obj = class(10, 20, 40, 80)
print(obj.GetPos()) --> 10, 20

obj.SetPos(50, 100)
print(obj.GetPos()) --> 50, 100

obj.x = 21
obj.y = 42
print(obj.GetPos())  --> 50, 100 (unchanged, private)

obj.visible = true
print(obj.GetVisible()) -- true (public)

标签: lua

解决方案


推荐阅读