首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从另一个lua脚本加载lua脚本

从另一个lua脚本加载lua脚本
EN

Stack Overflow用户
提问于 2016-09-13 09:52:33
回答 3查看 2.2K关注 0票数 2

我已经为我的node.js项目编写了一些lua脚本。但我的一些lua脚本中有相同的代码。让我先解释一下。

我的第一个脚本从redis返回来自给定键的所有数据。

script1.lua

代码语言:javascript
复制
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

代码语言:javascript
复制
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 (如下图所示)

代码语言:javascript
复制
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.

我曾尝试过以上代码,但经过了以下错误

代码语言:javascript
复制
Script attempted to access unexisting global variable 'loadfile'

很抱歉我解释得不太好。

EN

回答 3

Stack Overflow用户

发布于 2016-09-13 10:38:49

这是一个红色的问题

看:https://redislabs.com/ebook/redis-in-action/part-3-next-steps-3/chapter-11-scripting-redis-with-lua/11-1-adding-functionality-without-writing-c/11-1-1-loading-lua-scripts-into-redis

还有这里

http://redis.io/commands/script-load

ret_1 =script_load(“返回1") Ret_1(康涅狄格) 1L

在您的例子中,脚本不理解'loadfile‘是什么意思。

或者尝试这个项目https://github.com/anvaka/redis-load-scripts

票数 2
EN

Stack Overflow用户

发布于 2021-04-08 09:49:35

可以使用dofile("filename.lua")运行文件,也可以使用loadstring(stringOfCode)获取字符串的函数。示例:

代码语言:javascript
复制
code = "print('hello from string')"
fnc = loadstring(code)
fnc()

或者简单地说:

代码语言:javascript
复制
loadstring("print('hello from string')")()

这将打印: hello from string

票数 1
EN

Stack Overflow用户

发布于 2018-07-21 08:35:44

使用dofile(文件名)。并将您的第二个lua文件重组如下:

代码语言:javascript
复制
file2_function = function()
code
code
code
code
return blah,blub
end

然后按如下方式简单地调用全局变量file2_function:

blah,blub = file2_function()

这个解决方案唯一丑陋的地方是您创建了一个全局变量: file2_function。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39467078

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档