您当前的位置: 首页 > 

开发游戏的老王

暂无认证

  • 4浏览

    0关注

    803博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

match语句

开发游戏的老王 发布时间:2019-10-13 10:28:41 ,浏览量:4

Godot Engine 3.2Alpha2

本文主要依据Godot官方提供的match关键字文档,我补充了一下代码实例及个人理解

基本用法
match x:
    1:
        print("We are number one!")
    2:
        print("Two are better than one!")
    "test":
        print("Oh snap! It's a string!")

match的基本用法看起来和传统的switch没有太大区别,如果你熟悉switch的用法,下面简单几步就可以用match来实现:

  1. match替换switch
  2. 去掉case
  3. 把所有的break去掉,因为match默认就是执行完一个分支自动break.如果你想让它顺序执行下一条分支,只需要加一个continue即可
  4. 如果你需要default的话,用_来代替它。
6+1种模式
  • 常量模式(Constant Pattern)

预置常量比如数字或字符串,和经典的switch相比最大的区别在于分支可以是不同类型的常量。

match x:
    1:
        print("We are number one!")
    2:
        print("Two are better than one!")
    "test":
        print("Oh snap! It's a string!")
  • 变量模式(Variable Pattern)

用变量当分支条件是很多人梦寐以求的

extends Node

var TYPE_REAL = 100
var TYPE_STRING = "hello"
var TYPE_ARRAY = [1,2,3]


func _ready():
	var x = [1,2,3]
	match x:
		TYPE_REAL:
			print(TYPE_REAL)
		TYPE_STRING:
			print(TYPE_STRING)
		TYPE_ARRAY:
			print(TYPE_ARRAY)

输出结果

[1, 2, 3]
  • 通配符模式(Wildcard Pattern)

_相当于default

match x:
    1:
        print("It's one!")
    2:
        print("It's one times two!")
    _:
        print("It's not 1 or 2. I don't care tbh.")
  • 绑定模式(Binding pattern)

这里会声明一个新的变量,和通配符一样相当于default,只是给值赋予了名字。文档中说这种机制在数字和字典模式下很有用,我自己目前没有想到用法,以后补充。

match x:
    1:
        print("It's one!")
    2:
        print("It's one times two!")
    var new_var:
        print("It's not 1 or 2, it's ", new_var)

  • 数组模式(Array Pattern)

    • 数组的每一个元素都是独立的模式,因此这种模式支持嵌套。
    • 匹配时会先检查数组的长度,如果长度不匹配则直接否决。
    • 开放数组(Open-ended array):把最后一个子模式设为..可以时数组大于匹配条件。
match x:
    []:
        print("Empty array")
    [1, 3, "test", null]:
        print("Very specific array")
    [var start, _, "test"]:
        print("First element is ", start, ", and the last is \"test\"")
    [42, ..]:
        print("Open ended array")
  • 字典模式(Dictionary Pattern)

和数组模式很相似,注意每个键值必须是常量

match x:
    {}:
        print("Empty dict")
    {"name": "Dennis"}:
        print("The name is Dennis")
    {"name": "Dennis", "age": var age}:
        print("Dennis is ", age, " years old.")
    {"name", "age"}:
        print("Has a name and an age, but it's not Dennis :(")
    {"key": "godotisawesome", ..}:
        print("I only checked for one entry and ignored the rest")
  • 复合模式(Multipatterns)
match x:
    1, 2, 3:
        print("It's 1 - 3")
    "Sword", "Splash potion", "Fist":
        print("Yep, you've taken damage")

关注
打赏
1656935939
查看更多评论
立即登录/注册

微信扫码登录

0.1019s