Variables, Constants, and Assignment

This page covers the main ways to store values in LunarBasic.

Back to Language Reference


Const

Use Const when a value should not change.

Const <declarator>[, <declarator>...] <name> [As <typeName>] = <expression>

Classic type suffixes also work here, so a name like title$ is treated as a String constant and count% is treated as an Integer constant.

Dim

Use Dim when you want to declare a variable, with or without dimensions.

Dim <declarator>[, <declarator>...] <name> [(<dimensionExpr>[, <dimensionExpr>...])] [As <typeName>]

Classic suffix typing works with Dim too.

If you also write an As type, it must match the suffix. For example, Dim name$ As String is valid, but Dim name$ As Integer is a compiler error.

As can also name a user-defined type declared with Type.

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

Dim currentPlayer As Player

If you want a full beginner-friendly explanation of array declarations and indexing, see Arrays.

Arrays at a Glance

Arrays are declared with dimensions in Dim, then used with index access.

Dim scores(10) As Integer
Dim currentScore As Integer

scores[0] = 100
currentScore = scores[0]

Assignment

Assignments use = at the top level of the statement.

Identifiers, members, indexes, and chained member/index targets are supported. Invocation results such as foo() = 1 are not valid assignment targets.

For objects created from a Type, assign fields through either member-access form. . is the recommended style, while \ is supported for compatibility.

currentPlayer = New Player
currentPlayer.Name = "Luna"
currentPlayer\Score = 100