lua-users home
lua-l archive

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


> Here's a question you will likely find trivial. It appears to
> be generating talk at work...

Easy, perhaps.

> What happens when one compare's userdata with the value 0
> (or any other number for that matter) in Lua?

Lua returns false.

> Example:

> 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.
>    end
> end


> 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 
recommended?

I'd create a lightuserdata with the value NULL. Then you could just do
the comparison.

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.)

Thanks!