Re: How to create another lua_State in pthread?

  • From: Mike Pall <mike-1301@xxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Wed, 23 Jan 2013 23:30:10 +0100

Wolfgang Pupp wrote:
> Henk Boom wrote:
> > I couldn't find a way to get the returned callback through the lua API
> I used lua_tointeger for this (not completely sure if it'd work with a
> LuaJIT x64 build).

It does, because lua_Integer is a ptrdiff_t per luaconf.h, which
is an int64_t on x64.

> Ran into some (surprising to me) quirks though:
>     print(ffi.cast('ptrdiff_t', 5))      --> cdata<int>: 0x...
>     print('ptrdiff_t[1]', 5)[0]) --> 5
>     print('ptrdiff_t', 5)+0)     --> 5LL
> I can understand why the cast would give me a boxed int instead of a
> number-- I asked for it, after all, and the documentation says that
> C->Lua type conversions only happen with return values from FFI-function
> calls (or when dereferencing, thus case 2).

The canonical way to convert a cdata pointer to a Lua number is:

  tonumber(ffi.cast('intptr_t', ffi.cast('void *', ptr)))

This returns a signed result, which is cheaper to handle and turns
into a no-op, when JIT-compiled. If you really need an unsigned
address (and not just an abstract identifier), then use uintptr_t.

> But I don't understand why I'm getting a different result for the third
> case (a boxed int64). Can someone explain?

ptrdiff_t is an int32_t on your platform and cdata number
arithmetic coerces to int64_t/uint64_t. Only the 64 bit types have
a tostring() metamethod that shows them as LL/ULL.

[It's rarely helpful to operate on isolated, boxed 32 bit ints.
They occur only as results of casts or as boxed enums. Plain Lua
numbers work just as well.]


Other related posts: