Reputation: 6241
I have written some lua script for my node.js project. but some of my lua scripts has same code in it. let me explain first.
my first script returns all the data from given key from 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);
my second script returns top 2 records from the same key from redis.
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);
Now want to call script1.lua from script2.lua like as follows.
script2.lua (Want like as follow)
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.
I had tried above code, but it through following error
Script attempted to access unexisting global variable 'loadfile'
Sorry for my poor explanation.
Upvotes: 2
Views: 3007
Reputation: 26
either use dofile("filename.lua")
to run a file or use loadstring(stringOfCode)
to get a function of a string. Example:
code = "print('hello from string')"
fnc = loadstring(code)
fnc()
or in short:
loadstring("print('hello from string')")()
this will print: hello from string
Upvotes: 1
Reputation: 294
use dofile(filename). and restructure your second lua file as follows:
file2_function = function()
code
code
code
code
return blah,blub
end
then simply call global variable file2_function as follows:
blah,blub = file2_function()
the only ugly thing about this solution is that you create one global variable : file2_function.
Upvotes: 0
Reputation: 27221
This is a redis issue
and here
http://redis.io/commands/script-load
ret_1 = script_load("return 1")
ret_1(conn)
1L
In your case the script doesn't understand what does 'loadfile' mean.
or try this project https://github.com/anvaka/redis-load-scripts
Upvotes: 2