RCBasic UDTs [RCBasic Doc]

## USER DEFINED TYPES (UDTs)

RCBasic v4 and up introduces the ability to create user defined types. These are basically structures that allow you to store and manage related data. To create a user defined type you need to use the TYPE keyword. Look at the following:

`Type player
Dim x, y
End Type
`

In the above code, a type called player is created. The DIM keyword must be used to add attributes to our type. Now we can create a variable with the data type player as follows:

`Dim hero As player
`

Notice that in the above code, we are using the DIM keyword we have used in previous sections to create variables and arrays. We now have a variable called hero whose data type is player.

Since our hero variable is of type player, it has all the attributes of that type. So we can access the attribute's with a "." like so:

`hero.x = 23
Print "Hero x is "; hero.x
`

The attributes of a UDT variable are accessed the same way a normal variable is. You can also create an array of UDT's the same way you would create a normal array. Look at the following:

`Dim enemy[20] As player
`

If you read through the section on arrays then this should make sense. We are using the DIM keyword to make an array called enemy and then we use the AS keyword to set the type of enemy to player.

UDTs can also be used for attributes inside other UDTs. Lets say we wanted each player to have stats like health and power. We could create a UDT for player stats and have an attribute of that stat type inside our player UDT. Here is that example demonstrated:

`Type Player_Stats
Dim health
Dim power
End Type
Type Player
Dim x, y
Dim stats As Player_Stats
End Type
Dim hero As Player
`

In the above example, hero now has an attribute called stats that is of type Player_Stats. So now we can access the stats attributes like so:

`hero.stats.health = 100
Print "Hero Health = "; hero.stats.health
`

If used effectively, you can drastically increase the readability and maintainability of your code. Especially in large projects.