记录:使用lua进行编写脚本时,由于功能逻辑需要,会封装一些公用的函数到lua文件,在需要用到的lua脚本中引入并使用这些函数,但是Lua脚本没有提供include关键词,此时可使用dofile()函数。
例如:
在function.lua中封装了一个打印table数据的公用函数:
-- 封装公用的函数文件
-- lua打印table数据
function LuaPrintTable(t, name)
local spaceAdd = 4
local function getTableStr(t, name, space)
local str = string.format("%s%s = {\n", string.rep(" ", space - spaceAdd), (name or "table"))
local init = false
for k, v in pairs(t) do
if type(v) == "table" then
str = str .. getTableStr(v, k, space + spaceAdd)
else
if type(v) == "string" and string.len(v) > 2 and string.sub(v, 1, 3) == "cs." then
init = true
end
str = str .. string.format("%s%s = %s\n", string.rep(" ", space), k, v)
end
end
str = str .. string.rep(" ", space - spaceAdd) .. "}\n"
return str
end
if (type(t) == "table") then
ngx.print("\n" .. getTableStr(t, name, spaceAdd))
else
ngx.print(t)
end
end
在test.lua中调用此函数:
-- 备注:修改参数跟随轮询文件
local mysql = require "resty.mysql"
local db, err = mysql:new()
if not db then
ngx.say("failed to instantiate mysql: ", err)
return
end
ngx.say("connected to mysql.")
db:set_timeout(1000) -- 1 sec
local ok, err, errno, sqlstate = db:connect{
host = "******",
port = 3306,
database = "ceshi",
user = "root",
password = "root",
max_packet_size = 1024 * 1024 }
if not ok then
ngx.say("failed to connect: ", err, ": ", errno, " ", sqlstate)
return
end
ngx.say("connected to mysql.")
--查询需要生成配置文件的数据
local select_sql = " select * from domain_name where status=8"
res,err,errno,sqlstate = db:query(select_sql)
if not res then
ngx.say("select rows error:",err,",errno:",errno,",sqlstate:",sqlstate)
return
end
-- 打印res的数据类型,输出结果为table
ngx.print(type(res))
-- 加载并编译外部运行脚本
dofile("/usr/local/openresty/nginx/lua/function.lua")
-- 打印table数据
LuaPrintTable(res,'table')
do return end
ngx.say("7777") -- 此句不会输出