Lua 中高效的自定义数据类型
我需要一个类似二维向量的数据结构,以便在 Lua 中使用。到目前为止,我已经找到了解决这个问题的几种解决方案:
- 在纯 Lua 中定义数据类型的经典解决方案 - 缺点是对其进行的所有操作(例如加法)都需要创建新的数据类型,设置元表等。 x, y存储为字段,因此可以快速访问。
- C端的经典完整用户数据解决方案——它可能更快,仍然允许运算符,操作代码是C端,但每个操作仍然需要分配一个新对象。但不存在字段的可能性,因此需要执行自定义 __index/newindex 函数来模拟 x 和 y,这在 Lua 方面可能会很慢。
- 混合方法,我们定义一个 Lua 对象,但通过 C 代码,x 和 y 仍然是具有简单访问的字段,但函数将用 C 编码,因此更快?
我确实尝试了#1 方法,由于效率问题,我计划转向#2 或#3,但我不知道哪一种更有效。
从长远来看,还可以在编译器本身中对数据类型进行硬编码,但我认为我还没有准备好接受如此激进的想法:)(这并不像听起来那么疯狂,一个 2d 向量会很好适合本地 Lua 类型的双倍大小)。
这两种方法中哪一种更有效?在这些情况下是否有我没有想到的陷阱?
I need a 2d vector-like data structure for use in Lua. So far I've found several solutions to this problem:
- Classic solution of defining the datatype in pure Lua -- the disadvantage is that all operations on it (like addition) need to create a new datatype, set metatables, etc. x, y are stored as fields, and hence have fast access.
- Classic full userdata solution on C-side -- it might be faster, still allows operators, operation code is C side, but still every operation needs to do a allocation of a new object. There is no possibilities of fields though, so one would need to do a custom __index/newindex function to simulate x and y what might be slow on Lua side.
- Hybrid approach, where we define a Lua object but through C code, x and y would still be fields with simple access, but the functions would be coded in C, hence faster?
I did try the #1 approach and due to efficiency issues I plan to move to either #2 or #3, however I don't know which one would be more efficient.
On the far side there's also the possibility to hardcode the datatype in the compiler itself, but I don't think I'm ready yet for such drastic ideas :) (this isn't as crazy as it sounds, a 2d vector would nicely fit in the double size of a native Lua type).
Which of the two methods would be more efficient? Are there any pitfals I havn't thought about in those cases?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
选项#4:使用 LuaJIT2 和 FFI
查看相关工作
Option #4: use LuaJIT2 with FFI
See related work