Efficient custom datatype in Lua

1.5k Views Asked by At

I need a 2d vector-like data structure for use in Lua. So far I've found several solutions to this problem:

  1. 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.
  2. 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.
  3. 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?

1

There are 1 best solutions below

1
On

Option #4: use LuaJIT2 with FFI

See related work