LUA筆記 - 入門

Lua is a powerful, fast, lightweight, embeddable scripting language. "Lua" (pronounced LOO-ah) means "Moon" in Portuguese.數組

http://www.lua.org函數

http://www.lua.org/manual/5.2/ui

2013.01.06lua

 

1. 註釋
spa

-- 至關於//

--[[
    至關與 /*...*/    
--]]

 

2. 類型與值, 表達式線程

nil 空值,全部沒有使用過的變量,都是nil。nil既是值,又是類型。
boolean 布爾值,true 和 false。Lua中條件判斷只有 false 和 nil 視爲「假」,其餘均爲「真」。
number 數值,在Lua裏,數值至關於C語言的double。
string 字符串,Lua的字符串是不可變的值,不能像C語言那樣直接修改字符串的某個字符。
table 表,關聯數組。在lua中,table既不是「值」,也不是「變量」,而是「對象」。
function 函數類型,
userdata 自定義類型,
thread 線程,
print(type("hello world"))      -- string
print(type(10*4.3))             -- number 
print(type(print))              -- function
print(type(true))               -- boolean
print(type(nil))                -- nil
print(type(type(X)))            -- string
print(type({}))                 -- table

-- 未賦值的變量爲nil
print(type(name))

-- 如下寫法是同一個字符串
a = 'alo\n123"'
a = "alo\n123\""
a = '\97lo\10\04923"'
a = [[alo
 123"]]
a = [==[
alo
123"]==]
-- 算術操做
a = 109
b = 8
print(a%b == a - math.floor(a/b)*b)     -- true

pi = math.pi
print(pi)                   -- 3.1415926535898
print(pi - pi%0.01)         -- 3.14 


-- 關係操做符
-- <    >   <=  >=  ==  ~=

-- 對於table, function, userdata類型的數據,只有 == 和 ~= 能夠用。
a={1,2}
b=a
print(a==b, a~=b)       -- true     false
a={1,2}
b={1,2}
print(a==b, a~=b)       -- false    true
local f1 = math.sin
local f2 = math.sin
print(f1 == f2)         -- true
f2 = function () end 
print(f1 == f2)         -- false

-- 邏輯操做   and or not   
-- 僅僅將false nil視爲假
print(4 and 5)          -- 5        and or 均爲短路求值
print(nil and 13)       -- nil
print(false and 13)     -- false
print(4 or 5)           -- 4
print(false or 5)       -- 5

-- c語言中的語句: x = a ? b : c,習慣寫法 (a and b) or c 前提是b不爲假
a = false 
b, c = 1, 1024
print(a and b or c)     -- 1024 
-- 它至關於 if not x then x = v end 
x = x or v

 

3. 語句code

-- 1. 控制語句

-- if exp then block {elseif exp then block} [else block] end
if nil then
    print(nil)
elseif true then
    print(true)
else
    print("else")
end    

-- while exp do block end
i = 1
while i < 10 do
    print(i)
    if i == 3 then break end
    i = i + 1
end

-- repeat block until exp
repeat print("halo") until 1+1 == 2 

-- for Name ‘=’ exp ‘,’ exp [‘,’ exp] do block end
-- for 變量=初值, 終點值, 步進 do ... end
for i = 1, 10, 2 do
    print(i)        -- 1  3  5  7  9 
end

-- for namelist in explist do block end
-- for 變量1, 變量2, ... 變量n in 表或枚舉函數 do ... end
days = {"Suanday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} 
for i,v in ipairs(days) do
    print(v)
end   



-- 2. 賦值

a = "hello " .. "world" 

x, y = 1, 2^3
print(x, y)     --  1   8
x, y = y, x
print(x, y)     --  8   1, 

a, b, c = 0, 1
print(a, b, c)          --  0   1   nil 
a, b = a+1, b+1, b+2    -- b+2 被忽略
print(a, b, c)          --  1   2   nil
a, b, c = 0
print(a, b, c)          --  0   nil nil
a, _, c = 'x', 'y', 'z'
print(a, _, c)          --  x   y   z 



-- 3. 局部變量和塊

x = 10              -- 全局
local i = 1         -- 局部
while i <= x do
    local x = i*2       -- 循環體中局部變量
    i = i + 1
end
-- 很少說,local聲明局部變量,在塊中有效
-- 語句塊在C中是用"{"和"}"括起來的,在Lua中,它是用 do 和 end 括起來



-- 4. break / return

-- break 用來終止一個循環(while, repeat, for)
-- return 用來從一個函數中返回結果,或用於結束一個函數的執行。
-- break return 只能是一個塊的最後一條語句(end,else, until前一條語句)
function foo ()
    --return true           -- syn err
    do return true end      -- ok
end

 

4.  table對象

第一,全部元素之間,老是用逗號 "," 隔開;
第二,全部索引值都須要用 "["和"]" 括起來;若是是字符串,還能夠去掉引號和中括號; 即若是沒有[]括起,則認爲是字符串索引;
第三,若是不寫索引,則索引就會被認爲是數字,並按順序自動從 1 日後編;blog

 

local math= require "math"
w = {x = 0, y = 1, label = 'console'}
x = {math.sin(0), math.sin(1), math.sin(2)}
w[1] = "another field"
x.f = w

print(w["x"])           -- 0
print(w[1])             -- another field
print(x.f["label"])     -- console
print(x.f.label)        -- console
print(w.x)              -- 0
for k,v in ipairs(w) do
    print(tostring(k), tostring(v))     -- 1   another field
end

print("-----------")
days = {"monday", "Tuesday"}
print(days[2])          -- Tuesday


print("-----------")
t = {}
t[1] = 10
t["jhon"] = {age = 27, gender = "male"}
print(t[1]) 
print(t["jhon"]["age"])
print(t["jhon"].age)


i = 10; j = "10"; k = "+10"
a = {}
a[i] = "one value"
a[j] = "another value"
a[k] = "yet another value"
print(a[j])            --> another value
print(a[k])            --> yet another value
print(a[tonumber(j)])  --> one value
print(a[tonumber(k)])  --> one value


polyline = { color = "blue", thickness = 2, npoits = 4,
            {x = 1, y = 2},
            {x = 3, y = 4},
            "jeff",
            {x = 5, y = 6},
}
print(polyline[1].y)            -- 2
print(polyline[2].x)            -- 3
print(polyline[3])              -- jeff
print(polyline["color"])        -- blue

  

5. function索引

-- 1. 定義

function add1 (a, b)
    return a + b
end

add2 = function (a, b)  -- 一個匿名函數,賦值給add2 
    return a + b
end

print(add1(1, 2))       -- 3
print(add2(3, 4))       -- 7


-- 2. 可變參數
function sum (a, b, ...)
    local s = a + b
    --for _,v in ipairs(arg) do
    for _,v in ipairs {...} do
        s = s + v
    end
    return s
end

print(sum(1, 2, 3, 4))      -- 10


-- 3. 多重返回值
function foo0 () end
function foo1 () return "a" end
function foo2 () return "a", "b" end

x,y = foo2()            -- x="a", y="b"
x = foo2()              -- x="a"
x,y,z = 10, foo2()      -- x=10, y="a", z="b"

-- 若是一個函數不是一系列表達式的最後一個元素,那麼將只會產生一個值:
x,y = foo2(), 20
print(x,y)              -- a   20
x,y,z = foo2(), 20
print(x,y,z)            -- a   20   nil

print(foo2(), 100)      -- a   100
print(100, foo2())      -- 100  a   b


-- 4. 尾調用
-- Proper Tail Calls是LUA的另外一個有趣的特性, 在一個LUA函數中, 若是最後一個操做是返回一個函數調用, 
-- 例如 return g(...), 那麼LUA不會把它看成一個函數調用而創建調用堆棧而只簡單的跳轉到另外一個函數中。
-- 下面例子傳入任何數字做爲參數都不會形成棧溢出
function foo (n)
    if n > 0 then return foo(n - 1) end
end

foo(1000000000)
相關文章
相關標籤/搜索