Types and Objects

This page explains LunarBasic's user-defined type system. Use Type blocks to describe object data, Dim ... As TypeName to declare object variables, and New to allocate objects.

Back to Language Reference


Declaring a Type

Types are declared at the top level of a source file.

Type Player
    Field Name As String
    Field Score As Integer
End Type

Declaring Variables

Object variables are declared with Dim and an As type clause.

Type Player
    Field Name As String
    Field Score As Integer
End Type

Dim currentPlayer As Player
Dim backupPlayer As Player

Allocating Objects

Use New <TypeName> to create an object instance.

currentPlayer = New Player
backupPlayer = New Player

New is an expression, so it can be assigned anywhere a value is allowed.

Declaring a variable with Dim currentPlayer As Player does not allocate the object by itself. You still need currentPlayer = New Player before using fields on that object.

Releasing Objects

Use Free when you are done with an object that was created with New.

Dim currentPlayer As Player
currentPlayer = New Player
currentPlayer.Name = "Luna"
Free(currentPlayer)

Free is for user-defined type objects. It is not used for runtime asset handles such as images, sprites, or fonts.

Free releases that one object instance. If the object contains fields that point to other objects created with New, free those nested objects separately first if you no longer need them.

For built-in runtime-owned object graphs (such as TiledMap returned by LoadTiledMap), free only the root object unless documentation for that API says otherwise.

After calling Free, do not read or write fields through that value again unless you assign a new object to it first.

Built-in Tiled Structures

LunarBasic also provides built-in object types for Tiled maps: TiledMap, TiledLayer, TiledObject, TiledTileset, and TiledProperty.

Load a map with LoadTiledMap, then access nested data using the same field and array syntax as your own types.

Dim map As TiledMap
Dim layer As TiledLayer

map = LoadTiledMap("assets/maps/level1.tmx")
If map <> Null Then
    DebugPrint "Layer count: " + Str(map.LayerCount)
    If map.LayerCount > 0 Then
        layer = map.Layers[0]
        DebugPrint layer.Name
    End If
    Free(map)
End If

For more details, see LoadTiledMap in the System Functions reference.

Accessing Fields

Fields can be read or written with either member-access style.

currentPlayer.Name = "Luna"
currentPlayer.Score = 100
backupPlayer\Name = "Nova"
backupPlayer\Score = 75

Nested Types

A field can use another user-defined type.

Type Position
    Field X As Integer
    Field Y As Integer
End Type

Type Player
    Field Name As String
    Field Location As Position
End Type

Dim currentPlayer As Player
currentPlayer = New Player
currentPlayer.Location = New Position
currentPlayer.Location.X = 320
currentPlayer.Location.Y = 200

Current Rules

Common Errors