lua脚本加载并编译外部的lua运行脚本

记录:使用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") -- 	此句不会输出
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值