title: Efficient custom datatype in Lua
body: <p>I need a 2d vector-like data structure for use in Lua. So far I've found several solutions to this problem:</p>
  
  <ol>
  <li>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.</li>
  <li>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.</li>
  <li>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?</li>
  </ol>
  
  <p>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.</p>
  
  <p>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).</p>
  
  <p>Which of the two methods would be more efficient? Are there any pitfals I havn't thought about in those cases?</p>