[Learning LUA] Lesson 3: Values and Operators is up!

Talk about creating Grimrock 1 levels and mods here. Warning: forum contains spoilers!
User avatar
SpiderFighter
Posts: 789
Joined: Thu Apr 12, 2012 4:15 pm

[Learning LUA] Lesson 3: Values and Operators is up!

Post by SpiderFighter » Fri Mar 29, 2013 12:03 pm

I'm tired of having to cobble together pieces of code, or use a gazillion jillion trazillion plates, counters, timers, and blockers to get everything to work the way I want it to. Moreover, I'm done with misunderstanding what I'm doing and thinking I'm coding something I'm actually not. So, let's learn lua! I have my copies of "Beginning Lua Programming" and "Learn Lua for iOS Game Development" loaded on my e-readers and ready to go. I have the Lua 5.2 Reference Manual, LUA: really for Beginners, lua-users Lua Tutorial, and Lua for Dummies:Variables loaded in my browser. I have the libraries and executables compiled and ready to go. A few things before I get started:

1. If anyone else wants to join me, please do! Let's make this a thread where we can feel free to ask anything we want without fear of feeling embarrassed, and support each other as we go.

2. If any Lua Code Warriors want to check in on us from time to time, we would greatly appreciate it. Any advice you'd like to give before we start is also most appreciated.

3. I'm going to feel really stupid if I'm the only newbie here. :D But I'm doing it anyway.

4. If you would like to add some tips/tricks/lessons of your own, please ensure they are your own words. No copying and pasting.

Lesson Color Key:
This color illustrates examples you can use in lua scripts.
This color illustrates examples you shouldn't (or can't) use in lua scripts.

The Lessons:
Day One - The Basics
Day One - Types of Variables
Day Two - Values, Operators, and Assignments

Additions / Corrections / Useful Information (found in this thread):
How to properly use "and" by msyblade
More on Logical Operators from Ryeath_Greystalk
More on Relational Operators from John_Wordsworth
More about Variables from Alcator
About Binary Numbers in Lua by Xanathar (reposted by Ryeath_Greystalk)
More about "nil" and how logical operators compare to C# by Xanathar
General Programming Principals by Diarmuid
Last edited by SpiderFighter on Mon Apr 08, 2013 2:50 pm, edited 14 times in total.

User avatar
Neikun
Posts: 2457
Joined: Thu Sep 13, 2012 1:06 pm
Location: New Brunswick, Canada
Contact:

Re: [LUA NEWBIES] Let's do this!!

Post by Neikun » Fri Mar 29, 2013 12:21 pm

Great idea!
Maybe if my life chills out in the near future I'll join you.
"I'm okay with being referred to as a goddess."
Community Model Request Thread
See what I'm working on right now: Neikun's Workshop
Lead Coordinator for Legends of the Northern Realms Project
  • Message me to join in!

User avatar
petri
Posts: 1898
Joined: Thu Mar 01, 2012 4:58 pm
Location: Finland

Re: [LUA NEWBIES] Let's do this!!

Post by petri » Fri Mar 29, 2013 12:22 pm

Sounds great! I suggest you also read Programming in Lua by Roberto Ierusalimsky et al, the creators of Lua. It is The Book about Lua. It's easily one of the best written programming books I've read and covers everything about the Lua language.

User avatar
SpiderFighter
Posts: 789
Joined: Thu Apr 12, 2012 4:15 pm

Re: [LUA NEWBIES] Let's do this!!

Post by SpiderFighter » Fri Mar 29, 2013 12:39 pm

petri wrote:Sounds great! I suggest you also read Programming in Lua by Roberto Ierusalimsky et al, the creators of Lua. It is The Book about Lua. It's easily one of the best written programming books I've read and covers everything about the Lua language.
Thanks, Petri! I saw that the third edition was just published in January, but it's paper-only at this point. I didn't realize it was written by the authors of the language, so I was going to wait, but I'll order a copy today.

@Neikun: Please do! It's difficult to find truly beginning information on lua in one place, so it's my hope that this will become a useful thread to others after we've moved on.

User avatar
Krazzikk
Posts: 37
Joined: Sat Mar 16, 2013 11:30 pm

Re: [LUA NEWBIES] Let's do this!!

Post by Krazzikk » Fri Mar 29, 2013 2:26 pm

Well so far I've just been learning as I go, but I might check it out ;D

User avatar
SpiderFighter
Posts: 789
Joined: Thu Apr 12, 2012 4:15 pm

Day One - The Basics

Post by SpiderFighter » Fri Mar 29, 2013 4:39 pm

Day One - The Basics

