Remember our Person struct in the previous example?
struct Person:
age: uint256
name: String[64]
people: HashMap[uint256, Person]Now we're going to learn how to create new Persons and add them to our people mapping.
// create a New Person:
Person vasa = Person({ name: "vasa", age: 22 })
// Add that person to the mapping with key `0`:
self.people[0] = vasaWe can also combine these together and do them in one line of code to keep things clean:
self.people[0] = Person({ name: "vasa", age: 22 })Notice that we are using self keyword to access the people (state) variable.
self is an environment variable used to reference a contract from within itself. self allows you to read and write to state variables and to call private (internal) functions within the contract. We will learn about external/internal functions in the next chapter.
self is used to access a contract’s state variables, as shown in the following example:
message: String[10]
@external
def setMessage(msg: String[10]):
self.message = msgself is also used to call internal functions within a contract:
@internal
def multiplyByTwo(amount: uint256):
amount * 2
@external
def calculate(amount: uint256):
self.multiplyByTwo(amount)Let's make our createPokemon function do something!
-
Remove the
passkeyword. Fill in the function body so it creates a newPokemon, and adds it to thepokemonListmapping with a key value of 0. Use the following values for the newPokemon:name: name (from function argument),dna: dna (from function argument),HP: HP (from function argument),matches: 0,wins: 0
-
Do not forget to use the
selfenvironment variable to accesspokemonListmapping. -
Let's do it in one line of code to keep things clean.