Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

attempt to compare number with string (Lua)

Tags:

lua

I've been programming this

io.write("How many languages do you speak?\n")

answer = io.read()

if (answer == 1)
then
io.write("You're a monolingual beta")
elseif (answer == 2)
 then
 io.write("You're bilingual")
elseif (answer == 3)
 then
 io.write("You're a multilingual semichad")
elseif (answer == 4)
 then
 io.write("You're a polyglot")
elseif (answer == 5)
 then
 io.write("You're a super polyglot")
elseif (answer == 6)
 then
 io.write("You're an hyper polyglot")
elseif (answer == 7)
 then
 io.write("You're a ultra polyglot")
elseif (answer == 8)
 then
 io.write("You're a mega polyglot")
elseif (answer == 9)
 then
 io.write("You're an ultra-mega polyglot")
elseif (answer >= 10)
 then
 io.write("You're an infinite polyglot gigachad")
end

But when i try to execute it and i put a number, it just says the error in the title. The line of code which the error refers is this one

elseif (answer >= 10)

And i can't really understand the issue. There are no strings. Can someone please help me out?

like image 881
TheXXcoder Avatar asked Jun 12 '26 08:06

TheXXcoder


2 Answers

answer variable contains a string as the result of io.read() call. Either add tonumber around io.read() or use io.read("n") to get a number.

like image 97
Paul Kulchenko Avatar answered Jun 15 '26 01:06

Paul Kulchenko


To add an explanation as to how the error comes into being:

io.read() reads a string (a line). answers thus holds the age in string form.

Lua's comparisons are strict; all equality comparisons of strings against numbers fail since strings and numbers are of different types. It eventually falls through to answer >= 10 which throws the error since all ordering relations (<, >, <=, >=) only accept either two strings or two numbers (or two tables with metatables, excepting debug.setmetatable for the sake of simplicity).

answer >= 10 where answer is a string finally throws the error.

like image 24
LMD Avatar answered Jun 15 '26 03:06

LMD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!