2014年左右,在组内做分享时写的一个文档,最近翻出来了,在这里记录下

variable

num = 42
str = ‘hello’
is_ok = false

t = {key1 = 'value1', key2 = false}

u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'}
print(u[6.28])  -- prints "tau"

for key, val in pairs(u) do
  print(key, val)
end


v = {'value1', 'value2', 1.21, 'gigawatts'}
for i = 1, #v do
  print(v[i])
end

function fib(n)
  if n < 2 then return 1 end
  return fib(n - 2) + fib(n - 1)
end

flow control

if

if num > 40 then
  print('over 40')
elseif s ~= 'walternate' then  -- ~= is not equals.
  io.write('not over 40\n')  -- Defaults to stdout.
else
  -- Variables are global by default.
  thisIsGlobal = 5  -- Camel case is common.

  -- How to make a variable local:
  local line = io.read()  -- Reads next stdin line.

  -- String concatenation uses the .. operator:
  print('Winter is coming, ' .. line)
end

for loop

karlSum = 0
for i = 1, 100 do  -- The range includes both ends.
  karlSum = karlSum + i
end

repeat loop

repeat
  print('the way of the future')
  num = num - 1
until num == 0

Modules

mod.lua

local M = {}

local function sayMyName()
  print('Hrunkner')
end

function M.sayHello()
  print('Why hello there')
  sayMyName()
end

return M

test.lua

local mod = require('mod')  -- Run the file mod.lua.

mod.sayHello() 

Nginx lua

hello world

location /hellolua {
    default_type 'text/plain';

    content_by_lua '
        local name = ngx.var.arg_name or "Anonymous"
        ngx.say("Hello, ", name, "!")
    ';
}

$> curl http://localhost/hellolua?name=Lua
Hello, Lua!

sub requests

location / {
content_by_lua '
    local res = ngx.location.capture("/sub")
    if res.status >= 500 then 
        ngx.exit(res.status) 
    end
    ngx.status = res.status
    ngx.say(res.body)
';
}

location /sub {
    echo "Hello, Sub-Request!";
}

share data in current request

location /ctx {
    access_by_lua '
        ngx.ctx.userid = 12345
    ';
    content_by_lua '
        ngx.say(ngx.ctx.userid)
    ';
}
$> curl http://localhost/ctx
12345

share data across all requests.

http {
    lua_shared_dict stats 10m;
    server {
        location / {
            content_by_lua '
                ngx.shared.stats:incr("hits", 1)
                ngx.say(ngx.shared.stats:get("hits"))
            ';
        }
    }
}

参考链接