DAY 24
0
Software Development

# 變數的查找

``````function parentFunction()
local L1 = 100
local function childFunction()
print("here is child")
end
return childFunction
end

f1 = parentFunction(100)
f1()  -- Output: here is child
``````

## 詞法環境(Lexical)

### 隱藏區塊變數

``````do
local L1 = 100

do
local L1 = nil

do  -- 隱藏的區塊
print(L1) -- Output: nil
end

end
print(L1) -- Output: 100

end
``````

# 提供不同的區塊變數

``````function createFunTable()
local T = {}
do
local L1 = 100
function T.f1()
print(L1)
end
end

do
local L1 = 200
function T.f2()
print(L1)
end
end
return T
end

T = createFunTable()
T.f1() -- Output: 100
T.f2() -- Output: 200
``````

``````function createFunTable()
local T = {}
function T.f1()
local L1 = 100
print(L1)
end

function T.f2()
local L1 = 200
print(L1)
end

return T
end

T = createFunTable()
T.f1() -- Output: 100
T.f2() -- Output: 200
``````

# 只有特定函數可以存取的特別變數

``````do
local X = 1
function getX()
return X
end

function setX(v)
X = v
return X
end
end

print(X) -- Output: nil
print(getX()) --> 1
setX(100)
print(getX()) --> 100
``````

## 唯讀

``````do
local X<const> = 1
function getX()
return X
end
end

print(X) -- Output: nil
print(getX()) --> 1
``````

# 閉包

``````function makeAdd(n)
local n = n
return function (k)
return n + k
end
end