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/

2013.01.06

 

1. 注释

-- 相当于//

--[[
    相当与 /*...*/    
--]]

 

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. 语句

-- 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 往后编;

 

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)

 

posted @ 2013-07-07 16:18  stallman  阅读(525)  评论(0编辑  收藏  举报