Well, as with a lot of these things, there are many ways of doing it. The best way can depend on the complexity of what you are trying to achieve.
For a few simple variables, simply setting a variable in the plugin will guarantee it is saved at the end of one session, and restored at the start of another, eg.
SetVariable ("mobs_killed", 22)
This happens if you ticked the "save state" box when making the plugin, which should result in something like this at the start of your plugin file:
<muclient>
<plugin
name="Count_Mobs_Killed"
author="Nick Gammon"
id="f11e3bb0e48d526152798439"
language="Lua"
purpose="Counts how many mobs I have killed"
save_state="y"
date_written="2008-01-08 15:17:18"
requires="4.00"
version="1.0"
>
However this gets a bit tedious if you have lots of things to save, like a table of mobs and how many of them you killed. Now you have to record the mob name, when it died (maybe), and how many you killed. You soon start using up lots of individual variables that way. This is where serialization helps, as it turns a whole table into a single string.
Now (as described near the bottom of the first page of http://www.gammon.com.au/forum/?id=6030) you can simply turn the whole table into a single string.
For example, the killed mobs might look like this:
killed_mobs = {
Tiopon = {
count = 3,
last_time = 1236234406,
},
naga = {
count = 3,
last_time = 1236234406,
},
kobold = {
count = 3,
last_time = 1236234406,
},
someone = {
count = 25,
last_time = 1235851630,
},
}
Now by assigning that string to a MUSHclient variable, the entire table gets saved. You could do that in a plugin like this:
require "var"
require "serialize"
function OnPluginSaveState ()
var.killed_mobs = "killed_mobs = " .. serialize.save_simple (killed_mobs)
end --- function OnPluginSaveState
So, whenever the plugin saves its state, your entire table is saved.
We need another function to make sure the table is restored next time the plugin loads:
-- load data from variable in state file into a Lua table
function OnPluginInstall ()
assert (loadstring (GetVariable ("killed_mobs") or "")) ()
killed_mobs = killed_mobs or {} -- ensure table exists
end -- function OnPluginInstall
Quote:
... they get saved into a... not sure, something, that saves between sessions... Another single variable? Into the plugin itself?
The plugin itself is treated as read-only. This is because plugins might be shared between multiple worlds. However if you have "save_state" checked, then each plugin automatically writes a "state" file when it saves or closes. Effectively, this saves any plugin variables to a disk file that is identified by concatenating the plugin ID with the world ID, giving a unique filename for each world, for each plugin.
|