1

I wrote a Lua code to arrange a list but when I enter any number with 2 decimals as 10, 20, etc. in the list, the variable 'ordenado' always takes the value 1 although whether it fulfills the conditions or not.

valor = {}
ordenado = 0

function inicializar ()
  for i = 1,10 do
    print ("Introduzca el valor "..i..":")
    valor[i] = io.read()  
  end 
end

function verificar ()
  for i = 2, #valor do
    if valor[i]>valor[i-1] then
      ordenado = ordenado + 0
    else
      ordenado = ordenado + 1
    end
    print ("actual: "..valor[i].." \nanterior: "..valor[i-1].."\nordenado:"..ordenado.."\n")
  end
end

function imprimir()
  if ordenado == 0 then
    print "La lista esta ordenada"
  else 
    print "La lista no esta ordenada"
  end
end

a = inicializar()
a = verificar()
a = imprimir()

The Lua version is 5.2.

4
  • 1
    What do you intend with a statement like ordenado = ordenado + 0? Commented Mar 12, 2014 at 15:36
  • 2
    Use valor[i] = tonumber(io.read()) to get numbers, not strings Commented Mar 12, 2014 at 15:38
  • faranwath: It is because the next function if the list is arranged then ordenado only take the value 0 and the program print that the list is arrenged. Sorry to write the code in Spanish Commented Mar 12, 2014 at 19:19
  • @EgorSkriptunoff Skriptunoff: you right, with this valor[i] = tonumber(io.read()) it work now Commented Mar 12, 2014 at 22:36

1 Answer 1

1

The line valor[i] = io.read() stores a string in valor[i]. As strings, "2" > "10".

Sign up to request clarification or add additional context in comments.

2 Comments

Won't I have this problem if I write valor[i] = tonumber(io.read())?
@Dominuskernel, probably not. Try it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.