Skip to content
Himxh edited this page Oct 4, 2026 · 1 revision

数组 / Arrays

什么是数组 / What an Array Is

数组是一组相同类型的值,用下标访问。例如一个整数数组可以同时存放 5 个整数,用 arr[0] 到 arr[4] 分别读取或修改它们。

An array is a group of values of the same kind, accessed by index. An integer array can hold 5 integers, read or modified via arr[0] through arr[4].

数组适合"数量固定、同类元素"的场景:一排坐标、一组等级、一列玩家名。

Arrays fit "fixed count, same kind" scenarios: a row of coordinates, a set of levels, a list of player names.


声明数组 / Declaring an Array

声明数组时,方括号放在变量名之后,里面是元素个数:

When declaring an array, put the brackets after the variable name, with the element count inside:

int scores[5];          // 5 个整数,初始都是 0
double pos[3];          // 3 个小数
string names[10];       // 10 个字符串,初始都是 null

也可以同时给出初始值:

You may supply initial values at the same time:

int scores[5] = {10, 20, 30, 40, 50};
string names[3] = {"Steve", "Alex", "Herobrine"};

方括号里的数字可以省略,此时长度由初始值列表决定:

The count inside the brackets may be omitted; the length then comes from the initializer:

int scores[] = {10, 20, 30};        // 长度 3
string names[] = {"Steve", "Alex"}; // 长度 2

如果方括号里写了数字,同时也给了初始值列表,数字优先,多余或不足的元素会被补齐或忽略:

If both a count and an initializer are given, the count wins; elements are padded or dropped:

int a[5] = {1, 2, 3};       // {1, 2, 3, 0, 0}
int b[2] = {1, 2, 3, 4};    // {1, 2}

访问元素 / Accessing Elements

用 数组名[下标] 读取元素。下标从 0 开始:

Use name[index] to read an element. Indices are 0-based:

int scores[] = {10, 20, 30};
int first = scores[0];     // 10
int second = scores[1];    // 20
int last = scores[2];      // 30

修改元素:

Modify an element:

scores[0] = 100;            // 现在数组是 {100, 20, 30}
scores[1] += 5;             // 复合赋值也可以
scores[2]++;                // 自增也可以

越界会报错 / Out-of-Bounds Errors

下标必须在 0 到 size() - 1 之间。越界时报错:

Indices must be in 0 to size() - 1. Out of range errors:

int arr[] = {1, 2, 3};
int x = arr[5];             // ✗ 越界

访问之前先检查下标范围:

Check the index before accessing:

int i = 10;
if (i >= 0 && i < arr.size()) {
    int x = arr[i];
}

遍历数组 / Iterating an Array

用 for 循环,配合 size() 取长度:

Use a for loop with size() for length:

int scores[] = {10, 20, 30, 40, 50};

for (int i = 0; i < scores.size(); i = i + 1) {
    runcmd("CONSOLE", "say 第 " + i + " 项: " + scores[i]);
}

和遍历列表一样:先把长度取出来,不要在条件里每次调用 size():

As with lists: read the length first rather than calling size() in the condition:

int total = scores.size();
for (int i = 0; i < total; i = i + 1) {
    // ...
}

数组长度在声明后不会改变,所以提前取值总是安全的。

Array length never changes after declaration, so reading it up front is always safe.


数组是固定长度的 / Arrays Are Fixed-Length

数组一旦声明,长度就不能改。想加一个元素是做不到的:

Once declared, an array's length cannot change. Adding an element is not possible:

int arr[] = {1, 2, 3};
arr[3] = 4;         // ✗ 越界

如果你需要"能加能减"的序列,用 vector(见下一章)。判断标准很简单:数量在声明时就已经确定用数组;数量可能变化用 vector。

If you need a growable sequence, use vector (next chapter). The rule: count known at declaration → array; count may change → vector.


常见用法 / Common Patterns

查找最大值 / Finding the Maximum

int findMax(int data[]) {
    if (data.size() == 0) return 0;
    int best = data[0];
    for (int i = 1; i < data.size(); i = i + 1) {
        if (data[i] > best) {
            best = data[i];
        }
    }
    return best;
}

求和与平均 / Sum and Average

double average(int data[]) {
    if (data.size() == 0) return 0.0;
    double sum = 0.0;
    for (int i = 0; i < data.size(); i = i + 1) {
        sum += data[i];
    }
    return sum / data.size();
}

查找元素位置 / Finding an Element

int indexOf(string data[], string target) {
    for (int i = 0; i < data.size(); i = i + 1) {
        if (data[i] == target) {
            return i;
        }
    }
    return -1;      // 没找到
}

返回 -1 表示"未找到"是常见约定。调用方一定要检查,否则 -1 会被当作合法下标然后报错。

Returning -1 for "not found" is a common convention. Callers must check, or -1 is treated as a legal index and errors.


二维与更高维 / Two Dimensions and Beyond

HimDSL 没有专门的多维数组语法,但你可以在数组里放列表:

HimDSL has no dedicated multi-dimensional array syntax, but you can store lists inside:

var grid = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

int cell = grid[1][2];      // 6
grid[0][0] = 100;           // 修改

这里外层是"列表的列表",可以逐层下标访问。注意外层用 var 声明——嵌套字面量无法给出单一元素类型。

Here the outer is a "list of lists", indexed level by level. Note the outer uses var — nested literals cannot be given a single element type.

访问时越界检查同样适用,且要检查每一层。这个写法在需要小矩阵时很方便,但日常脚本用到的机会不多。

Bounds checks apply to each level. Convenient for small matrices, but rare in everyday scripts.


常见错误 / Common Mistakes

错误一:忘记方括号里的数字

int arr[];              // ✗ 语法错误:缺少长度和初始化

要么写长度 int arr[5];,要么给初始化 int arr[] = {1,2};。

错误二:size() 写成 length()

HimDSL 里数组和列表都统一用 size():

int n = arr.size();     // ✓
int m = arr.length();   // ✗ 不支持

错误三:在函数参数里写错数组语法

数组作为函数参数时,方括号放在参数名后面:

int sum(int data[]) { ... }        // ✓
int sum(int[] data) { ... }        // ✗

Mistake 1: Missing brackets and initializer

Give either a count or an initializer.

Mistake 2: length() instead of size()

Arrays and lists both use size() in HimDSL.

Mistake 3: Wrong array parameter syntax

Put brackets after the parameter name, not after the type.


小结 / Summary

  • 声明:类型 名称[长度] = {元素, ...};

  • 下标从 0 开始,越界报错。

  • 长度用 size() 读取,不会变化。

  • 遍历用 for + size()。

  • 需要动态增减时改用 vector。

  • 多维用"列表的列表"模拟。

  • Declare: type name[count] = {values...};

  • 0-based indices; out-of-range errors.

  • Read length with size(); it never changes.

  • Iterate with for + size().

  • For growable sequences, use vector.

  • Multi-dimensional via "list of lists".


下一步 / Next Steps

下一章 List / Set / Map 介绍三种常用的动态集合,它们比数组更灵活。

Next, List / Set / Map introduces three flexible collections, more dynamic than arrays.


HimDSL 文档 / Documentation

入门 / Getting Started

语言基础 / Language Basics

控制流 / Control Flow

函数 / Functions

数据结构 / Data Structures

自定义类型 / Custom Types

Minecraft 集成 / Minecraft Integration

事件与调度 / Events & Scheduling

GUI 系统 / GUI System

内置函数参考 / Built-ins Reference

进阶 / Advanced

扩展 API / Extension API

你真的需要 API 吗?/ Do you really need the API?

Clone this wiki locally