Lua笔记

2014-04-17 02:06  4756人阅读  评论 (0)
Tags: lua

变量

nil, boolean, number, string, function, userdata, thread, and table

nil

n = nil

boolean

只有false和nil是假, 其他都是true, 0也是true

b = false

number

i = 1
f = 1.0
h = 0x10

string

s = "hello world"

function

function function_name( a, b, ... )
    c = {...} -- 可变参数转换为table
    print(a, b, c)
end

userdata

C数据

thread

coroutine 协程

table

a = {1,2,3,4,5}
t = {key=value}
print(a.key)

多变量赋值/交换

x, y = 10, 20
print(x, y)      -- 10      20

class

Foo = {}
function Foo:new (name)
    local obj = {}
    setmetatable(obj, self)
    self.__index = self
    obj.name = name
    return obj
end
function Foo:getName ()
    return self.name
end

foo = Foo:new("dotcoo")
print(foo.getName())

变量环境

_G
_VERSION
_ENV

全局变量 局部变量

s = "hello world" -- 全局变量
local s = "hello world" -- 局部变量

错误处理

-- 抛出错误, 参数: 消息 等级
error (message[, level])
-- 隔离错误, 参数: 函数 函数参数 返回值: 是否有错误 错误消息
pcall (f [, arg1, ···])
-- 隔离并捕获错误, 参数: 函数 错误处理函数 函数参数 返回值: 是否有错误 错误消息
xpcall (f, msgh [, arg1, ···])

元表

有点像C++的操作符重载 python的运算符重载 也有点像javascript的原型 呵呵

setmetatable getmetatable

"__add": the + operation.

"__sub": the - operation. Behavior similar to the "add" operation.

"__mul": the * operation. Behavior similar to the "add" operation.

"__div": the / operation. Behavior similar to the "add" operation.

"__mod": the % operation. Behavior similar to the "add" operation, with the operation o1 - floor(o1/o2)*o2 as the primitive operation.

"__pow": the ^ (exponentiation) operation. Behavior similar to the "add" operation, with the function pow (from the C math library) as the primitive operation.

"__unm": the unary - operation.

"__concat": the .. (concatenation) operation.

"__len": the # operation.

"__eq": the == operation. The function getequalhandler defines how Lua chooses a metamethod for equality. A metamethod is selected only when both values being compared have the same type and the same metamethod for the selected operation, and the values are either tables or full userdata.

"__lt": the < operation.

"__le": the <= operation.

"__index": The indexing access table[key]. Note that the metamethod is tried only when key is not present in table. (When table is not a table, no key is ever present, so the metamethod is always tried.)

"__newindex": The indexing assignment table[key] = value. Note that the metamethod is tried only when key is not present in table.

"__call": called when Lua calls a value.

强引用 弱引用

objective-c 有这个概念

__mode

协程

function foo (a)
print("foo", a)
    return coroutine.yield(2*a)
end

co = coroutine.create(function (a,b)
    print("co-body", a, b)
    local r = foo(a+1)
    print("co-body", r)
    local r, s = coroutine.yield(a+b, a-b)
    print("co-body", r, s)
    return b, "end"
end)

print("main", coroutine.resume(co, 1, 10))
print("main", coroutine.resume(co, "r"))
print("main", coroutine.resume(co, "x", "y"))
print("main", coroutine.resume(co, "x", "y"))

output:

co-body 1       10
foo     2
main    true    4
co-body r
main    true    11      -9
co-body x       y
main    true    10      end
main    false   cannot resume dead coroutine

关键字

and       break     do        else      elseif    end
false     for       function  goto      if        in
local     nil       not       or        repeat    return
then      true      until     while

操作符

+     -     *     /     %     ^     #
==    ~=    <=    >=    <     >     =
(     )     {     }     [     ]     ::
;     :     ,     .     ..    ...

字符串

