View Single Post
Old 06-01-05, 08:15 AM   #3
Gello
A Scalebane Royal Guard
AddOn Author - Click to view addons
Join Date: Jan 2005
Posts: 430
SavedVariables is really simple. In the .toc, add this line:

## SavedVariables: myvariable

That's all there is to it. The value of myvariable will persist across sessions. How it works is pretty neat:

1. When you log in, each mod's lua gets "run" once.
specifically: from the <Script file="mymod.lua"/> line, WoW runs this file. It doesn't execute functions, but it picks up all version=1.0, stuff=etc that you define outside of functions
2. After the loading chugs a bit, the game "runs" the SavedVariables.lua file.
specifically: open SavedVariables.lua and you'll see a bunch of variable declarations. WoW doesn't "interpret" this file, it just runs it. While logged out, you could edit the file to add your own code and it'd run when you log back in.
3. When the game closes, it deletes SavedVariables.lua, then goes through all addons' .toc files to recreate it.
specifically: It goes through every .toc and if it sees ## SavedVariables (something), then it adds (something) into SavedVariables.lua in a form that can be run the next time a character logs in.

This is why your mod can say:
--MyMod.lua--
Code:
x=100

function MyMod_OnUpdate()
    --etc
end

functon MyMod_OnEvent()
    --etc
end
Then in game you do /script x=900. Then the next time you run it will stay 900 despite clearly saying x=100. It runs MyMod.lua and makes x=100. Later, it runs SavedVariables.lua. If there's an x=900 there, x will now be 900.

That's all you need to know, except to remember that SavedVariables.lua is always run just before the VARIABLES_LOADED event. So if you ever want to act on a saved variable at startup, make sure to put it there:

--MyMod.lua--
Code:
x=100

function MyMod_OnUpdate()
    this:RegisterEvent("VARIABLES_LOADED");
end

functon MyMod_OnEvent()
    if event=="VARIABLES_LOADED" then
       x = whatever x was when the user last logged out
    end
end
So to tweak the above a bit:

Code:
DS_UsedBefore = false

function DS_OnLoad()
    this:RegisterEvent("VARIABLES_LOADED")
end

function DS_OnEvent()
    if event=="VARIABLES_LOADED" then
        if not DS_UsedBefore then
            -- do one-time stuff for first use
            DS_UsedBefore = true
        end
    end
end
Gello is offline   Reply With Quote