博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
openresty下lua的function定义及调用
阅读量:7095 次
发布时间:2019-06-28

本文共 2187 字,大约阅读时间需要 7 分钟。

本文主要研究下如何在openresty下lua的function定义及调用。

源码示例

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

-- Copyright (C) by Yichun Zhang (agentzh)local ffi = require "ffi"local ffi_new = ffi.newlocal ffi_str = ffi.stringlocal C = ffi.Clocal setmetatable = setmetatablelocal error = errorlocal tonumber = tonumberlocal _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)endfunction _M.atoi(s)    return tonumber(C.ngx_atoi(s, #s))endreturn _M复制代码

实例

demo.lua

local _M = { _VERSION = '0.01' }function _M.hello()    ngx.say("hello from demo module!")endreturn _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 
, 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查找的路径下面,否则会报错。

doc

转载地址:http://ejaql.baihongyu.com/

你可能感兴趣的文章
uva 11354(最小瓶颈路--多组询问 MST+LCA倍增)
查看>>
简单聊下IO复用
查看>>
使用 Management Studio 进行连接
查看>>
GSS1 - Can you answer these queries I(线段树)
查看>>
Python脚本实现单据体背景色及字段前景色设置
查看>>
php-7.1.11编译选项配置
查看>>
Send Email
查看>>
git 的使用
查看>>
JVM必读----------垃圾收集器详解
查看>>
[网络流24题] 最长递增子序列 (最多不相交路径---网络最大流)
查看>>
js获取文档元素
查看>>
Opencv中的阈值函数
查看>>
java集合练习——Bank
查看>>
PowerDesigner建表
查看>>
好多问题
查看>>
设计模式 装饰者设计模式
查看>>
Hashmap误区
查看>>
LeetCode 209: Minimum Size Subarray
查看>>
二级域名怎么做优化
查看>>
svn冲突意思
查看>>