Handling floats in redis - lua

I need to use Redis in a project I am using and was wondering if there was anyway to do proper mathmatic operations and comparisons on floats using LUA scripts(or anyway really). For example, I have a field, and need to multiply it by another field, and compare it to a third field. For example
local staticVal = .2
local dynamicVal2 = redis.pcall('GET', 'dynamicVal2')
local calcVal = dynamicVal * staticVal
local compareVal = 100
if calcVal < compareVal then
return false
else
return true
Is there a possible way to do this, or do I have to just make the GET calls from another language and do the comparison there?
Thank you
Edit:
Or the ability to just compare floating point numbers would be helpful. It seems that a dictionary comparison is done rather than a numerical comparison.
Edit 2:
SET val1 10.5
SET val2 3.5
EVAL "local val1 = redis.pcall('GET','val1'); local val2 = redis.pcall('GET','val2'); if val1 > val2 then return val1 else return val2 end" 0

It seems that a dictionary comparison is done rather than a numerical comparison.
local val1 = redis.pcall('GET','val1');
local val2 = redis.pcall('GET','val2');
if val1 > val2 then ...
Check the type of val1 and val2 (e.g. print(type(val1))). My guess is that they are strings, which is why you're getting a lexical comparison rather than a numerical one.
Lua's native number type is floating point and it has no problem comparing them. If your values are indeed strings, you just need to convert them into numbers (e.g. tonumber(val1)) before comparing them.

Of course you can: in Lua, all the numbers are floats. It is actually more difficult to work with large integer values than with floats (due to the internal numbers representation).
From redis-cli:
set dynamicVal2 100000.0
eval "local staticVal = .2 ; local dynamicVal = tonumber(redis.call('GET', 'dynamicVal2')); local calcVal = dynamicVal * staticVal; local compareVal = 100; if calcVal < compareVal then return false; else return true; end;" 0
(integer) 1
Now using Lua for the example you gave is not that useful: what is done with Lua on server-side could be easily done on client-side with similar efficiency. And it is actually better to do it on client-side if you can. Like with many other data stores, the more you can do on client-side for the same number of roundtrips, the best it is.
It would have been more useful if the Lua script was effectively used to avoid multiple roundtrips to Redis.

Related

Substitute character for integer

I am working on a project where I need to find the integer value substituted from a character which is either 'K' 'M' or 'B'.
I am trying to find the best way for a user to input a string such as "1k" "12k" "100k" and to receive the value back in the appropriate way. Such as a user entering "12k" and I would receive "12000".
I am new to Lua, and I am not that great at string patterns.
if (string.match(text, 'k')) then
print(text)
local test = string.match(text, '%d+')
print(test)
end
local text = "1k"
print(tonumber((text:lower():gsub("[kmb]", {k="e3"}))))
I don't know what factors you use for M and B. What is that supposed to be? Million and billion?
I suggest you use the international standard. kilo (k), mega (M), giga (G) instead.
Then it would look like so:
local text = "1k"
print(tonumber((text:gsub("[mkMG]", {m = "e-3", k="e3", M="e6", G="e9"})))) --and so on
You can match the pattern as something like (%d+)([kmb]) to get the number and the suffix separately. Then just tonumber the first part and map the latter to a factor (using a table, for example) and multiply it with your result.
local factors = { k=1e3, m=1e6, --[and so on]] }
local num, suffix = string.match(text, '(%d+)([kmb])')
local result = tonumber(num) * factors[suffix]

LUA: How to Create 2-dimensional array/table from string

I see several posts about making a string in to a lua table, but my problem is a little different [I think] because there is an additional dimension to the table.
I have a table of tables saved as a file [i have no issue reading the file to a string].
let's say we start from this point:
local tot = "{{1,2,3}, {4,5,6}}"
When I try the answers from other users I end up with:
local OneDtable = {"{1,2,3}, {4,5,6}"}
This is not what i want.
how can i properly create a table, that contains those tables as entries?
Desired result:
TwoDtable = {{1,2,3}, {4,5,6}}
Thanks in advance
You can use the load function to read the content of your string as Lua code.
local myArray = "{{1,2,3}, {4,5,6}}"
local convert = "myTable = " .. myArray
local convertFunction = load(convert)
convertFunction()
print(myTable[1][1])
Now, myTable has the values in a 2-dimensional array.
For a quick solution I suggest going with the load hack, but be aware that this only works if your code happens to be formatted as a Lua table already. Otherwise, you'd have to parse the string yourself.
For example, you could try using lpeg to build a recursive parser. I built something very similar a while ago:
local lpeg = require 'lpeg'
local name = lpeg.R('az')^1 / '\0'
local space = lpeg.S('\t ')^1
local function compile_tuple(...)
return string.char(select('#', ...)) .. table.concat{...}
end
local expression = lpeg.P {
'e';
e = name + lpeg.V 't';
t = '(' * ((lpeg.V 'e' * ',' * space)^0 * lpeg.V 'e') / compile_tuple * ')';
}
local compiled = expression:match '(foo, (a, b), bar)'
print(compiled:byte(1, -1))
Its purpose is to parse things in quotes like the example string (foo, (a, b), bar) and turn it into a binary string describing the structure; most of that happens in the compile_tuple function though, so it should be easy to modify it to do what you want.
What you'd have to adapt:
change name for number (and change the pattern accordingly to lpeg.R('09')^1, without the / '\0')
change the compile_tuple function to a build_table function (local function build_tanle(...) return {...} end should do the trick)
Try it out and see if something else needs to be changed; I might have missed something.
You can read the lpeg manual here if you're curious about how this stuff works.

Return multiple values to a function, and access them separately in Lua?

