Saving and loading
HaasScript provides a way to save values between runs of a script using the Save()
and Load()
commands. This can be useful for persisting data such as configuration settings, user preferences, or even trading strategies.
Saving Values
To save a value, use the Save()
command with a key and a value:
Save('myKey', 42)
The key should be a string, and the value can be any valid Lua value. The saved value will be associated with the key and stored in a database. This value will persist between script runs until it is overwritten or deleted.
Loading Values
To load a saved value, use the Load()
command with a key and a default value:
myValue = Load('myKey', 0)
If a value is saved for the specified key, it will be returned. Otherwise, the default value specified (in this case, 0) will be returned.
Example Usage
Here’s an example of how you might use the Save()
and Load()
commands to persist a configuration setting between script runs:
-- Load the previous value of mySetting, defaulting to false if not found
mySetting = Load('mySetting', false)
-- ... use mySetting in your script ...
Log( mySetting and 'true' or 'false' ) -- Print the value
mySetting = not mySetting -- Flip from true to false/false to true
-- Save the updated value of mySetting for the next script run
Save('mySetting', mySetting)
With this code, the initial value of mySetting
will be loaded from the database, or it will default to false
if no value has been saved yet. The script can then use mySetting
as needed, and the final value will be saved to the database for use in the next script run.
Limitations
It’s important to note that the Save()
and Load()
commands are specific to the script instance that created them. If you have multiple scripts running simultaneously, each one will have its own set of saved values. Additionally, saved values are not shared between different HaasScript installations or between different machines.