lua

lua

lua_pcall 是使用 c 中的 setjmp 实现的, 对应在lua 中的函数就是 pcall

pcall/error 大概就相当于其他语言中的 try-catch /throw了

“`
local ok, errorobject = pcall(function()
    –here goes the protected code
    …
end)

if not ok then
    –here goes the error handling code
    –(errorobject has more information about the error)
    …
end
“`

# 协程

对称协程只有一个关键字: transfer, 类似于 goto 语句, 把控制权移交给其他的任意一个协程; 而非对称协程一般有两个关键字:resume 和 yield, 使用 resume打开一个协程, 然后在这个协程中使用 yield 返回.

学习lua可以获得

* 怎样实现一门语言,编译原理,离散数学
* lua本身
* 虚拟机,jit
* C语言能力的增强

lua 的标准库补充 [Penlight](https://github.com/stevedonovan/Penlight)

![](http://ww4.sinaimg.cn/large/006tNbRwgy1fg3q43bjn9j31kw1rgk1j.jpg)

openresty

1. The *by_lua modules that tweak the nginx behaviour (for ex the rewrite_by_lua that is the lua equivalent of nginx http rewrite) module are always run after the standard nginx modules.
2. The choice of *by_lua module to use largely depends upon the problem that you are trying to solve. For example the init_by_lua module is used for initialization operations where as access_by_lua may be used to implement access policies for a location block. Personally among the various directives I find most use for content_by_lua.

From

http://www.londonlua.org/scripting_nginx_with_lua/slides.html

Lua can access nginx at different phase, the most important directives are:

Rewrite_by_lua
Access_by_lua
Content_by_lua
Init_by_lua
Set_by_lua

Rememeber to set lua_code_cache when developing

Use `ngx.location.capture` to issue a sub-request to other locations in nginx

`ngx.ctx` is a lua table to store data with a lifetime

lua coroutine

Lua 的协程是非对称的协程也就是 resume 和 yeild 相当于调用和返回

Python 的协程是对称的协程, 相当于 goto.

Lua中携程相关的函数都放在coroutine包中
coroutine.create(function) 返回一个thread类型的值表示一个协程,并且处于suspend状态。
resume(co, params…) 执行一个协程,并且能够传递参数,返回运行的状态的函数yield返回的结果