load lua script from another lua scrpit

Question!

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.



Answers

This is a redis issue

Look at: 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

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



This video can help you solving your question :)
By: admin