# storage operation

# A brief introduction to storage

Each smart contract can store and query some state data in the blockchain. This function is called storage.

In the API function in a contract, you can use self.storage to get the storage object of the current contract. The contract loaded by import_contract is not allowed to directly read and write its storage

Storage object can be similar to table operation, read attributes, write attributes, but can only nest at most one layer table, and storage [a certain attribute name] value is a certain type, modify the value of this attribute can only be changed to the same The value of the type, if storage[a certain attribute name] is a table, the type of the value of different attributes in this table should be the same, for example, all are integers or all strings.

Storage modification operations are not submitted immediately, but when the current lua stack is closed, if there are no errors, the storage changes are automatically submitted (only the changes are submitted instead of the storage itself)

# Basic types of storage

the type of each attribute storage may be used int, number, bool, string, Stream, Map<int>, Map<number>, Map<bool>, Map<string>, Array<int>, Array<number>, Array<bool>, Array<string>these types

Storage operations such as:

self.storage.name = "hi"
self.storage.age = 123
self.storage.name = 456 -- Error, type cannot be changed
let abc = self.storage.age -- Correct, read the storage attribute value
self.storage.tt = {name: "hi", age: 2} -- Error, the type of the attribute value of the nested table should be the same
self.storage.tt = {name: {name: "hi"}} -- Error, multiple layers of nested table in storage are not allowed
self.storage.tt = {name: "hi", age: "2"} -- Correct

# fast map storage

The map/array type in storage directly loads the entire map/array into memory when it is used, and is only suitable for smaller maps/arrays. If you want to use a larger map/array, please use fast map storage

The storage of the fast map type is not directly defined in the storage type definition, but is directly read fast_map_get and fast_map_set written with the sum function. When using fast map to read and write, only the item that is accessed is loaded in memory, so that when fast map is large, only a small amount of memory is required.

such as:

print("test_fastmap begin")

var a1 = fast_map_get('balances', 'user1')
print("a1: ", a1)

fast_map_set('balances', 'user1', 123)
var a2 = fast_map_get('balances', 'user1')
print("a2: ", a2)


fast_map_set('balances', 'user1', 234)
var a3 = fast_map_get('balances', 'user1')
print("a3: ", a3)

fast_map_set('balances', 'user2', 'world')
var b1 = fast_map_get('balances', 'user2')
print('b1: ', b1)

fast_map_set('balances', 'user2', nil)
var b3 = fast_map_get('balances', 'user2')
print('b3: ', b3)


fast_map_set('balances', 'user1', 'hello')


var a4 = fast_map_get('balances', 'user1')
print("a4: ", a4)

print("test_fastmap end")