Variables, Constants, and Assignment
This page covers the main ways to store values in LunarBasic.
Const
Use Const when a value should not change.
Const <declarator>[, <declarator>...]
<name> [As <typeName>] = <expression>
- Const answer = 42
- Const greeting As String = "hello"
- Const x = 1, y As Integer = 2
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>]
- Dim counter
- Dim name As String
- Dim values(10, 20) As Integer
- Dim a, b(5), c As Float
Classic suffix typing works with Dim too.
- Dim name$
- Dim score%
- Dim velocity!
- Dim distance#
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]
- Use
()when declaring the array. - Use
[]when accessing an element. - Use commas for multiple dimensions, such as
board[x, y].
Assignment
Assignments use = at the top level of the statement.
- counter = 0
- foo.bar = 1
- foo\bar = 1
- foo[1, 2] = value
- foo.bar[1].baz = 2
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