[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Comparing userdata to 0 in Lua 5.0
- From: RLake@...
- Date: Thu, 6 Nov 2003 10:46:54 -0500
> Here's a question you will likely find trivial. It appears to
> be generating talk at work...
> What happens when one compare's userdata with the value 0
> (or any other number for that matter) in Lua?
Lua returns false.
> function foo()
> local pointer1 = GetSomePointerFromC();
> local pointer2 = GetSomeOtherPointerFromC();
> if (pointer1 == 0) then
> -- pointer is NULL.
Nope, this will only be executed if pointer is the LuaNumber 0
> elseif (pointer1 == pointer2) then
> -- addresses are the same.
The equality test will work the way you expect on lightuserdata.
> More precisely, is it safe (and correct) to compare a pointer
> (lightuserdata) with the number 0 in order to determine if it's NULL?
Safe, yes. Correct, no.
> If not, what would be the correct way to determine whether a pointer
> from C is NULL or not? Would a IsPointerNULL() C function be
I'd create a lightuserdata with the value NULL. Then you could just do
Note: There is no guarantee that a lightuserdata is a pointer at all.
It could be anything which fits into a long. The semantics are not
visible to Lua; it is sort of like a void* in that respect (which
might also be cast from an integer, for example.)