Lua math.floor return wrong value - lua

.There is my code:
for k,v in pairs(result) do
result[k] = math.floor(v*1000)/1000
if k == 215 then
print(v, math.floor(v*1000))
end
end
for k,v in pairs(extra) do
extra[k] = math.floor(v*1000)/1000
end
Where
result[215] = 113
But when I run it by C++ Lua-Tinker, I get the print:
113, 112999
It's very confusing!

Thank to Egor Skriptunoff, I got the answer.
There is an exmple:
local num1 = 100 + 1300/100
print(num1, math.floor(num1))
local num2 = (1 + 13/100) * 100
print(num2, math.floor(num2))
And the result is:
113 113
113 112
Actually, the num2 = 112.9999999999999..., because of the 13/100.But when use 'print' to show it, there is a round action:
local a=112.99999999999 --(the count of 9 is 11)
print(a)
local b=112.999999999999 --(the count of 9 is 12)
print(b)
the result is:
112.99999999999
113

Related

finding minimum values from a cut table Lua 5.1.5

I have a Lua script that turns a table into segments:
function tablecut(t, n)
local result = {}
local j = 0
for i = 1, #t do
if (i-1) % n == 0 then
j = j + 1
result[j] = {}
end
result[j][#result[j]+1] = t[i]
end
return result
end
output = tablecut({'15', '62', '14', '91', '33', '55', '29', '4'}, 4)
for i = 1, #output do
for j = 1, #output[i] do
io.write(tostring(output[i][j])..' ')
end
print()
end
output:
15 62 14 91
33 55 29 4
And I am trying to find the minima from the cut lists so the output would look like this:
15 62 14 91
min = 14
33 55 29 4
min = 4
Edit: If its of any importance this is how I got it to work on Lua 5.3 but there is no table.move function on Lua 5.1. I can't remember how my thought function worked when I wrote this code.
function indexOf(array, value)
for i, v in ipairs(array) do
if v == value then
return i
end
end
return nil
end
Indicies = {}
Answers = {}
function chunks(lst, size)
local i = 1
local count = 0
return function()
if i > #lst then return end
local chunk = table.move(lst, i, i + size -1, 1, {})
i = i + size
count = count + 1
return count, chunk
end
end
local a = {91,52,19,59,38,29,58,11,717,91,456,49,30,62,43,8,17,15,26,22,13,10,2,23} --Test list
for i, chunk in chunks(a, 4) do
x=math.min(a)
print(string.format("#%d: %s", i, table.concat(chunk, ",")))
table.sort(chunk)
print(math.min(chunk[1]))
table.insert(Answers, chunk[1])
table.insert(Indicies, (indexOf(a, chunk[1])))
Output:
#1: 91,52,19,59
19
#2: 38,29,58,11
11
#3: 717,91,456,49
49
your table cut function could be simplified, and your output for loop needs you use an iterator if you want to get an output simply like you do in your 5.3 script.
function cuttable(t,n)
local binned = {}
for i=1,#t,n do
local bin = {}
for j=1,n do
table.insert(bin, t[i + ((j - 1) % n)])
end
table.insert(binned, bin)
end
return binned
end
For the for loop, we can use ipairs on the output of cuttable keeping things pretty simple, then we just do the same steps of concat then sort and print out our results.
for k, bin in ipairs(cuttable(a,4)) do
local output = "#" .. k .. ":" .. table.concat(bin, ",")
table.sort(bin)
print(output)
print(bin[1])
end
Output
#1:91,52,19,59
19
#2:38,29,58,11
11
#3:717,91,456,49
49
#4:30,62,43,8
8
#5:17,15,26,22
15
#6:13,10,2,23
2
One way to implement the cutting would be using a for loop & unpack. I have handled the case of the length not being divisible by 4 after the for loop to (1) maximize performance (check doesn't need to be done every iteration) and (2) be able to directly pass the values to math.min, which doesn't accept nils.
for i = 1, math.floor(#t / 4), 4 do
print(unpack(t, i, i+4))
print("min = " .. math.min(unpack(t, i, i+4)))
end
-- If #t is not divisible by 4, deal with the remaining elements
local remaining = #t % 4
if remaining > 0 then
print(unpack(t, #t - remaining, remaining))
print("min = " .. math.min(unpack(t, #t - remaining, remaining)))
end

How to get the latest x entries of a table in Lua?

If I have (for example) a table with 300 entries, how would I get the latest x entries only?
I was thinking of doing the next, but I'm wondering if there is a better/more optimized way to do this exact thing.
local TestTable = {}
-- Populate table
for i = 1, 300, 1 do
print('Adding: ' .. i)
table.insert(TestTable , i)
end
-- Get latest x of table
function GetLatestFromTable(OriginalTable, Amount)
local TableLength = #OriginalTable
local Retval = {}
for i = 1, Amount, 1 do
if TableLength - i <= 0 then break end -- Dont allow to go under 0
table.insert(Retval, OriginalTable[TableLength - i])
print("Adding to Retval: " .. OriginalTable[TableLength - i] .. ' (Index: ' .. TableLength - i .. ')')
end
return Retval
end
print(#TestTable)
local LatestTable = GetLatestFromTable(TestTable, 10)
print(#LatestTable)
For keys in sequence (and values are string/number) a call to table.concat() allows range parameter.
local tab = {"One", "Two", "Three", "Four", "Five"}
print(table.concat(tab, '\n', #tab - 1, #tab)) -- Last two entries
See: table.concat()
As mentioned by #Luke100000, one way could be to use Lua custom iterators. In Lua, an iterator is a special function which, when called, will return the next value. It is made possible by the fact that functions are first-class citizen in Lua and they can refer to previous scope with a mecanism named closure.
To answer the question, one could start implement a general iterator over a given range.
function IterateRange (Table, Min, Max)
local ClosureIndex = Min - 1
local ClosureMax = math.min(Max, #Table)
local function Closure ()
if (ClosureIndex < ClosureMax) then
ClosureIndex = ClosureIndex + 1
return Table[ClosureIndex]
end
end
return Closure
end
IterateRange is a function returning an anonymous function. The anonymous function does not take any parameter. It simply update the ClosureIndex index defined in the local scope of IterateRange and return the table value.
The first thing that the anonymous function do is to increment ClosureIndex. For that reason, ClosureIndex must be initialized to Min - 1.
This function works as one might expect:
TestTable = {}
for i = 1, 300, 1 do
print('Adding: ' .. i)
table.insert(TestTable , i)
end
for Value in IterateRange(TestTable, 290, 300) do
print(Value)
end
290
291
292
293
294
295
296
297
298
299
300
Now, it's trivial to reuse this general iterator to iterate over the last N entries of a given table:
function IterateLastEntries (Table, Count)
local TableSize = #Table
local StartIndex = (TableSize - Count)
return IterateRange(Table, StartIndex, TableSize)
end
It also work as one might expect:
TestTable = {}
for i = 1, 300, 1 do
print('Adding: ' .. i)
table.insert(TestTable , i)
end
for Value in IterateLastEntries(TestTable, 10) do
print(Value)
end
290
291
292
293
294
295
296
297
298
299
300
And finally, to summarize all this in a fully copy & pasteable solution:
TestTable = {}
for i = 1, 300, 1 do
print('Adding: ' .. i)
table.insert(TestTable , i)
end
function IterateRange (Table, Min, Max)
local ClosureIndex = Min - 1
local ClosureMax = math.min(Max, #Table)
local function Closure ()
if (ClosureIndex < ClosureMax) then
ClosureIndex = ClosureIndex + 1
return Table[ClosureIndex]
end
end
return Closure
end
function IterateLastEntries (Table, Count)
local TableSize = #Table
local StartIndex = (TableSize - Count)
return IterateRange(Table, StartIndex, TableSize)
end
for Value in IterateLastEntries(TestTable, 10) do
print(Value)
end
This should return:
290
291
292
293
294
295
296
297
298
299
300
I will let the OP update the code in order to achieve the same results for 30 entries.

Reversing an decode function

I'm trying to reverse a decode function. This function takes a string and a key and encodes the string with that key. This is the code:
function decode(key, code)
return (code:gsub("..", function(h)
return string.char((tonumber(h, 16) + 256 - 13 - key + 255999744) % 256)
end))
end
If I input 7A as code and 9990 as key, it returns g
I tried reversing the operators and fed back the output of the decode function but I get an error becauase tonumber() returns nil. How can I reverse this function?
By using the answer to this Lua base coverter and flipping the operators of the decode function, I was able to convert back the input.
This is the whole code:
function encodes(key, code)
return (code:gsub("..", function(h)
return string.char((tonumber(h, 16) + 256 - 13 - key + 255999744) % 256)
end))
end
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
function decodes(key, code)
return (code:gsub(".", function(h)
out = (string.byte(h) - 256 + 13 + key - 255999744) % 256
return basen(out,16)
end))
end
a = encodes(9999, "7c7A")
print(a) --prints: `^
print("----------")
b = decodes(9999, a)
print(b) --prints: 7C7A

How to arrange picture in lua like a grid?

I'm learning lua and I want to arrange my bubble picture with some specific x and y coordinates, here's my code so far, the value of my j and i is only incrementing by 1 instead of the +29, I know I'm lacking some knowledge so any help will be appreciated
local background = display.newImageRect("blueBackground.png",642, 1040)
background.x = display.contentCenterX
background.y = display.contentCenterY
local x = 15
local y=15
for i=15,25 do
for j=15, 25 do
local bubble = display.newImageRect("bubble.png", 23,23)
bubble.x = i
bubble.y = j
j = j + 29
print("j",j)
end
i = i + 29
print("i",i)
end
This should helps you.
From Lua documentation
The for statement has two variants: the numeric for and the
generic for.
A numeric for has the following syntax:
for var=exp1,exp2,exp3 do
something
end
That loop will execute something for each value of var from exp1
to exp2, using exp3 as the step to increment var. This third
expression is optional; when absent, Lua assumes one as the step
value. As typical examples of such loops, we have
for i=1,f(x) do print(i) end
for i=10,1,-1 do print(i) end
Use
for i=15, 29*10+15, 29 do
for j=15, 29*10+15, 29 do
local bubble = display.newImageRect("bubble.png", 23,23)
bubble.x = i
bubble.y = j
print("j",j)
end
print("i",i)
end
or
for i=0, 10 do
for j=0, 10 do
local bubble = display.newImageRect("bubble.png", 23,23)
bubble.x = 15 + i * 29
bubble.y = 15 + j * 29
...

Lua (Lapis) random values returns the same result even using randomseed

At first, I use this:
math.randomseed(os.time())
This function to check:
function makeString(l)
if l < 1 then return nil end
local s = ""
for i = 0, l do
n = math.random(0, 61)--61
n0 = 0
if n < 10 then n0 = n + 48
elseif n < 36 then n0 = n - 10 + 65
else n0 = n - 36 + 97 end
s = s .. string.char(n0)
end
return s
end
If I use this function:
app:match("/tttt", function()
local ss = ""
for i=1,10 do ss = ss .. makeString(30) .. "\n" end
return ss
end)
I receive good different values.
If I use this:
app:match("/ttt", function()
return makeString(30)
end)
and JavaScript jQuery,
:
$("#button5").click(function(){
var ss = ""
for(var i = 0; i < 10; i++)
{
$("#div1").load("/ttt", function() {
ss = ss + $(this).text()
alert(ss);
});
}
$("#div1").text(ss);
});
I recieve the same random strings every one second.
How to fix it? I tried to create database with different random data but I recieve the same strings!!! This is just example I wrote but filling the database gives the same result!##%%
Any ideas to fix it?
I found that this is "feature" of lua to generate random using seconds. Use this link to read more: http://lua-users.org/wiki/MathLibraryTutorial
But the solution which can help is to user /dev/urandom
The link to describe:
http://lua-users.org/lists/lua-l/2008-05/msg00498.html
In my case example:
local frandom = io.open("/dev/urandom", "rb")
local makeString
makeString = function(l)
local d = frandom:read(4)
math.randomseed(d:byte(1) + (d:byte(2) * 256) + (d:byte(3) * 65536) + (d:byte(4) * 4294967296))
if l < 1 then return nil end
local s = ""
for i = 0, l do
local n = math.random(0, 61)
n0 = 0
if n < 10 then n0 = n + 48
elseif n < 36 then n0 = n - 10 + 65
else n0 = n - 36 + 97 end
s = s .. string.char(n0)
end
return s
end

Resources