openresty下lua的function定義及調用

本文主要研究下如何在openresty下lua的function定義及調用。html

源碼示例

/usr/local/openresty/lualib/resty/string.luanginx

-- Copyright (C) by Yichun Zhang (agentzh)


local ffi = require "ffi"
local ffi_new = ffi.new
local ffi_str = ffi.string
local C = ffi.C
local setmetatable = setmetatable
local error = error
local tonumber = tonumber


local _M = { _VERSION = '0.09' }


ffi.cdef[[
typedef unsigned char u_char;

u_char * ngx_hex_dump(u_char *dst, const u_char *src, size_t len);

intptr_t ngx_atoi(const unsigned char *line, size_t n);
]]

local str_type = ffi.typeof("uint8_t[?]")


function _M.to_hex(s)
    local len = #s * 2
    local buf = ffi_new(str_type, len)
    C.ngx_hex_dump(buf, s, #s)
    return ffi_str(buf, len)
end


function _M.atoi(s)
    return tonumber(C.ngx_atoi(s, #s))
end


return _M

實例

demo.lua

local _M = { _VERSION = '0.01' }
function _M.hello()
    ngx.say("hello from demo module!")
end
return _M

conf

location /function {
            content_by_lua '
                local demo = require("demo")
                demo.hello()
            ';
        }

報錯

2018/03/26 16:24:15 [error] 5#5: *1 lua entry thread aborted: runtime error: content_by_lua(nginx.conf:69):2: module 'demo' not found:
    no field package.preload['demo']
    no file '/usr/local/openresty/lualib/demo.lua'
    no file '/usr/local/openresty/lualib/demo/init.lua'
    no file './demo.lua'
    no file '/usr/local/openresty/luajit/share/luajit-2.1.0-beta2/demo.lua'
    no file '/usr/local/share/lua/5.1/demo.lua'
    no file '/usr/local/share/lua/5.1/demo/init.lua'
    no file '/usr/local/openresty/luajit/share/lua/5.1/demo.lua'
    no file '/usr/local/openresty/luajit/share/lua/5.1/demo/init.lua'
    no file '/usr/local/openresty/lualib/demo.so'
    no file './demo.so'
    no file '/usr/local/lib/lua/5.1/demo.so'
    no file '/usr/local/openresty/luajit/lib/lua/5.1/demo.so'
    no file '/usr/local/lib/lua/5.1/loadall.so'
stack traceback:
coroutine 0:
    [C]: in function 'require'
    content_by_lua(nginx.conf:69):2: in function <content_by_lua(nginx.conf:69):1>, client: 192.168.99.1, server: , request: "GET /function HTTP/1.1", host: "192.168.99.100:8686"

修復

ADD demo.lua /usr/local/openresty/lualib/demo.lua

小結

從源碼能夠看出,基本是定義一個_M變量,裏頭有個_VERSION屬性,而後定義_M的function,最後返回_M。另外注意本身定義的類庫須要放在openresty查找的路徑下面,不然會報錯。git

doc

相關文章
相關標籤/搜索