How to loop over a Table collection?

I’m using a Table collection because

  • I need a (key, value) map
  • I don’t know the amount of keys I will have during runtime.

Now I would like to loop over the table to update all the values.
How do I do this?
Do I need a different collection?
dev_cheat_sheet - Sui move collection decision tree

3 Likes

Solution:
If you want a collection with:

  • a (key, value) map

  • 1000+ items

  • the possibility to loop the table

    – > LinkedTable

code example:

use sui::linked_table::{Self, LinkedTable};

...

let table_x = linked_table::new(ctx)

...

let key_i = linked_table::front(&table_x); // Returns the key for the first element in the table, or None if the table is empty
while(option::is_some(key_i)) {
   let k = *option::borrow(key_i); // option::borrow - returns an immutable reference to the value inside the Option
   let v = linked_table::borrow_mut(&mut table_x, k);
   *v = 0; // update the u64 value of the key k to 0 in the LinkedTable table_x
   key_i = linked_table::next(&table_x, k);
}

Credit to @josemvcerqueira of Interest Protocol for pointing me in the right direction on Telegram

4 Likes