You don't have to do this.
When player logout, reloadui, change cvar or get kicked for inactivity, saved variables are automatically saved. there's nothing to do.
You must not prehook or use those events if it's for saved variables usage.
For people who want to to this, here's how I do :
At ADD_ON_LOADED :
- I set a flag, this one goes to saved var. it will be used to guess at next ADD_ON_LOADED what kind of exit user did. If there's nothing to do at next add_on_loaded specifically for this kind of exit, don't do this.
Lua Code:
-- ex: inactivity = 1, reloadui = 2, logout = 3, setCvar = 4, quit = 5
local myaddon.db.exitMethod = 1
-- then I prehook :
-- PreHook ReloadUI, LogOut & Quit
ZO_PreHook("ReloadUI", function()
myaddon.db.exitMethod = 2
myaddon.doThingsAtReloadUI()
end)
ZO_PreHook("Logout", function()
myaddon.db.exitMethod = 3
myaddon.doThingsAtLogOut()
end)
ZO_PreHook("SetCVar", function()
myaddon.db.exitMethod = 4
myaddon.doThingsAtSetCVar()
end)
ZO_PreHook("Quit", function()
myaddon.db.exitMethod = 5
myaddon.doThingsAtQuit()
end)
-- then at ADD_ON_LOADED, just before setting the flag, I read value.
if myaddon.db.exitMethod == 1 then
-- last exit was a reloadui, so I do things specificaly at addon startup after a reload.
myaddon.reloadThings()
end
But I repeat, if it's just only to save things on SavedVars, do not use this trick.
It's mainly used for addons which store things per session and don't want thoses ones being resetted after a reloadui or a characer change.
typical example : the chatbox being wiped, or stats. (KillCounter is a very good exemple too). some DPS meter could use this too but it's less important.