范围

范围是名称绑定有效的计算机程序区域。名称绑定只是说“变量”的一个花哨的词。
范围在编程应用程序中的范围可能有所不同。
这些可以从小的 for 循环和 if 语句到整个类。

范围级别

  • 全球范围
  • 类/文件/模块范围
  • 功能范围
  • 代码块范围

    全球范围

    全局作用域是可以在 Godot 应用程序中的任何位置使用的类、变量或函数。
    一个例子是 Node 类: ```swift extends Node

The rest of your class

  1. <a name="kIhej"></a>
  2. #### 类范围
  3. 类作用域是可以在类文件中的任何位置使用的变量或函数。
  4. ```swift
  5. extends Node # Global Scope Class Name Node
  6. # Class variables that can be used anywhere in the class file
  7. var health: String = 100
  8. var speed: float = 10.0

功能范围

只能在函数内部使用的变量/值

  1. extends Node # Global Scope Class Name Node
  2. #Class Scope
  3. var health: String = 100
  4. var speed: float = 10.0
  5. func example():
  6. # variable functionVariable can only be used inside of the function `example()`
  7. var functionVariable = 10

代码块范围

只能在代码块内部使用的变量/值。
示例 fo 代码块将是 if 语句、match 语句、for & while 循环等:

  1. extends Node # Global Scope Class Name Node
  2. # Class Scope
  3. var health: String = 100
  4. var speed: float = 10.0
  5. func example():
  6. # Function Scope
  7. var functionVariable = 10
  8. if(true):
  9. # Code Block Scope
  10. # variable message exists only inside this one if statement
  11. var message = "Hi!"
  12. print(message)