If I have a function that returns multiple values, how can I access those values separately? Something like table[i].
angles = function()
x = function()
local value = 0
return value
end
y = function()
local value = 90
return value
end
z = function()
local value = 180
return value
end
return x(), y(), z()
end
A problem arises here when wanting to use, for example, the x value separately, while keeping it in the function angles.
print(????)
Sort of wish functions worked like tables in this respect, so I could type something like print(angles.x)
Also, I know that code seems really redundant, but it's actually a much more simplified version of what I'm actually using. Sorry if it makes less sense that way.
x, y, z= angles()
print (x,y,z)
There's a couple of ways to do this.
Most obvious would be
local x, y, z = angles()
print(x)
If you want the first value specifically
local x = ( angles() )
-- `local x = angles()` would work too. Lua discards excess return values.
print(x)
or, somewhat less readably
print((angles()))
You could also return a table from the function, or use the standard module table to pack the return values into one.
local vals = table.pack(angles())
print(vals[1])
Another way of accessing them individually (as the question wording implies) rather than all at once is this:
print((select(1,angles())))
print((select(2,angles())))
print((select(3,angles())))
Output:
0
90
180
The select() call needs to be in parentheses in order to return individual entries rather than all after the given offset.

How to return very long integer in Lua

I am trying to return very long integer number but my result returns as
"7.6561197971049e+016".
How do I make it return 76561197971049296 ?
local id64 = 76561197960265728
Z = string.match("STEAM_0:0:5391784", 'STEAM_%d+:%d+:(%d+)')
Y = string.match("STEAM_0:0:5391784", 'STEAM_%d+:(%d+):%d+')
--For 64-bit systems
--Let X, Y and Z constants be defined by the SteamID: STEAM_X:Y:Z.
--Let V be SteamID64 identifier of the account type (0x0110000100000000 in hexadecimal format).
--Using the formula W=Z*2+V+Y
if Z == nil then
return "none"
else
return Z*2+id64+Y
end
I installed lbc arbitrary precision now with this code
return bc.add(bc.number(id64),bc.number(2)):tostring()
it returns 70000000000000002 but if I delete 3 digits from id64 it displays correctly.
How can I get correct result without deleting the digits?
You need to use strings for long numbers. Otherwise, the Lua lexer converts them to doubles and loses precision in this case. Here is code using my lbc:
local bc=require"bc"
local id64=bc.number"76561197960265728"
local Y,Z=string.match("STEAM_0:0:5391784",'STEAM_%d+:(%d+):(%d+)')
if Z == nil then
return "none"
else
return (Z*2+id64+Y):tostring()
end
check out this library for arbitrary precision arithmetics. this so post might be of interest to you as well.
Assuming your implementation of Lua supports that many significant digits in the number type, your return statement is returning that result.
You're probably seeing exponential notation when you convert the number to a string or printing it. You can use the string.format function to control the conversion:
assert( "76561197971049296" == string.format("%0.17g", 76561197971049296))
If number is an IEEE-754 double, then it doesn't work. You do have to know how your Lua is implemented and keep in mind the the technical limitations.
If you have luajit installed, you can do this:
local ffi = require("ffi")
steamid64 = tostring(ffi.new("uint64_t", 76561197960265728) + ffi.new("uint64_t", tonumber(accountid)))
steamid64 = string.sub(steamid64, 1, -4) -- to remove 'ULL at the end'
Hope it helps.

Lua base converter

I need a base converter function for Lua. I need to convert from base 10 to base 2,3,4,5,6,7,8,9,10,11...36 how can i to this?
In the string to number direction, the function tonumber() takes an optional second argument that specifies the base to use, which may range from 2 to 36 with the obvious meaning for digits in bases greater than 10.
In the number to string direction, this can be done slightly more efficiently than Nikolaus's answer by something like this:
local floor,insert = math.floor, table.insert
function basen(n,b)
n = floor(n)
if not b or b == 10 then return tostring(n) end
local digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
local t = {}
local sign = ""
if n < 0 then
sign = "-"
n = -n
end
repeat
local d = (n % b) + 1
n = floor(n / b)
insert(t, 1, digits:sub(d,d))
until n == 0
return sign .. table.concat(t,"")
end
This creates fewer garbage strings to collect by using table.concat() instead of repeated calls to the string concatenation operator ... Although it makes little practical difference for strings this small, this idiom should be learned because otherwise building a buffer in a loop with the concatenation operator will actually tend to O(n2) performance while table.concat() has been designed to do substantially better.
There is an unanswered question as to whether it is more efficient to push the digits on a stack in the table t with calls to table.insert(t,1,digit), or to append them to the end with t[#t+1]=digit, followed by a call to string.reverse() to put the digits in the right order. I'll leave the benchmarking to the student. Note that although the code I pasted here does run and appears to get correct answers, there may other opportunities to tune it further.
For example, the common case of base 10 is culled off and handled with the built in tostring() function. But similar culls can be done for bases 8 and 16 which have conversion specifiers for string.format() ("%o" and "%x", respectively).
Also, neither Nikolaus's solution nor mine handle non-integers particularly well. I emphasize that here by forcing the value n to an integer with math.floor() at the beginning.
Correctly converting a general floating point value to any base (even base 10) is fraught with subtleties, which I leave as an exercise to the reader.
you can use a loop to convert an integer into a string containting the required base. for bases below 10 use the following code, if you need a base larger than that you need to add a line that mapps the result of x % base to a character (usign an array for example)
x = 1234
r = ""
base = 8
while x > 0 do
r = "" .. (x % base ) .. r
x = math.floor(x / base)
end
print( r );

Resources