我已经为我的node.js项目编写了一些lua脚本。但我的一些lua脚本中有相同的代码。让我先解释一下。
我的第一个脚本从redis返回来自给定键的所有数据。
script1.lua
local data = {};
local keyslist = redis.call('keys', 'day:*');
local key, redisData;
for iCtr = 1, #keyslist do
key = string.gsub(keyslist[iCtr], 'day:','');
redisData = redis.call('hmget', keyslist[iCtr], 'users');
table.insert(data, {date=key, users=redisData[1]});
end
return cjson.encode(data);我的第二个脚本从redis返回相同键的前2条记录。
script2.lua
local data = {};
local keyslist = redis.call('keys', 'day:*');
local key, redisData;
for iCtr = 1, #keyslist do
if iCtr < 3
key = string.gsub(keyslist[iCtr], 'day:','');
redisData = redis.call('hmget', keyslist[iCtr], 'users');
table.insert(data, {date=key, users=redisData[1]});
end
end
return cjson.encode(data);现在想从script2.lua调用script1.lua,如下所示。
script2.lua (如下图所示)
local file = assert(loadfile("script1.lua"));
return file(2) -- return only top 2 records where needed.
-- some forLoop logic will be change as per about need.我曾尝试过以上代码,但经过了以下错误
Script attempted to access unexisting global variable 'loadfile'很抱歉我解释得不太好。
发布于 2016-09-13 10:38:49
这是一个红色的问题
还有这里
http://redis.io/commands/script-load
ret_1 =script_load(“返回1") Ret_1(康涅狄格) 1L
在您的例子中,脚本不理解'loadfile‘是什么意思。
发布于 2021-04-08 09:49:35
可以使用dofile("filename.lua")运行文件,也可以使用loadstring(stringOfCode)获取字符串的函数。示例:
code = "print('hello from string')"
fnc = loadstring(code)
fnc()或者简单地说:
loadstring("print('hello from string')")()这将打印: hello from string
发布于 2018-07-21 08:35:44
使用dofile(文件名)。并将您的第二个lua文件重组如下:
file2_function = function()
code
code
code
code
return blah,blub
end然后按如下方式简单地调用全局变量file2_function:
blah,blub = file2_function()
这个解决方案唯一丑陋的地方是您创建了一个全局变量: file2_function。
https://stackoverflow.com/questions/39467078
复制相似问题