Searching in Redis evaluating Lua script - lua

I'm trying to search for field value in hash using Lua script and I'm doing something wrong :)
I have key "articles" which is zset holding article IDs and keys article:n where "n" is the article number.
The following script:
local ids = redis.call("zrange", 'articles', '0', '-1')
local ret = {}
for k, id in pairs(ids) do
local row = redis.call("hgetall", "article:"..id)
ret[k] = row
end
return ret
returns this:
1) 1) "slug"
2) "first-title"
3) "title"
4) "first title"
2) 1) "slug"
2) "second-title"
3) "title"
4) "second title"
Than I'm trying to include condition to return only keys containing string "second" in title but it returns nothing.
local ids = redis.call("zrange", 'articles', '0', '-1')
local ret = {}
for k, id in pairs(ids) do
local row = redis.call("hgetall", "article:"..id)
if (string.find(row[4], "second")) then
ret[k] = row
end
end
return ret
Please could you help me?

The table you returned from lua, must be an array whose index staring from 1.
However, In your example, only the second article matches the condition, and its index is 2. So you are, in fact, setting the table as: ret[2] = row. Since the returned table is NOT an array whose index starting from 1, Redis takes it as an empty array, and you get nothing.
Solution:
local ids = redis.call("zrange", 'articles', '0', '-1')
local ret = {}
local idx = 1; -- index starting from 1
for k, id in pairs(ids) do
local row = redis.call("hgetall", "article:"..id)
if (string.find(row[4], "second")) then
ret[idx] = row -- set table
idx = idx + 1 -- incr index by 1
end
end
return ret

Try this condition
if (string.find(row[4], "second") ~= nil) then

Related

How to select multiple random elements from a LUA table?

