Manish Sapkal
Manish Sapkal

Reputation: 6241

load lua script from another lua script

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

Answers (3)

Ensber
Ensber

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

KGM
KGM

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

Vyacheslav
Vyacheslav

Reputation: 27221

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

Upvotes: 2

Related Questions