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

本文共 2215 字,大约阅读时间需要 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://rlvhl.baihongyu.com/

你可能感兴趣的文章
HTML5之桌面提醒
查看>>
IDEA注册机
查看>>
微信APP支付 ,App无法调起微信
查看>>
Spring boot 内嵌tomcat,临时目录不存在 错误
查看>>
fedora16中virtualbox无法启动xp虚假机
查看>>
(十五)用JAVA编写MP3解码器——音频输出
查看>>
MyClouds开发指南》第1章 MyClouds微服务治理及快速开发平台简介
查看>>
mysql 时间格式化
查看>>
用JDK制作可能运行的JAR
查看>>
eval 解析 JSON 格式数据
查看>>
hibernate笔记(六)关于懒加载和load()方法之三——误区
查看>>
消息队里-消息队列应用场景
查看>>
推荐:7 月份值得一看的 Java 技术干货!
查看>>
3.7 Struts2综合应用实例--添加学生信息
查看>>
vscode下的eslint自动修复配置
查看>>
31.TCP设置ip 文件秒传
查看>>
Spring 事件Application Event
查看>>
c++类型转换
查看>>
开发人员如何转型做产品经理
查看>>
Ubuntu 下控制台和UI切换
查看>>