lua - 在 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)
解决方案
推荐阅读
- c++ - 字符串和双精度的 C++ 重叠输出
- unicode - 为什么我的 Alt+164 给我 ♫ 而不是 ñ?
- android - 如何在android studio中实现语音气泡的xml文件,他们会调整自己的大小吗?
- vb.net - 有人在 Visual Studio 2019 中发布时遇到这种错误吗?VB.NET 语言
- c# - c# 如何使符号保持打开控制台(记忆游戏)
- reactjs - 找不到模块:无法解析 '*.module.scss'
- php - 如何在wordpress的类别页面下隐藏帖子列表?
- swift - 如何在组合布局中创建弹性标题?
- linux - 获取每秒总计数的命令
- r - 如何更优雅地分组我的数据框