Lua and if then statements

PvtBonesPvtBones Join Date: 2004-04-25 Member: 28187Members
<div class="IPBDescription">gwargh!</div>so I've trying to teach myself lua (basically just messing around and google/youtube)

I've been trying to make a super simple guess the random number game but I've run into a wall I can't seem to figure out. when I've looked online for other examples they are alot more complicated than what I am trying to do (and using functions I've yet to touch)

<div class='codetop'>CODE</div><div class='codemain' style='height:200px;white-space:pre;overflow:auto'>math.randomseed(os.time()) \\from what I understand math.random kinda fails to make a random number on the first go, I've seen this recommended to do first.
io.write ("what is your name?\n")
name = io.read()
io.write ("Hi ", name, "\n")

io.write ("Lets play a game ", name ," guess the number between 1 and 10\n")

guess = io.read()
numb = math.random(1,3)

if guess == numb then
io.write ("Good guess", name ,":)\n")
else
io.write ("Bad luck ", name, " , The number was ", numb, " :(\n")
end

</div>

to me this seems a logical way to get from a to b but whenever I test the scenario, I get the else statement even if I guess the number correctly

as in:
"
>what is your name?
adk
>Hi adk
>Lets play a game adk guess the number between 1 and 10
3
>Bad luck adk , The number was 3 :("

halp?

Comments

  • remiremi remedy [blu.knight] Join Date: 2003-11-18 Member: 23112Members, Super Administrators, Forum Admins, NS2 Developer, NS2 Playtester
    edited September 2012
    your problem is io.read() returns a string, math.random() returns a number. You need to convert io.read to a number before doing your equality test (or numb to a string, but that's silly)

    Also, random number generators aren't actually just like rolling a dice. They run a formula to psuedo-randomly choose the next number, but if you start with the same seed the sequence you get will always be the same. That's why people generally use the current time as a seed, it's "random" enough that after calling that there is no predictability to what will be returned by math.random. During debugging it can actually be better to use a static seed ( math.randomseed(5) ) so that your random numbers will always be the same... In your case, this would mean you would always know which number the program selected, and you could just do the "time" seed once you're sure your program is functioning.

    Also there's this great reference book that's free online:
    <a href="http://www.lua.org/pil/" target="_blank">http://www.lua.org/pil/</a>

    It's for the previous version of Lua, but is still correct for most of the basics. I've been reading the second edition one myself. Lua's a pretty awesome and powerful language. :)
  • SwiftspearSwiftspear Custim tital Join Date: 2003-10-29 Member: 22097Members
    edited September 2012
    to expand a little on what Psych said about the actual cause of your problem...

    In computer languages there are different types of variables. This is due to computers needing to be able to handle many different types of symbolic representations of what things mean. You can think of it a little like metric measurements vs imperial measurements. If someone says it's 40 degrees outside, you need other information in order to determine weather they mean it's really hot or it's really cold out.

    Computers never just guess at what you mean, they deal with absolute correct statements only, this is the main reason why programming is hard, because you know exactly what you want the computer to do, but you have to figure out the exact language for telling it how to do that.

    Therefore, when the computer asks you to type in a number, it does not read what you respond as a number, it reads it as a string (one or more items in a row) of 32 bit binary characters, because you might have well typed "steve" rather than typing "6". Since you are free to type in any input you like, the computer cannot guess absolutely correctly that the type of input you are giving it fits into a number.

    As the programmer, it's your job to decide how you want the input to be interpreted by the computer. What you will want to do, is convert the input given by the user from the type "string" into the type "integer". In lua you can use the function toNumber() to convert from a string to a number. Honestly, lua is a little ugly in this regard because it hides type casting half the time but doesn't hide it the other half.

    read the section on Coercion on the bottom of this page for more information: <a href="http://lua-users.org/wiki/NumbersTutorial" target="_blank">http://lua-users.org/wiki/NumbersTutorial</a>

    [edit] I would do it this way:
    <div class='codetop'>CODE</div><div class='codemain' style='height:200px;white-space:pre;overflow:auto'> guess = tonumber(io.read())
    numb = math.random(1,3)

    if guess == nil then
    io.write ("Only numbers are valid, sorry ", name ,":)\n")
    else if guess == numb then
    \\the rest of your code goes here</div>
  • PvtBonesPvtBones Join Date: 2004-04-25 Member: 28187Members
    thank you both for your help. I for some silly reason thought lua was able to determine strings from numbers and vice versa (I'm going to blame coercion >_>)

    Swiftspear: that is deffinately better code than what I did.

    been appearently too long since highschool programming XD
  • SwiftspearSwiftspear Custim tital Join Date: 2003-10-29 Member: 22097Members
    <!--quoteo(post=1984284:date=Sep 28 2012, 05:25 PM:name=PvtBones)--><div class='quotetop'>QUOTE (PvtBones @ Sep 28 2012, 05:25 PM) <a href="index.php?act=findpost&pid=1984284"><{POST_SNAPBACK}></a></div><div class='quotemain'><!--quotec-->thank you both for your help. I for some silly reason thought lua was able to determine strings from numbers and vice versa (I'm going to blame coercion >_>)

    Swiftspear: that is deffinately better code than what I did.

    been appearently too long since highschool programming XD<!--QuoteEnd--></div><!--QuoteEEnd-->
    Like I say, Lua is a little derpy. It WILL determine numbers in strings if you put them into mathematical statements (IE, 1 + "1" = x) but not if they're in logical statements. It's sort of half way between a strongly typed language and a weakly typed language.

    What you could have done is <div class='codetop'>CODE</div><div class='codemain' style='height:200px;white-space:pre;overflow:auto'>guess = io.read() + 0</div>

    that would have automatically casted guess to a number, however, if the user did something fun like entering "steve" instead of "5", then it would barf an error, which is fine for testing purposes, but you'd have to learn error handling to make it run nicely again and not be prone to barfing uncontrolled errors.

    ----------------------------------

    out of curiosity, is there a specific reason you've chosen to work with Lua? Lua is very easy for experienced programmers to learn, but the weird inconsistencies like the one you just encountered here can make it a bit frustrating for someone without significant programming experience to start with as their first language.
  • spellman23spellman23 NS1 Theorycraft Expert Join Date: 2007-05-17 Member: 60920Members
    <!--quoteo(post=1985486:date=Oct 1 2012, 12:00 AM:name=Swiftspear)--><div class='quotetop'>QUOTE (Swiftspear @ Oct 1 2012, 12:00 AM) <a href="index.php?act=findpost&pid=1985486"><{POST_SNAPBACK}></a></div><div class='quotemain'><!--quotec-->out of curiosity, is there a specific reason you've chosen to work with Lua? Lua is very easy for experienced programmers to learn, but the weird inconsistencies like the one you just encountered here can make it a bit frustrating for someone without significant programming experience to start with as their first language.<!--QuoteEnd--></div><!--QuoteEEnd-->

    Recommendation Python for easy coding (and less pain with variable conversion) or get in the grime with C++ (you will learn all that is good and bad about languages or perish. mmm strongly-typed languages)
  • remiremi remedy [blu.knight] Join Date: 2003-11-18 Member: 23112Members, Super Administrators, Forum Admins, NS2 Developer, NS2 Playtester
    edited October 2012
    <!--quoteo(post=1985486:date=Oct 1 2012, 12:00 AM:name=Swiftspear)--><div class='quotetop'>QUOTE (Swiftspear @ Oct 1 2012, 12:00 AM) <a href="index.php?act=findpost&pid=1985486"><{POST_SNAPBACK}></a></div><div class='quotemain'><!--quotec-->out of curiosity, is there a specific reason you've chosen to work with Lua? Lua is very easy for experienced programmers to learn, but the weird inconsistencies like the one you just encountered here can make it a bit frustrating for someone without significant programming experience to start with as their first language.<!--QuoteEnd--></div><!--QuoteEEnd-->
    Really? To me it seems that Lua is extremely simple. Like much moreso than any other language. Maybe it's because I'm an experienced programmer that I get it easily, but it seems to me that the only weirdness is more like how you do a ternary operator in lua.


    <!--quoteo(post=1985992:date=Oct 1 2012, 10:26 PM:name=spellman23)--><div class='quotetop'>QUOTE (spellman23 @ Oct 1 2012, 10:26 PM) <a href="index.php?act=findpost&pid=1985992"><{POST_SNAPBACK}></a></div><div class='quotemain'><!--quotec-->Recommendation Python for easy coding (and less pain with variable conversion) or get in the grime with C++ (you will learn all that is good and bad about languages or perish. mmm strongly-typed languages)<!--QuoteEnd--></div><!--QuoteEEnd-->
    In Lua everything is a table, a number, or a string. There isn't really any variable conversion going on. Numbers can be operated on like ints or floats (because they are doubles). It's a different way of thinking for programmers who are used to having discrete numerical types, but I feel like for the newbie, this is far more accessible. Same thing with tables... There is no array/dictionary/objects/structs/etc. There are just tables. Tables encompass all of the above. Even global variables and functions are in a table... again, maybe this is all because I'm seeing it through the eyes of an experienced programmer... But to me so many of the complexities that exist in other languages are just completely gone in Lua. It's like how structured Japanese is compared to English/Spanish/French/etc.


    I would definitely recommend learning Lua to anyone who was getting started. For the next ludum dare / game jam, I'm planning on using <a href="https://love2d.org/" target="_blank">https://love2d.org/</a> which is a lua-based 2d game prototyping framework. I haven't used it much, but I've been growing quite fond of Lua and from the small amount I've done with LOVE, I can say it seems pretty quick to get going.
  • SwiftspearSwiftspear Custim tital Join Date: 2003-10-29 Member: 22097Members
    edited October 2012
    I make no claims that lua is bad or anything. I like the language in general. If you already know programming it's a very easy language to work with. It's just Lua is a little bit spotty. There are a handful of things in lua that are similar to what bones ran into here. It hides details of some underlying system in most cases, but then in one weird case the details just aren't hidden any more for no apparent reason.

    I suspect bones situation is one of the places where it's the most jarring. But to properly understand all the options for dealing with this problem you have to understand that mathematical functions automatically type cast, but throw an error that needs to be caught if fed an invalid number, but also that the equality operator does not automatically type cast, so if you want to use it you have to use a built in engine function, which does not use error handling to report an invalid type, but rather it either returns a number or a null value (which brings in the potential need to understand null logic).

    If you know all those things already, meh, no worries, just choose something that allows you to address what you're working on as quickly as possible from a coder's perspective... it's just unusual to have one construct that is pretty much fundamental to the language has SO many high level programming concepts latched onto it haphazardly. You wouldn't see something like that in Python or Java. They just tend to be more consistent. Although granted, at least for the case of Java, in it's consistency it also results in more code being required to do the same thing.

    Lua is SUCH a nice language for injecting into other scripting systems and what not. It's effectively a scripting language with high level programming features, which makes it extremely nice in so many situations. There are so many game engines that use lua injection as their modding interface for exactly that reason (NS2 included as I understand it). It's using a really nice software licence that allows pretty much anyone to use it in pretty much whatever creative way they can imagine. However, on some level it just doesn't ever really escape it's roots as a patchwork but powerful script language written by white hats to be used for what is effectively hacking. It's easy to use when you know it's eccentricies, and it's very powerful compared to many of it's peers, but it doesn't have the same sense of polish in design as most of the other high level programming languages people traditionally learn in.

    I guess that's sort of the up side of learning Lua for new programmers, it gives you avenues to be useful in cool projects pretty much right away. If that motivates you more, then I'd recommend just sticking with learning Lua. I wouldn't claim it's an exceptionally hard language to learn, because it's a reasonably easy language to work with, by nature it's going to be reasonable for learning, but you'll be caught by the occasional barb caused by weird design choices made by the language developers. However, if you want a more structured learning experience where you will encounter higher level concepts more gradually and find things less jumbled together I don't think Lua is the best language to start off with learning.
  • remiremi remedy [blu.knight] Join Date: 2003-11-18 Member: 23112Members, Super Administrators, Forum Admins, NS2 Developer, NS2 Playtester
    <!--quoteo(post=1986896:date=Oct 4 2012, 04:17 AM:name=Swiftspear)--><div class='quotetop'>QUOTE (Swiftspear @ Oct 4 2012, 04:17 AM) <a href="index.php?act=findpost&pid=1986896"><{POST_SNAPBACK}></a></div><div class='quotemain'><!--quotec-->. However, if you want a more structured learning experience where you will encounter higher level concepts more gradually and find things less jumbled together I don't think Lua is the best language to start off with learning.<!--QuoteEnd--></div><!--QuoteEEnd-->
    Good points. I think this last one is actually why I like Lua so much. I was able to grasp the whole of it quite quickly (I just read one book and feel I know the whole of it) and am able to hold the entire mental model in my head. Other languages I've used I've had to keep learning aspects of weeks in to using it (just because I hadn't had need to know those parts yet). I could definitely understand why that wouldn't be as good for someone who is just learning to program.
Sign In or Register to comment.