1

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?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Kornel Kisielewicz
  • 55,802
  • 15
  • 111
  • 149
  • 3
    Do you **know** #1 is too slow? –  Apr 25 '11 at 15:01
  • @delnan, I know the two golden rules of optimizing Lua ;). Also, moving away from #1 is also dictated by other reasons (deployment of the structure from C level, and others). – Kornel Kisielewicz Apr 25 '11 at 15:21
  • 2
    Can you put your #1 implementation somewhere? Maybe it wasn't that optimal. – kikito Apr 25 '11 at 17:53
  • Lua Gems had a recipe for a numeric array and vector data type built in C and stored in `userdata`. The code wasn't *that* complex, with most of the complexity due to dealing with housekeeping, the ability to see rows and columns of a matrix as a vector without copying data, and so forth. That was Chapter 16, A Primer of Scientific Computing in Lua. Probably worth a look. – RBerteig Nov 22 '13 at 19:24

1 Answers1

3

Option #4: use LuaJIT2 with FFI

See related work

Doug Currie
  • 40,708
  • 1
  • 95
  • 119
  • +1: wow, while it LuaJIT isn't something I can use (not all target architectures are supported) this is a very interesting link indeed, thanks! – Kornel Kisielewicz Apr 25 '11 at 23:57