【发布时间】:2017-01-20 21:08:26
【问题描述】:
我已经为我的 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'
对不起,我的解释很糟糕。
【问题讨论】:
-
你是如何执行 lua 脚本的?
-
@hjpotter92 使用 luaScriptManager luaScriptManager.loadFromDir(path + '/script2.lua');
-
你不能(正式)从 Redis 中的另一个脚本调用一个脚本。
标签: node.js lua redis eval lua-table