I'm trying to figure out how to randomly select multiple entries in a table.
This is what I have currently
local letters = {"w", "x", "y", "z"}
function randomletterselect()
local randomletters = {}
for i,v in pairs(letters) do
table.insert(randomletters,i)
end
local letter = letters[randomletters[math.random(#randomletters)]]
-- set multiple selected letters to the new table?
end
randomletterselect()
this code here works for selecting ONE random element(letter) from the table. essentially, when I run this, I want it to be multiple random letters selected. for example, one time it may select x,y another time it may be x,y,z.
The closest thing I found was honestly just what I had figured out, in this post Randomly select a key from a table in Lua
You can do...
randomletterselect=function()
local chars={}
for i=65,math.random(65,90) do
table.insert(chars,string.char(math.random(65,90)):lower())
end
print(table.concat(chars,','))
return chars
end
randomletterselect()
...for lowercase letters.
And this version returns a table without doubles...
randomletterselect=function()
local chars=setmetatable({},{__name='randomletters'})
for i=65,90 do
table.insert(chars,string.char(i):lower())
end
for i=1,math.random(#chars) do
table.remove(chars,math.random(#chars))
end
print(#chars,table.concat(chars,','))
return chars
end
local tbl = {'a', 'b', 'c', 'd'} -- your characters here
local MIN_NUM, MAX_NUM = 1, 2 ^ #tbl - 1
-- if the length of the table has changed, MAX_NUM gonna change too
math.randomseed(os.time())
local randomNum = math.random(MIN_NUM, MAX_NUM)
local function getRandomElements(num)
local rsl = {}
local cnt = 1
while num > 0 do
local sign = num % 2 -- to binary
-- if the num is 0b1010, sign will be 0101
num = (num - sign)/2
if sign == 1 then
local idx = #rsl + 1
-- use tbl[#tbl + 1] to expand the table (array)
rsl[idx] = tbl[cnt]
end
cnt = cnt + 1
end
return table.concat(rsl)
end
print(getRandomElements(randomNum))
I have another method to solve the problem, try.
MIN_NUM should be 1 cuz when its 0, getRandomElements will return an empty string

How to get the size of an array in lua

I'm trying get the size of an array and loop in it. I tried use the getn function, but it didn't work.
Here is my code:
results =
{
address= "Address 1",
type_address= "RESIDENCIAL",
phone= "654620460",
email= "email1#email.com"
},
{
address= "Address 2",
type_address= "COMERCIAL",
phone= "604654650",
email= "email1#email.com"
}
for i = 0, table.getn(results), 1 do
if results[i].type_address == "RESIDENCIAL" then
phone = results[i].phone
email = results[i].email
break
else
phone = results[1].phone
email = results[1].email
end
end
print (phone)
print (email)
To get the size of the table use #tbl for arrays.
You forgot to wrap items into {}. For now you assigned results to table with Address 1, table with Address 2 is ignored because you didn't assign it to anything (due to mistake)
Wrap it like this:
results = {
-- items here
}
Quick note: table.getn is deprecated and identical to #tbl, you can also use
for k,v in ipairs(results) do.
Third parameter of for statement is optional and defaults to 1.
for i = 0, #results do
if results[i].type_address == "RESIDENCIAL" then
-- etc
end
-- or
for k, v in ipairs(results) do
if v.type_address == "RESIDENCIAL" then
-- etc
end
I use...
function(len) local incr=0 for _ in pairs(len) do incr=incr+1 end return incr end
...as a metamethod __index.len for table key counting. Then...
> test_table={'1',two='2',pi=math.pi,popen=io.popen}
> setmetatable(test_table,{__index={len=function(len) local incr=0 for _ in pairs(len) do incr=incr+1 end return incr end}})
table: 0x565aa850
> test_table:len()
4
...it count mixed numbered and named keys correctly. Where...
> #test_table
1
...doesnt.

Inserting row to table, with values two levels deep

When looping through a table trying to add 'sub properties' I get an error that i'm attempting to index field '?'. I am also sure that count and v.name both contain values.
Send help?
count = 0
local tbl = {}
for k,v in pairs(list) do
if string.find(v.name,"Jim") then
count = count + 1
tbl[count] = count
--below throws an error
--tbl[count]["name"] = {v.name}
end
end

Trying to build a table of unique values in LUA

I am trying to build a table and add to it at the end each time I get a returned value that is not already in the table. So basically what I have so far is not working at all. I'm new to LUA but not to programming in general.
local DB = {}
local DBsize = 0
function test()
local classIndex = select(3, UnitClass("player")) -- This isn't the real function, just a sample
local cifound = False
if classIndex then
if DBsize > 0 then
for y = 1, DBsize do
if DB[y] == classIndex then
cifound = True
end
end
end
if not cifound then
DBsize = DBsize + 1
DB[DBsize] = classIndex
end
end
end
Then later I'm trying to use another function to print the contents of the table:
local x = 0
print(DBsize)
for x = 1, DBsize do
print(DB[x])
end
Any help would be much appreciated
Just store a value in the table using your unique value as a key. That way you don't have to check wether a value already exists. You simply overwrite any existing keys if you have it a second time.
Simple example that stores unique values from 100 random values.
local unique_values = {}
for i = 1, 100 do
local random_value = math.random(10)
unique_values[random_value] = true
end
for k,v in pairs(unique_values) do print(k) end

Can't figure out this table arrangement

--The view of the table
local originalStats = {
Info = {Visit = false, Name = "None", Characters = 1},
Stats = {Levels = 0, XP = 0, XP2 = 75, Silver = 95},
Inventory = {
Hats = {"NoobHat"},
Robes = {"NoobRobe"},
Boots = {"NoobBoot"},
Weapons = {"NoobSword"}
}
}
local tempData = {}
--The arrangement here
function Module:ReadAll(player)
for k,v in pairs(tempData[player]) do
if type(v) == 'table' then
for k2, v2 in pairs(v) do
print(k2) print(v2)
if type(v2) == 'table' then
for k3, v3 in pairs(v2) do
print(k3) print(v3)
end
else
print(k2) print(v2)
end
end
else
print(k) print(v)
end
end
end
I'm sorry, but I can't seem to figure out how to arrange this 'ReadAll' function to where It'll show all the correct stats in the right orders.
The output is something like this:
Boots
table: 1A73CF10
1
NoobBoot
Weapons
table: 1A7427F0
1
NoobSword
Robes
table: 1A743D50
1
NoobRobe
Hats
table: 1A73C9D0
1
NoobHat
XP2
75
XP2
75
Levels
2
Levels
2
XP
0
XP
0
Here's a way to print all the elements without double or table reference values showing up.
As the name states, this function will print all the elements within a table, no matter how many nested tables there are inside it. I don't have a way to order them at the moment, but I'll update my answer if I find a way. You can also get rid of the empty spaces in the print line, I just used it so it would look neater. Let me know if it works.
function allElementsInTable(table)
for k,v in pairs(table) do
if type(table[k]) == 'table' then
print(k .. ":")
allElementsInTable(v)
else
print(" " .. k .. " = " .. tostring(v))
end
end
end
--place the name of your table in the parameter for this function
allElementsInTable(originalStats)
After more experimenting, I got this, if anyone wants it, feel free to use it.
tempData = { Info = {Visit = false, Name = 'None'},
Stats = {LVL = 0, XP = 0, Silver = 75},
Inventory = { Armors = {'BasicArmor'},
Weapons = {'BasicSword'} }
}
function Read()
for i, v in pairs(tempData['Info']) do
print(i..'\t',v)
end
----------
for i2, v2 in pairs(tempData['Stats']) do
print(i2..'\t',v2)
end
----------
for i3, v3 in pairs(tempData['Inventory']) do
print(i3..':')
for i4, v4 in pairs(v3) do
print('\t',v4)
end
end
end
Read()
Don't expect table's fields to be iterated with pairs() in some specific order. Internally Lua tables are hashtables, and the order of fields in it is not specified at all. It will change between runs, you can't have them iterated in the same order as they were filled.Only arrays with consecutive integer indices will maintain the order of their elements.

Resources