是否可以在redis中调用其他lua脚本中定义的lua函数?

Tim*_*her 4 lua redis node.js

我试图声明一个没有local关键字的函数,然后从anther脚本调用该函数,但是当我运行命令时它给了我一个错误.

test = function ()    
    return 'test'
end



# from some other script
test()
Run Code Online (Sandbox Code Playgroud)

编辑:

我不敢相信我仍然没有答案.我将详细介绍我的设置.

我正在使用带有redis-scripto包的节点将脚本加载到redis中.这是一个例子.

var Scripto = require('redis-scripto');
var scriptManager = new Scripto(redis);

scriptManager.loadFromDir('./lua_scripts');

var keys    = [key1, key2];
var values  = [val];

scriptManager.run('run_function', keys, values, function(err, result) {
console.log(err, result)
})
Run Code Online (Sandbox Code Playgroud)

和lua脚本.

-- ./lua_scripts/dict_2_bulk.lua

-- turns a dictionary table into a bulk reply table
dict2bulk = function (dict)
    local result = {}
    for k, v in pairs(dict) do
        table.insert(result, k)
        table.insert(result, v)
    end
    return result
end


-- run_function.lua 

return dict2bulk({ test=1 })
Run Code Online (Sandbox Code Playgroud)

引发以下错误.

[Error: ERR Error running script (call to f_d06f7fd783cc537d535ec59228a18f70fccde663): @enable_strict_lua:14: user_script:1: Script attempted to access unexisting global variable 'dict2bulk' ] undefined
Run Code Online (Sandbox Code Playgroud)

Jos*_*iah 5

我会违背接受的答案,因为接受的答案是错误的.

虽然您无法显式定义命名函数,但可以调用可以调用的任何脚本EVALSHA.更具体地说,您通过SCRIPT LOAD或隐式通过显式定义的所有Lua脚本EVAL都可以在全局Lua命名空间中使用f_<sha1 hash>(直到/除非您调用SCRIPT FLUSH),您可以随时调用它们.

您遇到的问题是函数被定义为不带参数,KEYS而且ARGV表实际上是全局变量.因此,如果您希望能够在Lua脚本之间进行通信,则需要对表KEYSARGV表进行修改,或者需要使用标准Redis密钥空间来进行函数之间的通信.

127.0.0.1:6379> script load "return {KEYS[1], ARGV[1]}"
"d006f1a90249474274c76f5be725b8f5804a346b"
127.0.0.1:6379> eval "return f_d006f1a90249474274c76f5be725b8f5804a346b()" 1 "hello" "world"
1) "hello"
2) "world"
127.0.0.1:6379> eval "KEYS[1] = 'blah!'; return f_d006f1a90249474274c76f5be725b8f5804a346b()" 1 "hello" "world"
1) "blah!"
2) "world"
127.0.0.1:6379>

所有这些都说,这完全违反了规范,如果你试图在Redis集群场景中运行它,完全有可能以奇怪的方式停止工作.