openresty開發系列21 lua的模組

2022-06-16 06:42:07 字數 2361 閱讀 4633

openresty開發系列21--lua的模組

從lua5.1開始,lua 加入了標準的模組管理機制,lua 的模組是由變數、函式等已知元素組成的 table,

因此建立乙個模組很簡單,就是建立乙個 table,然後把需要匯出的常量、函式放入其中,最後返回這個 table 就行。

一)模組定義

模組的檔名 和 模組定義引用名稱要一致

-- 檔名為 model.lua

-- 定義乙個名為 model 的模組

model = {}

-- 定義乙個常量

model.constant = "這是乙個常量"

-- 定義乙個函式

function model.func1()

print("這是乙個公有函式")

endlocal function func2()

print("這是乙個私有函式!")

endfunction model.func3()

func2()

endreturn model

二)require 函式

lua提供了乙個名為require的函式用來載入模組。要載入乙個模組,只需要簡單地呼叫就可以了。例如:

require("《模組名》")  或者  require "《模組名》"

執行 require 後會返回乙個由模組常量或函式組成的 table,並且還會定義乙個包含該 table 的全域性變數。

-- test_model.lua 檔案

-- model 模組為上文提到 model.lua

require("model")

print(model.constant)

model.func3()

另一種寫法,給載入的模組定義乙個別名變數,方便呼叫

local m = require("model")

print(m.constant)

m.func3()

以上**執行結果為:

這是乙個常量

這是乙個私有函式!

如:模組定義的model,為local修飾為區域性變數,那只能採用local m = require("model") 引用

三)require 載入機制

我們使用require命令時,系統需要知道引入哪個路徑下的model.lua檔案。

require 用於搜尋 lua 檔案的路徑是存放在全域性變數 package.path 中,

當 lua 啟動後,會以環境變數 lua_path 的值來初始這個環境變數。

如果沒有找到該環境變數,則使用乙個編譯時定義的預設路徑來初始化。

lua檔案的路徑存放在全域性變數package.path中,預設的package.path的值為 print(package.path)

./?.lua;/usr/local/openresty/luajit/share/luajit-2.1.0-beta3/?.lua;/usr/local/share/lua/5.1/?.lua;/usr/local/share/lua/5.1/?/init.lua;/usr/local/openresty/luajit/share/lua/5.1/?.lua;/usr/local/openresty/luajit/share/lua/5.1/?/init.lua

我們執行require("model");相當於把model替換上面的?號,lua就會在那些目錄下面尋找model.lua如果找不到就報錯。

所以我們就知道為什麼會報錯了。

那我們如何解決,我這裡介紹常用的解決方案,編輯環境變數lua_path

在當前使用者根目錄下開啟 .profile 檔案(沒有則建立,開啟 .bashrc 檔案也可以),

例如把 "~/lua/" 路徑加入 lua_path 環境變數裡:

#lua_path

export lua_path="/usr/local/lua/?.lua;;"

檔案路徑以 ";" 號分隔,最後的 2 個 ";;" 表示新加的路徑後面加上原來的預設路徑。

接著,更新環境變數引數,使之立即生效。

source ~/.profile

這時假設 package.path 的值是:

/usr/local/lua/?.lua;./?.lua;/usr/local/openresty/luajit/share/luajit-2.1.0-beta3/?.lua;/usr/local/share/lua/5.1/?.lua;/usr/local/share/lua/5.1/?/init.lua;/usr/local/openresty/luajit/share/lua/5.1/?.lua;/usr/local/openresty/luajit/share/lua/5.1/?/init.lua

那麼呼叫 require("model") 時就會嘗試開啟以下檔案目錄去搜尋目標。

openresty 開發入門

文章目錄 1 openresty 安裝 2 lua 測試程式 3 nginx.conf 檔案配置 4 系統啟動1 openresty 安裝 2 tar xzvf openresty 1.9.15.1.tar.gz 3 進入 openresty 1.9.15.1 4 configure prefix ...

openresty 前端開發入門二

這一章主要介紹介紹怎麼獲取請求引數,並且處理之後返回資料 我們知道http請求通常分為兩種,分別是get,post,在http協議中,get引數通常會緊跟在uri後面,而post請求引數則包含在請求體中,nginx預設情況下是不會讀取post請求引數的,最好也不要試圖使改變這種行為,因為大多數情況下...

openresty 二 使用lua開發

在openresty中使用lua開發 在 usr local openresty nginx conf nginx.conf,修改檔案配置,把下面的新增到要訪問的location中 default type text html content by lua ngx.say hello,world 新...