[Lua] 使用 LuaRocks 安裝 socket 模組

[Lua] 使用 LuaRocks 安裝 socket 模組

想用 Lua 寫一個查詢網站是否健康的程式,

但 Lua 本身並不支援網路連線,

得先安裝 LuaRocks 這個套件管理器,

再用它來安裝 socket 套件才行~

 

執行下面的指令,來安裝 LuaRocks:

wget https://luarocks.org/releases/luarocks-3.3.1.tar.gz
tar zxpf luarocks-3.3.1.tar.gz
cd luarocks-3.3.1
./configure && make && sudo make install

 

基本上,上面的編譯應該也都不會遇到什麼問題。

問題在於接下來,使用 luarocks 指令安裝 socket 套件…

指令很簡單,執行 sudo luarocks install luasocket 就行:

testuser@localhost ~/luarocks-3.3.1 $ sudo luarocks install luasocket
......
No existing manifest. Attempting to rebuild...
luasocket 3.0rc1-2 is now installed in /Users/testuser/luarocks-3.3.1/./lua_modules (license: MIT)

 

不過這裡有一個雷,待會再提…

LuaRocks 看似裝好了 luasocket,

但是在 Lua 裡面,卻無法使用 require “socket” 敘述來匯入 socket 模組,

說找不到這個模組:

testuser@localhost ~/luarocks-3.3.1 $ lua
Lua 5.4.1  Copyright (C) 1994-2020 Lua.org, PUC-Rio
> require "socket"
stdin:1: module 'socket' not found:
    no field package.preload['socket']
    no file '/usr/local/share/lua/5.4/socket.lua'
    no file '/usr/local/share/lua/5.4/socket/init.lua'
    no file '/usr/local/lib/lua/5.4/socket.lua'
    no file '/usr/local/lib/lua/5.4/socket/init.lua'
    no file './socket.lua'
    no file './socket/init.lua'
    no file '/usr/local/lib/lua/5.4/socket.so'
    no file '/usr/local/lib/lua/5.4/loadall.so'
    no file './socket.so'
stack traceback:
    [C]: in function 'require'
    stdin:1: in main chunk
    [C]: in ?

 

找了半天,後來終於發現地雷…

我原本是在解開 luarocks-3.3.1.tar.gz 的目錄 (luarocks-3.3.1) 下,

執行 luarocks install luasocket,但這會讓 luarocks 搞不清楚狀況,

它可能把那個目錄當成了 LuaRocks 安裝好的系統目錄,

所以把 luasocket 裝到那個目錄下的 lua_modules 子目錄下了…

 

要解決這個問題也很簡單,

到別的目錄去 (像 ~ 家目錄或是 / 根目錄),不會讓 LuaRocks 搞混的地方,

再執行一次 sudo luarocks install luasocket。

這次裝好之後,Lua 裡就可以成功匯入 socket 模組囉:

testuser@localhost ~ $ lua
Lua 5.4.1  Copyright (C) 1994-2020 Lua.org, PUC-Rio
> require "socket"
table: 0x7fe1bb004130	/usr/local/share/lua/5.4/socket.lua

 

(本頁面已被瀏覽過 1,017 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料