Lua 函數是第一類值,支持多返回值、平行賦值、詞法作用域、閉包。本文以極簡示例速覽核心語法。
function foo(a, b, c)
local sum = a + b -- local 聲明局部變量(推薦)
return sum, c -- 多返回值
end
r1, r2 = foo(1, '123', "hello") -- 平行賦值接收多返回值
print(r1, r2) -- 4 hello
return a, b, c,調用方用 x, y, z = func() 接收;多餘返回值被丟棄,不足用 nil 補齊。a, b = c, d 先計算右側所有表達式,再賦值,支持交換 a, b = b, a。foo、r1、r2 均為全局。
function counter()
local count = 0
return function()
count = count + 1
return count
end
end
c1 = counter()
print(c1()) -- 1
print(c1()) -- 2
c2 = counter() -- 獨立閉包,各自 count
print(c2()) -- 1
Lua 函數語法極簡卻強大:**local 必加、多返回值、平行賦值、閉包工廠** 是日常高頻模式。牢記「無 local 即全局」,養成良好作用域習慣。