function definition and call of lua under openresty


This paper mainly studies how to define and call lua function in openresty.

Example of source code


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

local ffi = require "ffi"
local 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' }

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)

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

return _M



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


        location /function {
            content_by_lua '
                local demo = require("demo")

Report errors

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/'
	no file './'
	no file '/usr/local/lib/lua/5.1/'
	no file '/usr/local/openresty/luajit/lib/lua/5.1/'
	no file '/usr/local/lib/lua/5.1/'
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:, server: , request: "GET /function HTTP/1.1", host: ""


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


From the source code, it can be seen that the basic definition is to define a variable with a VERSION attribute, then define the function of the variable, and finally return to the variable. In addition, note that the self-defined class library needs to be placed under the path of openresty search, otherwise an error will be reported.


Tags: Nginx Attribute

Posted on Tue, 31 Mar 2020 10:57:48 -0700 by nitm