User Tools

Site Tools


Key-value storage

Key-value storage is a simple database that you can use to store any data using your scripts. It is useful when you need to save settings, parameters, counters, flags, etc. Values are being stored in backups as well. So they will be restored on backup restore.

This storage was added in WebHMI version 3.4.

You can address your values by special identifier - key. Key is a string that will identify your value in storage. Value could be a bool, number, or string type. If you need store tables you can use lua-cjson library to serialize/deserialize your table to/from string. See below for example.

There are two special functions to work with this storage: Get and Set.

Set(key, value)

The Set function saves value into key-value storage. key is an identifier of value. value is a data that you want to save to storage.

Function returns true on success and false if any error occurred.

Example:

function main (userId)
    if (Set("my permanent variable", 42) == false) then
       ERROR("Can't save data to storage.");
    end
end  

Get(key)

The Get function fetches data from key-value storage. key is an identified of value. The result of this function would be either value if it exists in storage or nil if value was not found.

Example:

function main (userId)
    local val = Get("my permanent variable");
 
    TRACE("val = " .. val);
end  

Save tables into storage

You can use lua_cjson library to encode tables into strings. This will allow save them into storage.

Here is example:

local val = Get("local2");
if (val ~= nil and val ~= "") then
    val = cjson.decode(val);
else 
    val = {};
end
 
function main (userId)
    if val[10] == nil then
         val[10] = 1;
    end
    val[10] = val[10] + 1;
    Set("local2", cjson.encode(val));
    ERROR(val[10]);
  -- Add your code here
end  

Page Tools