lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

On Wed, Jun 20, 2012 at 04:49:34PM +0200, Thijs Schreijer wrote:
> > > and why cast it (incorrectly) as a lua_CFunction? Why not a boxed
> > userdata?
> > 
> > It is not incorrect. ANSI C ensures that all pointers to functions are
> > compatible. That is, if A and B are pointers to functions, we can
> > convert from A to B and back to A without loss. Now that Lua 5.2 has
> > light C functions, this looks like an interesting technique to store
> > pointers to functions in Lua (as long as Lua code has no access to
> > them).
> > 
> > -- Roberto
> You refer specifically to 5.2. Does this mean it cannot be done reliably in
> 5.1 using lightuserdata for example?

Standard C doesn't allow conversion between between object pointers and
function pointers. This code is undefined in C:

void *foo(void) { return (void *)&foo; }

See,, and of C99. Those are the sections which
would define the behavior, but they don't; and no other section does.

In practice most platforms allow this, and POSIX actually requires it:

	2.12.3 Pointer Types

	All function pointer types shall have the same representation as the
	type pointer to void. Conversion of a function pointer to void *
	shall not alter the representation. A void * value resulting from
	such a conversion can be converted back to the original function
	pointer type, using an explicit cast, without loss of information.

Lua, OTOH, strives to be a strict adherent to the church of ISO C. She may
fantasize about--and ocassionally indulge--inappropriate relations between
object and void pointers, but she knows it's wrong. Still, if your platform
allows these conversions, then Lua can't prevent it.