a = 'alo\n123"'
a = "alo\n123\""
a = '\97lo\10\04923"'
-- 多行文本
a = [[alo
123"]]
-- 多行文本 任意多个等号
a = [==[
alo
123"]==]

注释

-- 单行注释

--[[
多行注释
--]]

--[=[
任意多等号
--]=]

数字

3     3.0     3.1416     314.16e-2     0.31416E1
0xff  0x0.1E  0xA23p-4   0X1.921FB54442D18P+1

流程控制

if 语句

if exp then
    block
elseif exp then
    block
else
    block
end

while 循环

while exp do
    block
end

do while 循环

repeat
    block
until exp

for 循环

-- for 起始 结束 间隔 do block end
for i=1,10,2 do
    print(i)
end

for in 循环

-- array
for i,v in ipairs(table_name) do
    print(i,v)
end

-- map
for k,v in pairs(table_name) do
    print(k,v)
end

break

-- break 必须在块的最后一行
break

continue

lua没有continue

return

-- return 必须在块的最后一行
return

goto 语句

for i,v in ipairs(a) do
    goto continue
    print(i,v) -- 可以替代continue
    :: continue ::
end

表达式

function f( ... )
    return ...
end

-- 返回值匹配
a, b, c = f(1,2,3)
-- 返回值过多 丢弃4,5
a, b, c = f(1,2,3,4,5)
-- 返回值太少 c为nil
a, b, c = f(1,2)
-- 返回值转换为集合
{f(1,2,3,4)} 
f(6, f(1,2,3,4,5))
-- 第一个值
(f(1,2,3))
{f(), nil}
f(f(1,2,3,4,5), 6)

算数运算 和 优先级

and
<     >     <=    >=    ~=    ==
..
+     -
*     /     %
not   #     - (unary)
^

长度获取

table.maxn(tab)
string.len(str)
rawlen(tab)
rawlen(str)

table

-- 创建
t = {}
t = {1,2,3,4}
t = {name='dotcoo', url="http://www.dotcoo.com/"}

-- 访问
t[1] -- array索引从1开始
t['name'] -- map是使用tab['key']来访问
t.name -- map也可以使用tab.key来访问

-- 修改
t[1] = 10
t['name'] = 'dotcoo2'
t.name = "dotcoo2"

-- 删除
table.remove(t) -- 删除最后一个
table.remove(t, 2) -- 删除指定索引
t['name'] = nil -- 删除指定键,赋值为nil即可
t.name = nil

函数调用

-- 函数调用
f()
f(a,b,c)

-- 默认参数
function f(status) status = status or 'ok' print(status) end

-- 多返回值
return x, y, z, f()

函数定义

-- 函数
function f () body end

-- 类方法 语法糖
function Foo:setName (name) body end

-- 第一个参数是自己
Foo.setName = function ( self, name ) body end

C API

XXX

扩展包

XXX

标准库

Lua functions

_G
_VERSION
assert
collectgarbage
dofile
error
getmetatable
ipairs
load
loadfile
next
pairs
pcall
print
rawequal
rawget
rawlen
rawset
require
select
setmetatable
tonumber
tostring
type
xpcall
bit32.arshift
bit32.band
bit32.bnot
bit32.bor
bit32.btest
bit32.bxor
bit32.extract
bit32.lrotate
bit32.lshift
bit32.replace
bit32.rrotate
bit32.rshift
coroutine.create
coroutine.resume
coroutine.running
coroutine.status
coroutine.wrap
coroutine.yield
debug.debug
debug.getuservalue
debug.gethook
debug.getinfo
debug.getlocal
debug.getmetatable
debug.getregistry
debug.getupvalue
debug.setuservalue
debug.sethook
debug.setlocal
debug.setmetatable
debug.setupvalue
debug.traceback
debug.upvalueid
debug.upvaluejoin
file:close
file:flush
file:lines
file:read
file:seek
file:setvbuf
file:write
io.close
io.flush
io.input
io.lines
io.open
io.output
io.popen
io.read
io.stderr
io.stdin
io.stdout
io.tmpfile
io.type
io.write
math.abs
math.acos
math.asin
math.atan
math.atan2
math.ceil
math.cos
math.cosh
math.deg
math.exp
math.floor
math.fmod
math.frexp
math.huge
math.ldexp
math.log
math.max
math.min
math.modf
math.pi
math.pow
math.rad
math.random
math.randomseed
math.sin
math.sinh
math.sqrt
math.tan
math.tanh
os.clock
os.date
os.difftime
os.execute
os.exit
os.getenv
os.remove
os.rename
os.setlocale
os.time
os.tmpname
package.config
package.cpath
package.loaded
package.loadlib
package.path
package.preload
package.searchers
package.searchpath
string.byte
string.char
string.dump
string.find
string.format
string.gmatch
string.gsub
string.len
string.lower
string.match
string.rep
string.reverse
string.sub
string.upper
table.concat
table.insert
table.pack
table.remove
table.sort
table.unpack

C API

lua_Alloc
lua_CFunction
lua_Debug
lua_Hook
lua_Integer
lua_Number
lua_Reader
lua_State
lua_Unsigned
lua_Writer
lua_absindex
lua_arith
lua_atpanic
lua_call
lua_callk
lua_checkstack
lua_close
lua_compare
lua_concat
lua_copy
lua_createtable
lua_dump
lua_error
lua_gc
lua_getallocf
lua_getctx
lua_getfield
lua_getglobal
lua_gethook
lua_gethookcount
lua_gethookmask
lua_getinfo
lua_getlocal
lua_getmetatable
lua_getstack
lua_gettable
lua_gettop
lua_getupvalue
lua_getuservalue
lua_insert
lua_isboolean
lua_iscfunction
lua_isfunction
lua_islightuserdata
lua_isnil
lua_isnone
lua_isnoneornil
lua_isnumber
lua_isstring
lua_istable
lua_isthread
lua_isuserdata
lua_len
lua_load
lua_newstate
lua_newtable
lua_newthread
lua_newuserdata
lua_next
lua_pcall
lua_pcallk
lua_pop
lua_pushboolean
lua_pushcclosure
lua_pushcfunction
lua_pushfstring
lua_pushglobaltable
lua_pushinteger
lua_pushlightuserdata
lua_pushliteral
lua_pushlstring
lua_pushnil
lua_pushnumber
lua_pushstring
lua_pushthread
lua_pushunsigned
lua_pushvalue
lua_pushvfstring
lua_rawequal
lua_rawget
lua_rawgeti
lua_rawgetp
lua_rawlen
lua_rawset
lua_rawseti
lua_rawsetp
lua_register
lua_remove
lua_replace
lua_resume
lua_setallocf
lua_setfield
lua_setglobal
lua_sethook
lua_setlocal
lua_setmetatable
lua_settable
lua_settop
lua_setupvalue
lua_setuservalue
lua_status
lua_toboolean
lua_tocfunction
lua_tointeger
lua_tointegerx
lua_tolstring
lua_tonumber
lua_tonumberx
lua_topointer
lua_tostring
lua_tothread
lua_tounsigned
lua_tounsignedx
lua_touserdata
lua_type
lua_typename
lua_upvalueid
lua_upvalueindex
lua_upvaluejoin
lua_version
lua_xmove
lua_yield
lua_yieldk

auxiliary library

luaL_Buffer
luaL_Reg
luaL_addchar
luaL_addlstring
luaL_addsize
luaL_addstring
luaL_addvalue
luaL_argcheck
luaL_argerror
luaL_buffinit
luaL_buffinitsize
luaL_callmeta
luaL_checkany
luaL_checkint
luaL_checkinteger
luaL_checklong
luaL_checklstring
luaL_checknumber
luaL_checkoption
luaL_checkstack
luaL_checkstring
luaL_checktype
luaL_checkudata
luaL_checkunsigned
luaL_checkversion
luaL_dofile
luaL_dostring
luaL_error
luaL_execresult
luaL_fileresult
luaL_getmetafield
luaL_getmetatable
luaL_getsubtable
luaL_gsub
luaL_len
luaL_loadbuffer
luaL_loadbufferx
luaL_loadfile
luaL_loadfilex
luaL_loadstring
luaL_newlib
luaL_newlibtable
luaL_newmetatable
luaL_newstate
luaL_openlibs
luaL_optint
luaL_optinteger
luaL_optlong
luaL_optlstring
luaL_optnumber
luaL_optstring
luaL_optunsigned
luaL_prepbuffer
luaL_prepbuffsize
luaL_pushresult
luaL_pushresultsize
luaL_ref
luaL_requiref
luaL_setfuncs
luaL_setmetatable
luaL_testudata
luaL_tolstring
luaL_traceback
luaL_typename
luaL_unref
luaL_where
豫ICP备09035262号-1