什么是Luarocks
Luarocks是一个Lua包管理器,基于 Lua 语言开发,提供一个命令行的方式来管理 Lua 包依赖、安装第三方 Lua 包等,社区比较流行的包管理器之一
Python具有PIP,Ruby具有Gems,Java具有Maven,Node具有npm,Lua具有Luarocks。
前要:先看Lua的require
以openresty中的Luajit/usr/local/openresty/luajit/bin/luajit
为例:
测试代码:
local cjson = require "cjson"
local s = cjson.encode({"test", "lua", "package"})
print(s)
执行结果:
/usr/local/openresty/luajit/bin/luajit: test.lua:3: module 'cjson' not found:
no field package.preload['cjson']
no file './cjson.lua'
no file '/usr/local/openresty/luajit/share/luajit-2.1.0-beta3/cjson.lua'
no file '/usr/local/share/lua/5.1/cjson.lua'
no file '/usr/local/share/lua/5.1/cjson/init.lua'
no file '/usr/local/openresty/luajit/share/lua/5.1/cjson.lua'
no file '/usr/local/openresty/luajit/share/lua/5.1/cjson/init.lua'
no file './cjson.so'
no file '/usr/local/lib/lua/5.1/cjson.so'
no file '/usr/local/openresty/luajit/lib/lua/5.1/cjson.so'
no file '/usr/local/lib/lua/5.1/loadall.so'
stack traceback:
[C]: in function 'require'
test.lua:3: in main chunk
[C]: at 0x004055d0
从测试结果可以看到,require有几个搜索目录,理论上任意目录都可以
Luarocks包管理
我们软件开发过程中会引入大量库。如果简单把所有库都放入代码仓,那会造成大量的混乱。因此,更适合的办法是,使用luarocks包管理工具,将库安装到库目录。
示例:luarocks 安装 cjson
以openresty中的Luajit/usr/local/openresty/luajit/bin/luajit
为例:
/usr/local/openresty/luajit/bin/luarocks install lua-cjson
Installing /luarocks.org/lua-cjson-2.1.0.10-1.src.rock
lua-cjson 2.1.0.10-1 depends on lua >= 5.1 (5.1-1 provided by VM)
gcc -O2 -fPIC -I/usr/local/openresty/luajit/include/luajit-2.1 -c lua_cjson.c -o lua_cjson.o
gcc -O2 -fPIC -I/usr/local/openresty/luajit/include/luajit-2.1 -c strbuf.c -o strbuf.o
gcc -O2 -fPIC -I/usr/local/openresty/luajit/include/luajit-2.1 -c fpconv.c -o fpconv.o
gcc -shared -o cjson.so lua_cjson.o strbuf.o fpconv.o
No existing manifest. Attempting to rebuild...
lua-cjson 2.1.0.10-1 is now installed in /usr/local/openresty/luajit (license: MIT)
# find /usr/local/openresty/luajit -name cjson.so
/usr/local/openresty/luajit/lib/lua/5.1/cjson.so
luarocks 安装nettle
# find /usr/local/openresty/luajit -name *nettle*
/usr/local/openresty/luajit/lib/luarocks/rocks-5.1/lua-resty-nettle
/usr/local/openresty/luajit/lib/luarocks/rocks-5.1/lua-resty-nettle/2.1-1/lua-resty-nettle-2.1-1.rockspec
/usr/local/openresty/luajit/share/lua/5.1/resty/nettle
/usr/local/openresty/luajit/share/lua/5.1/resty/nettle/types/nettle-types.lua
/usr/local/openresty/luajit/share/lua/5.1/resty/nettle.lua