如何在redis\lua中定义函数?

Avi*_*Net 6 lua globals redis node.js

我正在使用 Node.js 和“redis-scripto”模块,我正在尝试在 Lua 中定义一个函数:

 var redis = require("redis");  
 var redisClient = redis.createClient("6379","127.0.0.1");   

 var Scripto = require('redis-scripto');
 var scriptManager = new Scripto(redisClient);
 var scripts = {'add_script':'function add(i,j) return (i+j) end add(i,j)'};

 scriptManager.load(scripts);
 scriptManager.run('add_script', [], [1,1], function(err, result){
                    console.log(err || result);
 });
Run Code Online (Sandbox Code Playgroud)

所以我收到这个错误:

[错误:ERR 运行脚本时出错(调用 .... @enable_strict_lua:7: user_script:1: 脚本试图创建全局变量 'add']

所以我发现它是一种保护,如该线程中所述

scriptingEnableGlobalsProtection的文档字符串表明其意图是将常见错误通知脚本作者(不使用本地)。”

但我还是不明白 - 这个 scripting.c 在哪里?改变全局表的解决方案对我来说似乎有风险。

有没有简单的方法来设置 redis 的功能 - 使用 lua ?

Ale*_*lex 7

看起来脚本运行器正在函数中运行您的代码。所以当你 create 时function add(),它认为你是在一个函数中意外地做它。它也很可能在调用add(i,j). 如果这是正确的,那么这应该有效:

local function add(i,j) return (i+j) end return add(1,1)
Run Code Online (Sandbox Code Playgroud)

如果这有效,那么希望这也适用于您从 js 传递的参数:

local function add(i,j) return (i+j) end return add(...)
Run Code Online (Sandbox Code Playgroud)


Avi*_*Net 2

这对我有用:(更改上面问题的第 5 行):

var scripts = {
'add_script':'local function add(i,j) return (i+j) end return(add(ARGV[1],ARGV[2]))'};
Run Code Online (Sandbox Code Playgroud)

将变量传递给脚本使用 KEYS[] 和 ARGV[],如redis-scripto 指南中所述 ,这里还有一个很好的示例:“ Lua:Redis 用户指南