官术网_书友最值得收藏!

  • Lua Quick Start Guide
  • Gabor Szauer
  • 341字
  • 2021-08-05 10:30:38

Scope

Like many other programming languages, Lua implements the concept of scope for anything that can be named (like a variable). A scope defines where in the program a variable can be used. Scopes are limited to the chunks they appear in. A chunk is just a section of code. Some languages call chunks blocks because they are represented by blocks of code.

Every Lua file that is executed is a chunk. This chunk can contain other, smaller chunks. Think of it as a hierarchical relationship. Such a relationship could be visualized as follows:

You can create a local chunk in a file by using the do keyword. The chunk ends with the end keyword. The following bit of code demonstrates how to create a local chunk in a file:

-- main file chunk is anywhere in the file

do
-- local chunk
end

do
-- a different local chunk
end

As mentioned earlier, scope refers to visibility. A chunk can access any variables declared in its parent chunk, but none of the variables available in any child chunks. To demonstrate this, consider the following variable declarations in different chunks:

For now, ignore the syntax. In this example, the local chunk can see the variables dog, cat, and fish. However, the file chunk cannot see the fish variable, only dog and cat. Similarly, the global chunk can only see the dog variable. This diagram would be expressed in code like so:

-- Dog is accessable in the global chunk
dog = "This is a dog"

-- Cat is accessable in the file chunk
-- The local keyword makes cat local to the file
local cat = "This is a cat"

do -- Do / end will be discussed next
-- Fish is in a local chunk, in this example
-- that means local to the do/end block
local fish = "This is a fish"
end
More information on scope as it refers to computer science can be found online at http://lua-users.org/wiki/ScopeTutorial.

Lua supports a few different types of chunk; this section will explore the do/end chunk properties in detail.

主站蜘蛛池模板: 鹤峰县| 汶上县| 明光市| 鄂伦春自治旗| 英超| 临江市| 安平县| 抚州市| 东源县| 历史| 双辽市| 昆明市| 延长县| 静宁县| 宁国市| 宣恩县| 大石桥市| 台东市| 宽甸| 剑川县| 巫溪县| 夏邑县| 偏关县| 雷州市| 临城县| 平顶山市| 诸城市| 永兴县| 平定县| 屏山县| 广灵县| 宁城县| 栾川县| 泾川县| 怀来县| 漳平市| 四会市| 衡水市| 瑞昌市| 石屏县| 新建县|