Godot编写命令解析器:如何识别句中任意位置的关键词
实现方案
原有逻辑仅提取分词结果的第一个元素做匹配,因此只能识别句首命令。要支持任意位置关键词识别,直接遍历所有分词逐一匹配即可,修改后可直接运行的代码如下:
func process_command(_input: String) -> String: var words = _input.split(" ", false) if words.is_empty(): return "Error: no words were parsed." for word in words: match word.to_lower(): "hello": return hello() "help": return help() return "I don't understand." func hello() -> String: return "Hello. How are you?" func help() -> String: return "Press ESC for help."
注意事项
- GDScript语法依赖缩进:
hello()、help()两个函数需要和process_command()保持同级缩进,不能嵌套写在process_command内部,否则会触发语法报错。 - 匹配前对单词做小写转换,可兼容任意大小写的输入形式,比如
Hello、HELLO、hElLo都能正常触发对应响应。 - 当前逻辑为匹配到第一个关键词就返回结果,如果需要支持单句触发多个命令,可调整遍历逻辑,收集所有命中的响应内容后统一返回。
内容的提问来源于stack exchange,提问作者Hidden
相关产品推荐
相关产品推荐

