Executing the script before game closing

I send the value of a variable to the .ini file, and I need it to be set to 0 when the game closes by any reason. Is this possible?
Well, you'd just need to rewrite the original file except for the last line, I suppose, where you simply print something like tag=0 and that's it.

Ruby:
lines = File.readlines("Game.ini")
lines.pop
file = File.open("Game.ini", "w")
file.puts lines
file.puts "NewTag=" + $game_variables[YourVariableID].to_s
file.close
Regarding "game closes by any reason":
The Ruby-interpreter that runs RPGXP-games was easily capable to catch the moment it gets closed, Ace on the other hand will absolutely enforce closing with no interruption when you click [✕].

~炬燵あ

Original thread: https://forums.rpgmakerweb.com/threads/executing-the-script-before-game-closing.161036/