Lua check if a number/value is nan - lua

I have written a program to print a matrix after some computations and I am getting an output of nan for all elements. I want to break a for loop as soon as the matrix's first element becomes nan to understand the problem. How can I do this? In the terminal, I have printed the matrix a containing nan as all elements and typed a[1][1]=="nan" and a[{{1},{1}}]=="nan" both of which return false. Why are they not returning false and what statement should I use instead?

Your test fails because you are comparing a number with a string, "nan".
If you are sure it's a number, the easiest way is:
if a[1][1] ~= a[1][1] then
because according to IEEE 754, a nan value is considered not equal to any value, including itself.

Two solutions:
local n = 0/0 -- nan
-- first solution
if ( tostring(n) == "nan" ) then
print("is nan!!")
end
-- second solution
if (n ~= n) then
print("is nan!!")
end

Try this:
for x = 1, x2 do -- x2 depends on how big you matrix is.
for y = 1, y2 do -- y2 the same as x2
-- some code depending on how your program works
if a[x][y] == nan then
print( "X:" .. x .. ", Y:" .. y )
break
end
end
end
PS: (nan == nan) is true

Related

pico8 lua: unexpeted change of size of an array

I am seeing some unexpected behaviour when using a table as an array in pico8 lua when compared to regular PUC-Rio lua
If I run the following code using PUC-Rio lua5.4.4 (ubuntu)
local t={}
for i=1,10 do t[i] = i*10 end
t[2]=nil
t[4]=nil
t[6]=nil
t[8]=nil
print()
for i=1,#t do print(t[i]) end
I get the expected output
10
nil
30
nil
50
nil
70
nil
90
100
However if i run the same code with pico-8 I get:
10
This appears triggered only when I delete (ie set to nil) the t[8] element. if I comment out that line then I get the expected on pico8
10
nil
30
nil
50
nil
70
80
90
100
It appears, in pico8 lua, that the #t size of the array changes to 1 when the t[8] element is set to nil.
Both are expected results, the length operator # in lua returns a number n where t[n] ~= nil and t[n+1] == nil, if there are holes (nil value) inside, the result is undefined.
To find the maximum numeric index, in lua 5.1 you can use table.maxn, in other versions you have to write one.
table.maxn = function(t)
local n = 0
for k, v in pairs(t) do
if type(k) == 'number' and k > n then
n = k
end
end
return n
end
It seem that the size operator #t is just not well defined in lua in the presence of nil values.
https://www.lua.org/pil/19.1.html
"undefined behaviour" in a scripting language.. Nice.

My program filters some uneven numbers but also some even numbers

So I need to write a program which gets a table as an input and gives the same table as an output without the values with even keys. So basically I need to filter out the even keys and their values and leave the uneven keys with their values.
local function selecteer_oneven(tabel)
for q, n in ipairs(tabel) do
if (q % 2) == 0 then
table.remove(tabel, q)
end
end
return tabel
end
local function printtabel(tabel)
for k,v in pairs(tabel) do
print(k,v)
end
end
io.write("Geef een lua-tabel: ")
local tabelstring = "t = "..io.read()
local string2tab = loadstring(tabelstring)
string2tab()
local resultaat = selecteer_oneven(t)
printtabel(resultaat)
my input is
{ "aap", "kat", "hond", "paard", "kip", "salamander", "programmeren is leuk" }
and my output is
1 aap
2 hond
3 paard
4 salamander
5 programmeren is leuk
(sorry it is in Dutch)
"Aap", "Hond", "Programmeren is leuk" are the only uneven ones. "paard", and "salamander" are even.
Dont do table.remove on the table you are checking at same time.
Better do a second local table and insert q.
And finaly return the second table...
local function selecteer_oneven(tabel)
local tabel2={}
for q, n in ipairs(tabel) do
if (q % 2) ~= 0 then
table.insert(tabel2, q)
end
end
return tabel2
end
...dont tested - yet ;-)
EDIT: Tested with lua -i
-- <ready>
>function selecteer_oneven(tabel)
local tabel2={}
for q, n in ipairs(tabel) do
if (q % 2) ~= 0 then
table.insert(tabel2, q)
end
end
return tabel2
end
-- <ready>
>dump(selecteer_oneven({1,2,3,4,5,6,7,8,9,10}))
1=1
2=3
3=5
4=7
5=9
-- <ready>
>-- whats dump?
-- <ready>
>code.dump
-- dump()
return function(dump)
for key,value in pairs(dump) do
io.write(string.format("%s=%s\n",key,value))
end
end
-- <ready>

Display score using spritesheet

I would like to know how to display a score using a spritesheet. My game is about point collecting and I want to have this energybar to fill up. When the energybar is full an empty one pops up, the full one will disappear for end-game purposes. The spritesheet I have consists of 70 png images.
I could build it up using if-statements but there has to be a better way. Otherwise it would look something like this
if score == 0 then
display.newImage("00.png", x, y)
end
if score == 1 then
display.newImage("01.png", x, y)
end
if score == 2 then
display.newImage("02.png", x, y)
end
if score == 3 then
display.newImage("03.png", x, y)
end
...
if score == 70 then
display.newImage("70.png", x, y)
end
When the score is 71 it displays "01.png"
Since there seems to be a direct relation between score value and filename you are using (meaning that 00 -> '00.png', 1 -> '01.png', ... 70 -> '70.png' etc), and after score=70, the whole sequence repeats, one way of doing this would be to firstly, getting rid of multiplies of 70, then just appending 0 in front for single digit score. Here's a function that does just that:
-- Given a score, returns correct picture name
-- eg. for score = 01 returns 01.png
local function getFilenameFromScore(score)
while true do
if score < 71 then break end
-- get rid of multiplies of 70 by reducing score by 70
-- until it's 0-70
score = score - 70
end
-- if score is between 0 and 9 (one digit, so length is 1)
-- add 0 in front
-- this could also be done with modulo %
if string.len(score) == 1 then
score = '0' .. score
end
-- append .png and return
return score .. '.png'
end
And later, show score as follows:
local scorePicture = getFilenameFromScore(score)
display.newImage(scorePicture, x, y)
Here, scorePicture will depend on score value in the way you described.

