Lua_PushLightUserData - Intentionally Sending Nil?

BlitzMax Forums/BlitzMax Programming/Lua_PushLightUserData - Intentionally Sending Nil?

Gabriel(Posted 2009) [#1]
When I request a BlitzMax object from lua, I send the integer handle to it as LightUserData and then store it in a table in lua. That table has a bunch of functions added to it in lieu of methods and it is distributed in Lua as an object you can work with. Whenever it does anything in BlitzMax it sends the LightUserData back and BlitzMax finds the object it represents. Easy.

Except that Lua may occasionally ask for an object that doesn't exist. Up until now I've been using additional functions to check that an object exists before requesting it, but for some operations this effectively doubles the execution time needlessly. So I'd like to be able to shortcircuit this technique at some point.

So if I request an object which does not exist, I'd like to send userdata that's clearly invalid. Then Lua can check the userdata is nil, and not create the table, returning nil instead. Then the lua scripts can simply check if the "object" they're using is nil or not. But I can't get it to work. If I send a Null Byte Ptr, it is not detected as nil by Lua. Now I remember someone telling me that Null pointers have a specific address, and do not show as NULL in C++,so they probably don't show as nil in Lua either. So I made the lightuserdata equal to Byte Ptr(0) instead but this also isn't detected as nil.

How can I intentionally send something as lightuserdata that Lua will detect as nil?


N(Posted 2009) [#2]
If you push a light userdata, it's just going to push an address, so it's not going to push nil in lieu of an address even if it's Null (as it would be in C++ or BlitzMax). If you want nil, you have to push nil, simple as that. If you want to push Null as BlitzMax will see it, push something like this:

Strict

Private
Function p2p:Byte Ptr(p:Byte Ptr) NoDebug
	Return p
End Function

Public
Function ObjToPtr:Byte Ptr(obj:Object)
	Global o2p:Byte Ptr(o:Object)=Byte Ptr(p2p)
	Return o2p(obj)
End Function

Function NullObject:Byte Ptr()
	Return ObjToPtr(Null)
End Function

lua_pushlightuserdata(NullObject())



Gabriel(Posted 2009) [#3]
Ack, I didn't realize there was a Lua_PushNil function. The BlitzMax NullObject pushing will come in very handy too. Thanks Noel.