【问题标题】:load lua script from another lua script从另一个 lua 脚本加载 lua 脚本
【发布时间】: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


【解决方案1】:

【讨论】:

  • 我仍然有错误:脚本试图访问不存在的全局变量'script_load'
【解决方案2】:

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

code = "print('hello from string')"
fnc = loadstring(code)
fnc()

或者简而言之:

loadstring("print('hello from string')")()

这将打印:hello from string

【讨论】:

    【解决方案3】:

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

    file2_function = function()
    code
    code
    code
    code
    return blah,blub
    end
    

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

    废话,blub = file2_function()

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-08
      • 2019-01-31
      • 2017-07-30
      • 2012-12-21
      • 1970-01-01
      • 1970-01-01
      • 2016-03-05
      相关资源
      最近更新 更多