lua脚本加载并编译外部的lua运行脚本
发布日期:2021-11-02 06:36:24
浏览次数:22
分类:技术文章
本文共 2084 字,大约阅读时间需要 6 分钟。
记录:使用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) endend
在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") -- 此句不会输出
转载地址:https://blog.csdn.net/weixin_43652106/article/details/107764330 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
初次前来,多多关照!
[***.217.46.12]2024年05月03日 00时23分52秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
动态链接
2019-05-08
内存管理
2019-05-08
数值极值
2019-05-08
mysql日常管理
2019-05-08
mysql数据库管理常用命令
2019-05-08
C++强大背后
2019-05-08
tcp连接和断开流程
2019-05-08
C++程序运行时内存布局之----------this到底是什么?
2019-05-08
Linux man命令数字含义
2019-05-09
pthread_getpecific和pthread_setspecific
2019-05-09
TCP协议--CLOSE_WAIT状态
2019-05-09
TCP协议--TIME_WAIT状态
2019-05-09
MYSQL_FIELD
2019-05-09
Twemproxy源码分析之一 入口函数及启动过程
2019-05-09
twemproxy源码分析之二 nc_run
2019-05-09
Twemproxy源码分析之三:其进程以及时间模型
2019-05-09
twemproxy源码分析之五:zero copy
2019-05-09
多重继承
2019-05-09
网络连接 keepalive
2019-05-09