Cleanup functions for MaxLua

BlitzMax Forums/BlitzMax Module Tweaks/Cleanup functions for MaxLua

dan_upright(Posted 2014) [#1]
If you want the ability to remove objects created with RegisterLuaObject and/or close the lua state, make the following changes in brl.mod/maxlua.mod/maxlua.bmx.

First change the LuaState function to this:
Function LuaState:Byte Ptr(reset:Int = False)
	Global _luaState:Byte Ptr
	If reset And _luaState Then
		lua_close(_luaState)
		_luaState = Null
	End If
	If Not _luaState
		_luaState=luaL_newstate()
		luaL_openlibs _luaState
	EndIf
	Return _luaState
End Function

Then add the following two functions at the bottom of the file:
Function LuaDeregisterObject(name:String)
	lua_pushnil(LuaState())
	lua_setglobal(LuaState(), name)
End Function

Function LuaShutdown()
	LuaState(True)
End Function

Then you can remove a previously registered object with LuaDeregisterObject or close the current lua state with LuaShutdown (it'll automatically open a new state the next time you use any maxlua commands).


dan_upright(Posted 2014) [#2]
As an aside to this, I didn't do anything for cleaning up after TLuaObject or TLuaClass types because they already handle it themselves during garbage collection. If you want to force the issue, do this:
myTLuaClassOrObject = null
GCCollect()



dan_upright(Posted 2014) [#3]
Ok, so I wasn't entirely happy about leaving objects and classes without tidying functions so I added this at the bottom of maxlua.bmx:
Function DeleteLuaObject(o:TLuaObject Var)
	o = Null
	GCCollect()
End Function

Function DeleteLuaClass(c:TLuaClass Var)
	c = Null
	GCCollect()
End Function

So you can clean them up by calling:
DeleteLuaObject(myTLuaObject)
DeleteLuaClass(myTLuaClass)

Of course, if you're freeing up a lot of objects/classes at once, it'd be more efficient to just set them all to null and call GCCollect yourself but the simpler option is there now anyway.