Use nginx lua extension with custom lua in C-modules

170 views
Skip to first unread message

Dmitry Belyaev

unread,
Mar 9, 2016, 3:20:19 AM3/9/16
to openresty-en
Hi,

How to use custom Lua modules written in C in Nginx?

1) It is clear how to extend Lua with C: http://www.troubleshooters.com/codecorn/lua/lua_lua_calls_c.htm
Tried test samples -> all work good

2) It is clear how to use Lua modules with nginx written in Lua: https://github.com/openresty/lua-nginx-module#statically-linking-pure-lua-modules
Tried test samples -> all work good

But modules written in C and compiled as ".o" or ".so" object are not working.

1) I configure nginx with --with-ld-opt="-Wl,-rpath,/path/to/luajit-or-lua/lib,/<path>/mylua.o"
Content of "mylua.c"
--------------------------------------------------
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"

typedef int (*lua_CFunction) (lua_State *L);

lua_State* L;

static int test(lua_State *L)
{
    int x = 777;
    lua_pushnumber(L, x);
    return 1;
}

int luaopen_mylua(lua_State *L)
{
    lua_register(L, "test", test);
    return 0;
}
--------------------------------------------------

2) This module works if use it in lua, like:
lua> require("mylua");
print(test()); -- Prints "777"

3) Nginx is compiling correctly

4) When I use in nginx config:
content_by_lua_file '/opt/nginx/test.lua';

Content of /opt/nginx/test.lua
local foo = require("mylua");
ngx.say(foo.test());

I'm receiving the error:
[error] 9375#0: *1 lua entry thread aborted: runtime error: /opt/nginx/test.lua:1: module 'mylua' not found:
no field package.preload['mylua']

The names of modules and files are 100% correct. Checked 10x times.
I suppose that lua C-module must be compiled with "luajit".

Thanks in advance

Yichun Zhang (agentzh)

unread,
Mar 16, 2016, 3:42:57 PM3/16/16
to openresty-en
Hello!

On Wed, Mar 9, 2016 at 12:20 AM, Dmitry Belyaev wrote:
> I'm receiving the error:
> [error] 9375#0: *1 lua entry thread aborted: runtime error:
> /opt/nginx/test.lua:1: module 'mylua' not found:
> no field package.preload['mylua']
>

Looks like a Lua module search path issue. Have you configured the
lua_package_cpath directive properly?

See

https://github.com/openresty/lua-nginx-module#lua_package_cpath

> The names of modules and files are 100% correct. Checked 10x times.
> I suppose that lua C-module must be compiled with "luajit".
>

No, as long as your DSO is compiled using the Lua 5.1 ABI. LuaJIT is
compatible with the Lua 5.1 ABI.

Regards,
-agentzh
Reply all
Reply to author
Forward
0 new messages