GDScript语言基础内容(分号仅为个人习惯)
一、变量
1.var text = “10”; //可以仅声明不赋值,下同
2.var text:string = “10”; //可以声明变量类型
3.var num:float = 10 as float; //as为强制转换
二、二元关系
1.+-*/%
2.&& 等价于 and
3.|| 等价于 or
4.! 等价于 not
5.==等价于 is
三、常量
const xxx(同变量格式)
四、循环
- while循环
格式while 条件(为真时):
//do something
2.for循环
var number = 10;
var array = [1,2,3,4,5];
var dictionary = {“key1”:”value1”,”key2”:”value2”};
For value in number: //从0到9
//do something
For element in array://索引从0到4
//do something
For key in dictionary://遍历所有键值
//do something
五、match语句
用法同传统switch大致一致,最大的不同是分支可以是任意类型的常量,甚至变量!
var testreal = 100;
var array = [1,2,3];
match x:
1: //不用写case
print(“1”);
print(“2”); //自动break
“test”:
print(“a string”);
[1,2]:
Print(“1,2”);
array:
print(“array”);
testreal:
print(“testreal”);
[]:
print(“empty array”);
{“name”:”sb”}:
print(“ccfsb”);
_: //下划线就是default
print(“jsdakjd”);
六、array 数组
1.声明
var array = [];
array[0]=1;//赋值
var array = [[1,2],[3,4]]; //二维数组
2.一些方法
var array = [1,2,3,4,5];
array.pop_back(); //[1,2,3,4]
array.pop_front();//[2,3,4]
array.push_back(5); //[2,3,4,5]
array.push_front(1);//[1,2,3,4,5]
array=[];
array.resize(0);
array.clear(); //以上三行都可以用来清空一个数组
var length = array.size(); //长度
七、enum 枚举
enum{常量名1,常量名2,..}
enum 集合名{常量名1,常量名2,..}
默认从0递增分配值
例子
enum {A,B=10,C};
enum FOOD {APPLE,JUICE=-1}
print(C); //11
print(FOOD.APPLE);//0
八、dictionary 字典
var dict1 = {};
var dict2 = {1:[1,2] ,“name”:“ccfsb”};
dict1[1] = [1,2];
dict1[“name”] = “ccfsb”;
print(dict1 == dict2); //false
print(dict1.hash() == dict2.hash()); //true,必须比较hash值
for each in dict1.keys():
print(“value = ”,each);