Format string to number with minimum length in lua

For example I need number with minimum 3 digit
"512" --> 512
"24" --> 24.0
"5" --> 5.00
One option is write small function. Using answers here for my case it will be something like this
function f(value, w)
local p = math.ceil(math.log10(value))
local prec = value <= 1 and w - 1 or p > w and 0 or w - p
return string.format('%.' .. prec .. 'f', value)
end
print(f(12, 3))
But may be it is possible just using string.format() or any other simple way?
Ok, it seems this case beyond the string.format power. Thanks to #Schollii, this is my current variant
function f(value, w)
local p = math.ceil(math.log10(value))
local prec = value <= 1 and w - 1 or p > w and 0 or w - p
return string.format('%.' .. prec .. 'f', value)
end
print(f(12, 3))
There is no format code specifically for this since string.format uses printf minus a few codes (like * which would hace simplified the solution I give below). So you have to implement yourself, for example:
function f(num, w)
-- get number of digits before decimal
local intWidth = math.ceil(math.log10(num))
-- if intWidth > w then ... end -- may need this
local fmt='%'..w..'.' .. (w-intWidth) .. 'f'
return string.format(fmt, num)
end
print(f(12, 4))
print(f(12, 3))
print(f(12, 2))
print(f(512, 3))
print(f(24, 3))
print(f(5, 3))
You should probably handle case where integer part doesn't fit in field width given (return ceil or floor?).
You can't. Maximum you can reach - specify floating point precision or digit number, but you can't force output to be like your example. Lua uses C like printf with few limitations reference. Look here for full specifiers list link. Remember unsupported ones.
Writing a function would be the best and only solution, especially as your task looks strange, as it doesn't count decimal dot.

Lua Prime Number Checker

Here is my Lua code for taking user input, and checking if the number entered is prime. My issue is that the program thinks that any even number is not prime, and any odd number is.
print("Enter a number.")
local number = io.read("*n")
function prime(n)
for i = 2, n^(1/2) do
if (n % i) == 0 then
return false
end
return true
end
end
if prime(number) == true then
print("Your number is prime!")
end
if prime(number) == false then
print("Your number is not prime!")
end
Move return true out of the loop.
Hence:
function prime(n)
for i = 2, n^(1/2) do
if (n % i) == 0 then
return false
end
end
return true
end
You return true too soon. You return true as soon as any i meets the condition. You must place the return after the loop.
I know it's an old post but since it's near the top on google I figured it can't hurt to post up my prime finder. It basically does a few simple checks of the obvious stuff and then loops through whats left in a similar fashion to the first example in Jon Ericson' post. Haven't benchmarked it but it seems to cope well enough.
--returns true if prime
function isPrime(n)
local n = tonumber(n)
--catch nil, 0, 1, negative and non int numbers
if not n or n<2 or (n % 1 ~=0) then
return false
--catch even number above 2
elseif n>2 and (n % 2 == 0) then
return false
--primes over 5 end in 1,3,7 or 9
--catch numbers that end in 5 or 0 (multiples of 5)
elseif n>5 and (n % 5 ==0) then
return false
--now check for prime
else
--only do the odds
for i = 3, math.sqrt(n), 2 do
--did it divide evenly
if (n % i == 0) then
return false
end
end
--can defeat optimus
return true
end
end
If you are going to be checking primality, you might as well pick an efficient algorithm. As one answer (cryptically) pointed out, all even numbers greater than 2 are not prime. Therefore, you can short-circuit the check for half the numbers, which doubles the speed to check any particular number:
function check_prime (x)
-- Negative numbers, 0 and 1 are not prime.
if x < 2 then
return false
end
-- Primality for even numbers is easy.
if x == 2 then
return 2
end
if x%2 == 0 then
return false
end
-- Since we have already considered the even numbers,
-- see if the odd numbers are factors.
for i = 3, math.sqrt(x), 2 do
if x%i == 0 then
return false
end
end
return x
end
There are all sorts of optimizations we could apply, but let's take a shot at doing this in a more Lua manner:
function sieve (x)
if x < 2 then
return false
end
-- Assume all numbers are prime until proven not-prime.
local prime = {}
prime[1] = false
for i = 2, x do
prime[i] = true
end
-- For each prime we find, mark all multiples as not-prime.
for i = 2, math.sqrt(x) do
if prime[i] then
for j = i*i, x, i do
prime[j] = false
end
end
end
return prime
end
To use the sieve function:
prime = sieve(number)
if prime[number] then
print("Your number is prime!")
else
print("Your number is not prime!")
end
In my tests, the sieve version is about 6 times faster than the previous algorithm for generating all the primes less than 1 million. (Your mileage may vary.) You can easily check the primality of all numbers less than number at no extra cost. On the other hand, it uses more memory and if you really want check the primality of just one number, it's less efficient.
I would check for primes by dividing the number with 2 and checking if the floor of the division is equal to the division. It looks like this.
if (input/2 == math.floor(input/2)) then
print("is prime")
else
print("is not prime")
end

Resources