# [X分鐘速成Y](http://learnxinyminutes.com/)
## 其中 Y=Lua
源代碼下載:?[lua-cn.lua](http://learnxinyminutes.com/docs/files/lua-cn.lua)
~~~
-- 單行注釋以兩個連字符開頭
--[[
多行注釋
--]]
----------------------------------------------------
-- 1\. 變量和流程控制
----------------------------------------------------
num = 42 -- 所有的數字都是雙精度浮點型。
-- 別害怕,64位的雙精度浮點型數字中有52位用于
-- 保存精確的整型值; 對于52位以內的整型值,
-- 不用擔心精度問題。
s = 'walternate' -- 和Python一樣,字符串不可變。
t = "也可以用雙引號"
u = [[ 多行的字符串
以兩個方括號
開始和結尾。]]
t = nil -- 撤銷t的定義; Lua 支持垃圾回收。
-- 塊使用do/end之類的關鍵字標識:
while num < 50 do
num = num + 1 -- 不支持 ++ 或 += 運算符。
end
-- If語句:
if num > 40 then
print('over 40')
elseif s ~= 'walternate' then -- ~= 表示不等于。
-- 像Python一樣,用 == 檢查是否相等 ;字符串同樣適用。
io.write('not over 40\n') -- 默認標準輸出。
else
-- 默認全局變量。
thisIsGlobal = 5 -- 通常使用駝峰。
-- 如何定義局部變量:
local line = io.read() -- 讀取標準輸入的下一行。
-- ..操作符用于連接字符串:
print('Winter is coming, ' .. line)
end
-- 未定義的變量返回nil。
-- 這不是錯誤:
foo = anUnknownVariable -- 現在 foo = nil.
aBoolValue = false
--只有nil和false為假; 0和 ''均為真!
if not aBoolValue then print('false') end
-- 'or'和 'and'短路
-- 類似于C/js里的 a?b:c 操作符:
ans = aBoolValue and 'yes' or 'no' --> 'no'
karlSum = 0
for i = 1, 100 do -- 范圍包含兩端
karlSum = karlSum + i
end
-- 使用 "100, 1, -1" 表示遞減的范圍:
fredSum = 0
for j = 100, 1, -1 do fredSum = fredSum + j end
-- 通常,范圍表達式為begin, end[, step].
-- 循環的另一種結構:
repeat
print('the way of the future')
num = num - 1
until num == 0
----------------------------------------------------
-- 2\. 函數。
----------------------------------------------------
function fib(n)
if n < 2 then return 1 end
return fib(n - 2) + fib(n - 1)
end
-- 支持閉包及匿名函數:
function adder(x)
-- 調用adder時,會創建返回的函數,
-- 并且會記住x的值:
return function (y) return x + y end
end
a1 = adder(9)
a2 = adder(36)
print(a1(16)) --> 25
print(a2(64)) --> 100
-- 返回值、函數調用和賦值都可以
-- 使用長度不匹配的list。
-- 不匹配的接收方會被賦值nil;
-- 不匹配的發送方會被丟棄。
x, y, z = 1, 2, 3, 4
-- x = 1、y = 2、z = 3, 而 4 會被丟棄。
function bar(a, b, c)
print(a, b, c)
return 4, 8, 15, 16, 23, 42
end
x, y = bar('zaphod') --> 打印 "zaphod nil nil"
-- 現在 x = 4, y = 8, 而值15..42被丟棄。
-- 函數是一等公民,可以是局部的,也可以是全局的。
-- 以下表達式等價:
function f(x) return x * x end
f = function (x) return x * x end
-- 這些也是等價的:
local function g(x) return math.sin(x) end
local g; g = function (x) return math.sin(x) end
-- 'local g'使得g可以自引用。
-- 順便提下,三角函數以弧度為單位。
-- 用一個字符串參數調用函數,可以省略括號:
print 'hello' --可以工作。
-- 調用函數時,如果只有一個table參數,
-- 同樣可以省略括號(table詳情見下):
print {} -- 一樣可以工作。
----------------------------------------------------
-- 3\. Table。
----------------------------------------------------
-- Table = Lua唯一的組合數據結構;
-- 它們是關聯數組。
-- 類似于PHP的數組或者js的對象,
-- 它們是哈希表或者字典,也可以當列表使用。
-- 按字典/map的方式使用Table:
-- Dict字面量默認使用字符串類型的key:
t = {key1 = 'value1', key2 = false}
-- 字符串key可以使用類似js的點標記:
print(t.key1) -- 打印 'value1'.
t.newKey = {} -- 添加新的鍵值對。
t.key2 = nil -- 從table刪除 key2。
-- 使用任何非nil的值作為key:
u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'}
print(u[6.28]) -- 打印 "tau"
-- 數字和字符串的key按值匹配的
-- table按id匹配。
a = u['@!#'] -- 現在 a = 'qbert'.
b = u[{}] -- 我們或許期待的是 1729, 但是得到的是nil:
-- b = nil ,因為沒有找到。
-- 之所以沒找到,是因為我們用的key與保存數據時用的不是同
-- 一個對象。
-- 所以字符串和數字是移植性更好的key。
-- 只需要一個table參數的函數調用不需要括號:
function h(x) print(x.key1) end
h{key1 = 'Sonmi~451'} -- 打印'Sonmi~451'.
for key, val in pairs(u) do -- 遍歷Table
print(key, val)
end
-- _G 是一個特殊的table,用于保存所有的全局變量
print(_G['_G'] == _G) -- 打印'true'.
-- 按列表/數組的方式使用:
-- 列表字面量隱式添加整數鍵:
v = {'value1', 'value2', 1.21, 'gigawatts'}
for i = 1, #v do -- #v 是列表的大小
print(v[i]) -- 索引從 1 開始!! 太瘋狂了!
end
-- 'list'并非真正的類型,v 其實是一個table,
-- 只不過它用連續的整數作為key,可以像list那樣去使用。
----------------------------------------------------
-- 3.1 元表(metatable) 和元方法(metamethod)。
----------------------------------------------------
-- table的元表提供了一種機制,支持類似操作符重載的行為。
-- 稍后我們會看到元表如何支持類似js prototype的行為。
f1 = {a = 1, b = 2} -- 表示一個分數 a/b.
f2 = {a = 2, b = 3}
-- 這會失敗:
-- s = f1 + f2
metafraction = {}
function metafraction.__add(f1, f2)
sum = {}
sum.b = f1.b * f2.b
sum.a = f1.a * f2.b + f2.a * f1.b
return sum
end
setmetatable(f1, metafraction)
setmetatable(f2, metafraction)
s = f1 + f2 -- 調用在f1的元表上的__add(f1, f2) 方法
-- f1, f2 沒有關于元表的key,這點和js的prototype不一樣。
-- 因此你必須用getmetatable(f1)獲取元表。
-- 元表是一個普通的table,
-- 元表的key是普通的Lua中的key,例如__add。
-- 但是下面一行代碼會失敗,因為s沒有元表:
-- t = s + s
-- 下面提供的與類相似的模式可以解決這個問題:
-- 元表的__index 可以重載用于查找的點操作符:
defaultFavs = {animal = 'gru', food = 'donuts'}
myFavs = {food = 'pizza'}
setmetatable(myFavs, {__index = defaultFavs})
eatenBy = myFavs.animal -- 可以工作!感謝元表
-- 如果在table中直接查找key失敗,會使用
-- 元表的__index 遞歸地重試。
-- __index的值也可以是function(tbl, key)
-- 這樣可以支持自定義查找。
-- __index、__add等的值,被稱為元方法。
-- 這里是一個table元方法的清單:
-- __add(a, b) for a + b
-- __sub(a, b) for a - b
-- __mul(a, b) for a * b
-- __div(a, b) for a / b
-- __mod(a, b) for a % b
-- __pow(a, b) for a ^ b
-- __unm(a) for -a
-- __concat(a, b) for a .. b
-- __len(a) for #a
-- __eq(a, b) for a == b
-- __lt(a, b) for a < b
-- __le(a, b) for a <= b
-- __index(a, b) <fn or a table> for a.b
-- __newindex(a, b, c) for a.b = c
-- __call(a, ...) for a(...)
----------------------------------------------------
-- 3.2 與類相似的table和繼承。
----------------------------------------------------
-- Lua沒有內建的類;可以通過不同的方法,利用表和元表
-- 來實現類。
-- 下面是一個例子,解釋在后面:
Dog = {} -- 1\.
function Dog:new() -- 2\.
newObj = {sound = 'woof'} -- 3\.
self.__index = self -- 4\.
return setmetatable(newObj, self) -- 5\.
end
function Dog:makeSound() -- 6\.
print('I say ' .. self.sound)
end
mrDog = Dog:new() -- 7\.
mrDog:makeSound() -- 'I say woof' -- 8\.
-- 1\. Dog看上去像一個類;其實它是一個table。
-- 2\. 函數tablename:fn(...) 等價于
-- 函數tablename.fn(self, ...)
-- 冒號(:)只是添加了self作為第一個參數。
-- 閱讀7 & 8條 了解self變量是如何得到其值的。
-- 3\. newObj是類Dog的一個實例。
-- 4\. self = 被繼承的類。通常self = Dog,不過繼承可以改變它。
-- 如果把newObj的元表和__index都設置為self,
-- newObj就可以得到self的函數。
-- 5\. 備忘:setmetatable返回其第一個參數。
-- 6\. 冒號(:)的作用和第2條一樣,不過這里
-- self是一個實例,而不是類
-- 7\. 等價于Dog.new(Dog),所以在new()中,self = Dog。
-- 8\. 等價于mrDog.makeSound(mrDog); self = mrDog。
----------------------------------------------------
-- 繼承的例子:
LoudDog = Dog:new() -- 1\.
function LoudDog:makeSound()
s = self.sound .. ' ' -- 2\.
print(s .. s .. s)
end
seymour = LoudDog:new() -- 3\.
seymour:makeSound() -- 'woof woof woof' -- 4\.
-- 1\. LoudDog獲得Dog的方法和變量列表。
-- 2\. 因為new()的緣故,self擁有了一個'sound' key,參見第3條。
-- 3\. 等價于LoudDog.new(LoudDog),轉換一下就是
-- Dog.new(LoudDog),這是因為LoudDog沒有'new' key,
-- 但是它的元表中有 __index = Dog。
-- 結果: seymour的元表是LoudDog,并且
-- LoudDog.__index = Dog。所以有seymour.key
-- = seymour.key, LoudDog.key, Dog.key
-- 從其中第一個有指定key的table獲取。
-- 4\. 在LoudDog可以找到'makeSound'的key;
-- 等價于LoudDog.makeSound(seymour)。
-- 如果有必要,子類也可以有new(),與基類相似:
function LoudDog:new()
newObj = {}
-- 初始化newObj
self.__index = self
return setmetatable(newObj, self)
end
----------------------------------------------------
-- 4\. 模塊
----------------------------------------------------
--[[ 我把這部分給注釋了,這樣腳本剩下的部分可以運行
-- 假設文件mod.lua的內容類似這樣:
local M = {}
local function sayMyName()
print('Hrunkner')
end
function M.sayHello()
print('Why hello there')
sayMyName()
end
return M
-- 另一個文件可以使用mod.lua的功能:
local mod = require('mod') -- 運行文件mod.lua.
-- require是包含模塊的標準做法。
-- require等價于: (針對沒有被緩存的情況;參見后面的內容)
local mod = (function ()
<contents of mod.lua>
end)()
-- mod.lua被包在一個函數體中,因此mod.lua的局部變量
-- 對外不可見。
-- 下面的代碼可以工作,因為在這里mod = mod.lua 中的 M:
mod.sayHello() -- Says hello to Hrunkner.
-- 這是錯誤的;sayMyName只在mod.lua中存在:
mod.sayMyName() -- 錯誤
-- require返回的值會被緩存,所以一個文件只會被運行一次,
-- 即使它被require了多次。
-- 假設mod2.lua包含代碼"print('Hi!')"。
local a = require('mod2') -- 打印Hi!
local b = require('mod2') -- 不再打印; a=b.
-- dofile與require類似,但是不緩存:
dofile('mod2') --> Hi!
dofile('mod2') --> Hi! (再次運行,與require不同)
-- loadfile加載一個lua文件,但是并不運行它。
f = loadfile('mod2') -- Calling f() runs mod2.lua.
-- loadstring是loadfile的字符串版本。
g = loadstring('print(343)') --返回一個函數。
g() -- 打印343; 在此之前什么也不打印。
--]]
~~~
## 參考
為什么?我非常興奮地學習lua, 這樣我就可以使用[L?ve 2D游戲引擎](http://love2d.org/)來編游戲。
怎么做?我從[BlackBulletIV的面向程序員的Lua指南](http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/)入門。接著我閱讀了官方的[Lua編程](http://www.lua.org/pil/contents.html)一書。
lua-users.org上的[Lua簡明參考](http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf)應該值得一看。
本文沒有涉及標準庫的內容:
* [string library](http://lua-users.org/wiki/StringLibraryTutorial)
* [table library](http://lua-users.org/wiki/TableLibraryTutorial)
* [math library](http://lua-users.org/wiki/MathLibraryTutorial)
* [io library](http://lua-users.org/wiki/IoLibraryTutorial)
* [os library](http://lua-users.org/wiki/OsLibraryTutorial)
使用Lua,歡樂常在!