Re: structure pointers and metatypes using ffi

  • From: Mike Pall <mike-1205@xxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Mon, 14 May 2012 14:59:15 +0200

Daurnimator wrote:
> What if pointer types could have a default metatable?
> That is, if all pointer types came with a metatable where __add
> implemented point arithmetic;
> But a developer could set a new metatable; implementing their own (non
> pointer arithmetic) __add metamethod.
> 
> We seem to do without a range of raw* functions in lua as it is
> (though I admit, I sometimes miss them)

We can do without that because the basic operations on basic types
cannot be overriden. You can't override arithmetic on numbers or
string concatenation. A pointer is to the FFI what a number is to
plain Lua: a basic type.

You've stubled upon a key design aspect of Lua. If you add two
numbers, you get exactly what you expect. Period. There's just no
place for surprises, which is a good thing. Also, checking a
metatable for every number addition would be slow, very slow.

Read upon computer language design history a bit and you know why
those decisions were made. The seductive idea to 'let everyone
override every basic behavior globally' was tried and just doesn't
work well in practice. Apart from dashing all hope for modularity,
it leads to incomprehensible programs with unexpected side-effects.
And to slow implementations that have to use tons of tricks to
(partially) mitigate the effects of bad abstractions.

> It is low level, but needing to wrap pointers in a table or struct or
> some such to implement metamethods seems like a waste...

Use p[0] to get the struct metamethods. That's all. You can even
'lie' to the FFI about APIs with 'void *' pointers. Just declare
them as pointers to an opaque struct on the Lua side.

--Mike

Other related posts: