m
→VARIABLES_LOADED event: minor rewording
m (→Annoyances: This is the last time, I swear...) |
m (→VARIABLES_LOADED event: minor rewording) |
||
| Line 92: | Line 92: | ||
savedVar = f() -- will fail to save g | savedVar = f() -- will fail to save g | ||
== | == VARIABLES_LOADED event == | ||
When working with variables designated for saving, you should not initialized them with table values without paying attention to VARIABLES_LOADED event. Because, as explained in loading sequence above, file with saved variables is processed after code of your addon and because entire table is single value, if you define table with default values like this: | |||
tableName = { | tableName = { | ||
['key1'] = 'value1'; | ['key1'] = 'value1'; | ||
} | } | ||
and later alter the table to this: | and later alter the table in source to this: | ||
tableName = { | tableName = { | ||
['key1'] = 'value1'; | ['key1'] = 'value1'; | ||
['key2'] = 'value2'; | ['key2'] = 'value2'; | ||
} | } | ||
when your saved variables are loaded, saved value of table that have no 'key2' will overwrite table defined in source and, therefore, 'key2' won't have default value set. | |||
Correct way to initialize default values is to register for VARIABLES_LOADED event, test keys that you want to initialized if they are nil or not and write your default values. | |||
function AddOnName_OnLoad() | function AddOnName_OnLoad() | ||
| Line 117: | Line 113: | ||
function AddOnName_OnEvent(event) | function AddOnName_OnEvent(event) | ||
if event == 'VARIABLES_LOADED' then | if event == 'VARIABLES_LOADED' then | ||
if(not tableName.key1) then tableName.key1 = 'value1' end; | |||
if(not tableName.key2) then tableName.key1 = 'value2' end; | |||
end | end | ||
end | end | ||
Simple values, such as number or strings, still can be initialized without waiting for event if you do not require any additional checks or processing (because you'd be working on your hard-coded values, not on those read from saved file and all you work will be overwritten after that), but for sake of simple maintenance in case your initialization becomes more complex in future, it is advised to use registering for VARIABLES_LOADED event from beginning to save you rewrite or headache of catching elusive bugs later. | |||
[[Category: HOWTOs|Save Variables Between Game Sessions]] | [[Category: HOWTOs|Save Variables Between Game Sessions]] | ||