Things I've learned or reviewed today (if I make any mistakes, please correct me so I'm not misleading anyone else. I'm collating information from many different sources, some of which undoubtedly refer to older versions of lua):
  • 1. Line breaks don't matter. - Lua reads the following all the same way:

    Code: Select all

    x = "you're ugly!"
    print(x)
    
    x = "you're ugly!" print(x)
    
    x = "you're ugly!";
    print(x);
    
    x = "you're ugly!"; print(x)
    2. local variable vs global variables:
    a. All variables are global uness prefixed by local
    b. Local variables can only be called from within the same script, while global variables can be called from other scripts (more global variables means more work while it's running, so it's best to use local variables if possible).
    c. Variables can be of any value, whether numerical, a function, a word, a table, et al.

    Code: Select all

    z = 215
    monster = green_slime 
    awesome = "Almost Human"
    d. We'll cover the different types (or values) of variables later, but for now just know that variables can be any combination of numbers, letters and underscores, with the following exceptions: a digit as the first character, an underscore followed by a number (such as _2) or uppercase letters (such as _THIS). The general rule of thumb seems to be to not use an underscore as the first character in your variable except in certain circumstances. It should be noted that in LoG, connectors have difficulty with function names that contain underscores (such as: function true_or_false), and it is best to leave them out altogether.

    3. Lua is case-sensitive. The word Goromorg is not the same as goromorg. Words reserved for use within lua can be used as variables simply by changing the case (Then instead of then, for example).

    4. Words reserved for use in lua are:
    SpoilerShow
    and break do else elseif end false for function if in local nil not or repeat return then true until while
    You can not use any of those words as variables (unless you change the case, as mentioned in point #3).

    5. Comments: Comments can be added, or lines commented out, by using a double hyphen (--like this, or as in the following example script.)

    Code: Select all

    local message = spawn("scroll")
    message:setScrollText("(This is my message.)")   --The game won't see these words after the double hyphen
    green_slime_9:addItem(message)
    --hudPrint("Ta-DA!")
    In the above example, the game ignores the final line (hudPrint("Ta-DA!")) because it has been commented out. You can also comment out an entire block of code by using --[[ and --]]. Let's use the above example, but this time I want to comment out the whole thing except the last line (the added function and end lines are to make it playable in-game):

    Code: Select all

    --[[
    local message = spawn("scroll")
    message:setScrollText("(This is my message.)")   
    green_slime_9:addItem(message)
    --]]
    function tada()
    hudPrint("Ta-DA!")
    end
Last edited by SpiderFighter on Wed Apr 03, 2013 12:13 pm, edited 5 times in total.

Ryeath_Greystalk
Posts: 366
Joined: Tue Jan 15, 2013 3:26 am
Location: Oregon

Re: [LUA NEWBIES] Let's do this!!

Post by Ryeath_Greystalk » Fri Mar 29, 2013 4:48 pm

This could end up being just what I've been needing. With no real programming experience I've been gleaning little bits of information from all the various resources listed by SpiderFighter as well as all the posts here on the forums. I'll contribute what little I know.

User avatar
SpiderFighter
Posts: 789
Joined: Thu Apr 12, 2012 4:15 pm

Re: [LUA NEWBIES] Let's do this!!

Post by SpiderFighter » Fri Mar 29, 2013 4:58 pm

Ryeath_Greystalk wrote:This could end up being just what I've been needing. With no real programming experience I've been gleaning little bits of information from all the various resources listed by SpiderFighter as well as all the posts here on the forums. I'll contribute what little I know.
Please do! I've been learning it the same way as you, and I realized yesterday while talking with someone much more knowedgable than me about a lua script (sorry for putting you through that, Diarmuid), that doing it that way has left some pretty large gaps in my knowledge. Collating and re-writing everything like this helps me learn, so I figured maybe it would help others if I posted it here. I hope so. I'll keep updating the OP with new lessons as we go.

Thanks for the vote of encouragement, Ryeath; it means a lot.

Ryeath_Greystalk
Posts: 366
Joined: Tue Jan 15, 2013 3:26 am
Location: Oregon

Re: [LUA NEWBIES] Let's do this!!

Post by Ryeath_Greystalk » Fri Mar 29, 2013 7:24 pm

*raises hand*

I already have two questions on your lesson.

1. x = "you're ugly!";
print(x);

x = "you're ugly!"; print(x)

Does the semi colon serve a purpose here? I don't recall having used a semi colon in my travels yet.

2. If a variable is generated inside a function without the local preface is it still a global.

example:
script_a

x = 42 -- global
local y = 18 -- local to script_a

function meaningOfLife()
local z = 21 -- local to script_a.meaningOfLife()
a = 969 -- is this global or local to script_a.meaningOfLife()?
print x -- prints 42 (global)
print y -- prints 18 (local to script_a)
print z -- prints 21 (local to script_a.meaningOfLife())
print a -- prints 969 (???? global or local)
end

print x -- prints 42 (global)
print y -- prints 18 (local to script_a)
print z -- prints nil (z is local to function meaninOfLife())
print a --???? (if a is a global it would print 969. if local to function it would print nil)

script_b

print x -- prints 42 (global)
print y -- prints nil (local to script_a)
print z -- prints nil (local to script_a.meaningOfLife())
print a -- ???? (if a is a global it would print 969. if local to function it would print nil)


Thanks in advance.

edited -- apparently font color does not work inside code tags.

User avatar
SpiderFighter
Posts: 789
Joined: Thu Apr 12, 2012 4:15 pm

Day One - Types of Variables

Post by SpiderFighter » Fri Mar 29, 2013 7:30 pm

Day One - Types of Variables

(As always, if I make any mistakes, please correct me so I'm not misleading anyone else. I'm collating information from many different sources, some of which undoubtedly refer to older versions of lua):

Overview. - Lua recognizes eight different types of variables (also called identifiers), and they are all first-class (meaning their values can be manipulated and passed to, and returned from, functions). In alphabetical order, they are:
  • 1. Boolean - As is the norm elsewhere, boolean values are either true or false. However, in lua, there are only two inherently false conditionals: They are false and nil (see more on nil below). If a conditional is neither false nor nil, it must be true. This includes empty strings and zero.

    Connect the following script to a pressure plate:

    Code: Select all

    function trueorfalse()
    awesome = 1
    if (awesome) then hudPrint("You're awesome!")
    end
    end
    That will return "You're awesome!" to the screen, while replacing line 2 (awesome = 1) with

    Code: Select all

    awesome = nil
    or

    Code: Select all

    awesome = false
    will return nothing.

    The reserved operator not placed before true or false can be used to invert the meaning. For example

    Code: Select all

    print (not true)

    is the same as

    Code: Select all

    print (false)
    In the actual game (LoG), both of those examples will work within a script. However,

    Code: Select all

    hudPrint(false)
    will not (hudPrint("false") would work, but is obviously not the same thing).

    2. Function - Functions begin with function() and end with end. In between is the task that needs to be performed. They can be nested (as in a function within a function) or non-nested.

    Code: Select all

    function thisiseasy() print("yes it is!"); end -- declares the function
    thisiseasy() -- calls the function
    print(thisiseasy) -- finds the assigned value of the variable "thisiseasy" and prints it to the screen


    3. Nil - This is similar to null, in that it is not a value, but the absence of one. All global values are nil by default (until they are assigned a value by using = ). Nil is also useful for deleting the value of a variable within a script.

    4. Numbers - Lua deals with real, double precision, floating point decimal numbers. As long as the number is less than 10^14, there are no rounding errors. Simple math functions can be used:

    Code: Select all

    print(2+2)
    print(4-4)
    print(8*8)
    print(16/8)
    
    Lua also has its own advanced math library (more information can be found here). There are many scripts floating around these forums that make use of the more advanced math operators.

    5. Strings - I'll get more in-depth on strings another day, but a simple explanation is that a string is a sequence of characters to which we can assign variables. Strings can be joined by using ".." (without the quotes). Place the following inside a script in your LoG map and conect it to a pressure_plate:

    Code: Select all

    function partytalk1()	
    	local name1 = party:getChampion(1):getName()
    	local name2 = party:getChampion(2):getName()
    	        hudPrint(""..name1..": You're looking pretty good in those sandals, "..name2..". Too bad you haven't found any pants yet.")
    end
    If you use the ready-made party, when you step on the plate, you should see "Contar Stoneskull: You're looking pretty good in those sandals, Mork. Too bad you haven't found any pants yet."

    6. Tables - These require an in-depth tutorial but, for now, just be aware that they are used to store collections of variables, including lists, strings, arrays and, yes, even other tables.

    7. Thread - A special variable that specifies an independent thread of execution. No, I don't understand it yet either, but we'll get there in time. :)

    8. Userdata - Separated into Light Userdata and Heavy Userdata, it is a memory block allocated by C, that allows C functions to access and store data via lua variables. The only way to create or modify userdata is through the C application interface.
Whew! That's enough for today!
Last edited by SpiderFighter on Wed Apr 03, 2013 1:07 pm, edited 2 times in total.

Post Reply