目录
由于VEX是强类型,很难处理每个参数的值和类型都不同的参数集,dict类型提供了方法;dict缺乏效率,应仅在变量和类型不同时使用;
一,声明字典类型
通用格式:dict var_name
- 字典的index或key总是字符串string,其可以为任何值,但建议避免空字符串或含.的字符串;
- 字典的value可以为大多数基础的vex类型,如int, float, vector2, vector, vector4, matrix2, matrix3, matrix, string, int[], float[], string[], dict, dict[];
//声明字典变量
dict mydict;
//返回字典类型
dict rgb_table()
{
...
};
//空字典
dict s = {};
二,访问与设置字典值
使用格式:dict [index]
- index是字符串,由于访问其值,如key不存在,结果是默认初始值;
- vex要求在编译时知道类型,但实际存储的类型可能在运行时有所不同;因此通常需要一个显式函数类型转换;
- getcomp函数可携带一个默认参数,如key不存在使用此参数作为默认值;
- 可使用insert将一字典内键的值复制给另一个字典内键的值,也用于将两字典连接在一起;
- 可使用set根据参数构建字典;
dict dictionary; // Create empty dictionary
dictionary['key'] = 3; // Store 3 in the index key
float three = dictionary['key']; // Extract key
dictionary['newkey'] = dictionary['key']; // Error: Ambiguous type!
dictionary['newkey'] = int(dictionary['key']); // Extract key as int and copy
dict dictionary;
dictionary['key'] = 3;
int three = getcomp(dictionary, 'key', 52);
int fiftytwo = getcomp(dictionary, 'nonkey', 52);
dict a, b;
a['key'] = 3;
b['oldkey'] = 5;
insert(b, 'newkey', a, 'key'); // Makes b['newkey'] == 3
insert(b, 'oldkey', a, 'nonkey'); // Removes b['oldkey'] as nonkey missing in a.
insert(b, a); // Adds all entries of a to b, overwriting on conflict.
dict a;
a = set("key", 3.0, "nextkey", 5.0, "lastkey", "stringvalue");
三,字典函数的使用
字典函数可用于查询和管理字典;
Functions | Using |
len | 返回字典key的数量 |
keys | 返回所有key的字符串数组 |
isvalidindex | 指定key在字典内是否存在 |
insert | 复制值到另一个字典,也可合并字典到了一个字典 |
removeindex | 从字典中删除指定key |
set | 根据参数构建字典 |
注
- json_dumps,将VEX字典转化为JSON字符串;
- json_loads,将JSON字符串转化为VEX字典;
- keys,返回字典所有key;