TOOLBOX
Oh, Guest
Register Login
Servers

Sammy Servers Public Servers

It is currently Sat Dec 16, 2017 10:20 pm




 Page 1 of 2 [ 24 posts ] 

Go to page 1, 2  Next

Author Message
Norway Dellkan
PostPosted: Tue Aug 02, 2011 12:57 pm 
Dellkan
level4.png
User avatar
Featured Articles: 1 1000 posts +
Show user details
Male Plays Gmod Plays Minecraft
Unknown Unknown
Posts: 1116
16 people like this: c00terCobra HJRColdFrontierFrostIrish Aaron xDJelly Bellymod7788Tofty1996Uberdude9001Ultra Lulz and 6 more users
Image

Featured by Wooden Trout




So, you want to learn lua, huh?
The guide on getting started.
Totally not C++ in the image




Introduction
Learning lua, scripting, coding, programming, or whatever you prefer to call it won't happen as easily as reading this guide. Sorry
While I hope to give you a head start, you can really only learn by playing with the language and engine, in your own good time.

I will give you a few tips though:
  • Get an idea. Learning a language is so much easier when you are trying to make some specific.
  • Don't give up. Just because things aren't working right off the bat, doesn't mean you can't fix it. Spend time with it. Spend time planning and thinking how you want to set up the logic.
  • Learn by reading - Chances are someone have created something similar to what you are doing. Find those, then see how they have done it. Try to understand the logic of what a script is doing, even if you don't understand all the specific functions.

The language is combining a vast amount of different concepts, which, no doubt, will be hard to grasp for a beginner. My best tip here is to ignore it, and focus on the logic. You'll pick up the rest in your own good time.




Resources
Well, lets get started. Here is the requirement list:
Quote:
Requirements

And some other resources
Quote:
http://wiki.garrysmod.com <-- bible of everything gLua. Everything related to anything in garrysmod. Also contains tutorials, and many other resources.
http://www.lua.org/docs.html <--- lua documentation. While useful, its very hard to read for beginners.

And some useful folder locations
Quote:
steam\steamapps\<username>\garrysmod\garrysmod\lua\ You can put single script files in here, and open them directly ingame, no further configuration required. Try it! Run the command lua_openscript <filename>.lua in console in singleplayer.
steam\steamapps\<username>\garrysmod\garrysmod\addons\ This is where you put your addons, even your own if you create one
steam\steamapps\<username>\garrysmod\garrysmod\gamemodes\ This is where I work for the most part. It'll likely be empty for you. You can download gamemodes such as fretta or darkrp and put them in here, to create your own server with that gamemode on.





What is gLua?
gLua is garrysmod adaption of the open source lua language.
Lua is a language best described as a plugin language, often used for addons and plugins, from everything between garrysmod to WoW to even vlc.
One way to think of it is that lua is a simplified language which allows you to run functions on a more complex, underlying engine.

For us, that means that doing stuff in lua is sent to the source engine, which puts it together.

It also means that whatever limitations the source engine has, we also have.

As noted, we call garrysmod adaption of the lua language for gLua. The adaption involves a few differences from the official language, listed here.
Here's a short overview:
Quote:
Name Lua Standard C-Style
Multi-Line Comments --[[ comment ]] /* comment */
Single Line Comments -- comment // comment
And and &&
Or or ||
Not not !
Not-Equal ~= !=


Garry has made it simple for us, allowing either one to be used according to what you prefer.
Don't worry if nothing of this makes sense to you yet.




Concepts
Before ranting on about concepts, I guess its a good idea to give a little dictionary about some of the common expressions used.
Quote:
  • Variable - The bread and butter of any programming language, it functions like a container, or holder, and can be assigned to hold anything. It can be called anything. Its wise to call it something that'll make you understand what it is used for.
  • Datatypes - A variable can only hold one specific datatype at a time. String, number, vector(location), color, functions, and so forth are datatypes.
  • String - Simple text. Encased by quotes, like this "text". You've probably already noticed that you have to do the same for some console commands?
  • Table - Also called arrays. This is a datatype that holds other variables.
  • function - A piece of reusable code that will perform the same action every time it is called.
  • SWEP - Short for Scripted Weapon. Keys, flamethrower, pigeon pill, haax, ak47, gravgun are all examples of SWEP's.
  • SENT - Short for Scripted Entity. Keypad, weapon shipment, dynamic doors, zones, dropped money are all examples of SENT's.
  • Entity - In source engine, and in many other contexts, objects are referred to as entities. A player is an entity. The weapon a player is holding is an entity. Dropped money is an entity. All SWEP's and SENT's are entities.
  • Shared, serverside, clientside, cl_init, init, etc - Garrysmod revolves around two worlds. What happens on the server, and what happens on the client (on your computer as you play). The expressions mentioned here is essential as to describe where something is happening. More about this in next article.

Now, lets see some of these in action, shall we? (expand it)
LUA: [ Download ] [ Hide ]
MyString = "Hello world" -- Notice how it supports spaces? That is not the cases for variable names (string, left of the equal sign)
MyNumber = 15 -- No quotes necessary here. The program understands a number
MyTable = { "Hello world", 15 } -- Notice how we were able to place both of the above variables into a single variable here. Such is the power of tables.
function myFunction()
   print(MyString, MyNumber, MyTable) -- each time we call myFunction(), it will print the string, number, and table into the ingame console.
end
myFunction() -- and this is how we call the function.
 
Parsed in 0.002 seconds, using GeSHi 1.0.8.4

This is actual, working code. Run that ingame, and it will output "Hello world" 15 table: [Some random number].




Dissecting our first script
The best way to learn lua (or any language) is to look at existing code. There is no way to avoid it. You will be slapped with both functions and concepts you won't understand. Instead, take the code for granted, and instead focus on understanding the logic.

The logic is the main barrier in any script. Knowledge is easy. Figuring out how to make it work is the hard part.

We'll begin by looking at part of the money printer logic used on the live server at the moment.

LUA: [ Download ] [ Hide ]
local PrintMore
function ENT:Initialize() -- this is a function that is called when the printer is created
        self:SetModel("models/props_c17/consolebox01a.mdl") -- here we set the model. This is a model you can find in Q menu ingame
        self:PhysicsInit(SOLID_VPHYSICS) -- We want the money printer to be affected by physics, such as gravity. This is automatically taken care of by the engine when we type this
        self:SetMoveType(MOVETYPE_VPHYSICS) -- This defines how the money printer reacts to movement.
        self:SetSolid(SOLID_VPHYSICS) -- Here we set whether or not the printer is solid or not.
        local phys = self:GetPhysicsObject() -- PhysicsInit above gave the printer a physic object, which we retrieve here
        if phys:IsValid() then phys:Wake() end -- We check that everything went according to plan, then we wake the physic object up (it'll fly midair unless we do this)
        self.sparking = false -- This is a variable we'll be using later
        self.damage = 100 -- this is the health of the printer
        self.IsMoneyPrinter = true
        timer.Simple(27, PrintMore, self) -- we start the first print cycle. Notice that its set to 27 seconds.
end

function ENT:OnTakeDamage(dmg) -- this function is called when the printer takes damage.
        if self.burningup then return end -- If the printer is already burning, we "return", meaning we interrupt the script, thus disallowing damage to the printer

        self.damage = (self.damage or 100) - dmg:GetDamage() -- Here we use the variable .damage that was set in Initialize, then apply the received damage
        if self.damage <= 0 then -- if the health of our printer is equal to or less than 0...
                local rnd = math.random(1, 10) -- pick a random number between 1 and 10, and store it in the "rnd" variable
                if rnd < 3 then -- if the random number we picked is less than 3 then we...
                        self:BurstIntoFlames() -- put it on fire!
                else -- but if the number was 3 or higher then we..
                        self:Destruct() -- explode it
                        self:Remove() -- and remove it!
                end
        end
end

function ENT:Destruct() -- this is a custom function that is called when we want to blow the printer up
        -- We'll create a custom effect of an explosion. The next few lines can be hard to grasp. Skip for now
        local vPoint = self:GetPos() -- First, we get the position of our printer, and store that in vPoint for later use
        local effectdata = EffectData() -- Then we create the effect...
        effectdata:SetStart(vPoint) -- set its position using vPoint
        effectdata:SetOrigin(vPoint) -- this is also setting its position
        effectdata:SetScale(1) -- this is how big the explosion will appear)
        util.Effect("Explosion", effectdata) -- We've finished defining our explosion, time to put it into action. util.Effect(effect-type, settings)
        Notify(self.dt.owning_ent, 1, 4, "Your money printer has exploded!") -- we give the player a heads up, that his printer has blown up
end

function ENT:BurstIntoFlames() -- this is a custom function that is called when we want to put the printer on fire
        Notify(self.dt.owning_ent, 1, 4, "Your money printer is overheating!") -- we start off by giving the player a heads up that his printer is on fire!
        self.burningup = true -- We prevent the printer from taking more damage, so it can burn in peace (see ENT:OnTakeDamage())
        local burntime = math.random(8, 18) -- we pick a random number between 8 and 18, which will be how long it will burn
        self:Ignite(burntime, 0) -- we put the printer on fire..
        timer.Simple(burntime, self.Fireball, self) -- .. and after that duration we call the ENT:Fireball() function, which will blow the printer up.
end

function ENT:Fireball() -- This is a custom function that is called after the printer has been burning for a while
        if not self:IsOnFire() then return end -- if the printer isn't on fire, this must have been called by a mistake. Abort abort!
        local dist = math.random(20, 280) -- Explosion radius
        self:Destruct() -- We call the ENT:Destruct() function to create the explosion effect
        for k, v in pairs(ents.FindInSphere(self:GetPos(), dist)) do -- We search the surrounding vicinity of the printer, and for each item we find we..
                if not v:IsPlayer() and not v.IsMoneyPrinter then v:Ignite(math.random(5, 22), 0) end -- check that the item is not a player or another printer, then we put it on fire for a random duration between 5 and 22 seconds.
        end
        self:Remove() -- All done! We've blown the printer to hell, and put random shit nearby on fire. Now we can remove the printer.
end

PrintMore = function(ent) -- this is an alternative version of creating a function. Don't be alarmed, it works exactly the same.
        if ValidEntity(ent) then -- if the printer still exists..
                ent.sparking = true -- we make the printer spark, like it does when its about to print money
                timer.Simple(3, ent.CreateMoneybag, ent) -- after 3 seconds it will attempt to create money. Notice: 27 seconds first time + 3 seconds - 30 seconds from spawn. Always.
        end
end

function ENT:CreateMoneybag() -- This is a custom function that we call when we want the printer to attempt printing money
        if not ValidEntity(self) then return end -- printer no longer exist! Abort abort!
        if self:IsOnFire() then return end -- Printer is burning! Abort abort!
        local MoneyPos = self:GetPos() -- All is well, we proceed to figure out where the money should be spawned. We use the location of the printer.

        if math.random(1, 22) == 3 then self:BurstIntoFlames() end -- We make a random number between 1, and 22. And if that number is 3 exactly, we put the printer on fire! >:3
       
        local amount = GetConVarNumber("mprintamount") -- We check the server CVAR for how much money we should print
        if amount == 0 then -- is server is borked, and we didn't find the cvar, we default to 250
                amount = 250
        end

        DarkRPCreateMoneyBag(Vector(MoneyPos.x + 15, MoneyPos.y, MoneyPos.z + 15), amount) -- We actually create the money.
        self.sparking = false -- we are done creating money. No need to spark anymore.
        timer.Simple(math.random(100, 350), PrintMore, self) -- We start the next print cycle, between 100-350 seconds from now.
end

function ENT:Think() -- This is an engine function, which is called every "frame" or FPS that the server is alive on (i.e extremely often)
        if not self.sparking then return end -- if we aren't busy printing money, we have no further business here. We stop the script.

        -- the following is creating the spark effect the printer makes when its about to print money. As defined in PrintMore, it'll continue to do so for 3 whole seconds.
        local effectdata = EffectData()
        effectdata:SetOrigin(self:GetPos())
        effectdata:SetMagnitude(1)
        effectdata:SetScale(1)
        effectdata:SetRadius(2)
        util.Effect("Sparks", effectdata)
end
 
Parsed in 0.008 seconds, using GeSHi 1.0.8.4

Copy this script into your notepad++, then go to languages, and put on GMOD LUA to make it highlight everything. Green text is my comments, which I hope will help you understand how it works.

So, what are the main parts to take with you from this example?
To make a money printer, we have to figure out the following parts:
  • What happens when the printer is spawned? Is it automatically bound by gravity and physics?
  • How do we make it start printing money, and how do we make this continue to happen as long as the printer is alive?
  • What happens when the printer takes damage?
  • How do we determine how much money the printer should print?
  • How can we make it appear like the printer is randomly overheating?
  • How can we randomize all of the events above?




Other useful tips
  • Be realistic. Don't try to make a gamemode on your first day of writing lua. Start with something easy. Like changing the ammo type of an existing weapon.
  • Lua is always accessable ingame. If you are hosting a server from your computer, you can do lua_run <lua code> from your console! lua_run_cl is available on most multiplayer servers (excluding ours) allowing you to run clientside scripts.
  • Learn how to navigate http://wiki.garrysmod.com. It can instantly tell you how anything work, if you know how to use the site.
  • Create yourself an environment you can experiment in! By using the "Start new game" from main menu, garrysmod, followed by "Start multiplayer", you've got yourself a fully functional, free, all-included multiplayer server. Download an admin mod addon to change map and such. (This is how I test everything that I create for SS.)
  • When you are experimenting with code:
    • lua_openscript to mess with simple one-file scripts (requires no restart)
    • Map restart when you are editing existing scripts
    • If you add or remove files (such as addons, or gamemode files) garrysmod must be restarted, unfortunately.




Next article...
Will obviously be slightly more advanced. We will also create a weapon from scratch. Feel free to suggest contents for a custom weapon in a reply.


Last edited by Wooden Trout on Wed Aug 03, 2011 4:15 am, edited 8 times in total.

Offline
 Profile Chat  
O.P  
Norway Dellkan
PostPosted: Tue Aug 02, 2011 1:00 pm 
Dellkan
level4.png
User avatar
Featured Articles: 1 1000 posts +
Show user details
Male Plays Gmod Plays Minecraft
Unknown Unknown
Posts: 1116
[ - reserved - ]


Offline
 Profile Chat  
O.P  
United Kingdom Cherry
PostPosted: Tue Aug 02, 2011 1:11 pm 
Cherry
owner.png
User avatar
2000 posts +
Show user details
Cherry Plays Gmod Plays Minecraft
Unknown Unknown
Posts: 3275
1 person liked this: Ultra Lulz
Nice article Dellkan.

I'm sure this'll help out some new people to gLua. :)


Offline
 Profile Chat  
United States Lord Trollsidon
PostPosted: Tue Aug 02, 2011 3:10 pm 
Member
respected.png
User avatar
666 posts +
Show user details
Male Plays Gmod Plays Minecraft
Unknown Unknown
Posts: 684
:thumbup:
Great article



________________
Image
Offline
 Profile Chat  
 
United States Ultra Lulz
PostPosted: Tue Aug 02, 2011 5:24 pm 
Ultra Lulz
level4.png
User avatar
Featured Articles: 2 2000 posts +
Show user details
Female Plays Gmod Plays Minecraft
Unknown Unknown
Posts: 2842

CURRENTLY SERVER BANNED
Cherry wrote:
Nice article Dellkan.

I'm sure this'll help out some new people to gLua. :)


And I was just talking you last night about how I need to learn this stuff xD



________________
Tick tock goes the clock,
And what now shall we play?
Tick tock goes the clock,
Now summer's gone away
Offline
 Profile Chat  
 
United States Slendy
PostPosted: Tue Aug 02, 2011 5:31 pm 
Titan
level4.png
User avatar
500 posts +
Show user details
Female Plays Gmod Plays Minecraft
Unknown Unknown
Posts: 635
1 person liked this: Ultra Lulz
Ultra Lulz wrote:
Cherry wrote:
Nice article Dellkan.

I'm sure this'll help out some new people to gLua. :)


And I was just talking you last night about how I need to learn this stuff xD


You and me both :p we should learn together xD



________________
Has managed: SS Minecraft, SS Terraria, SS TF2

⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗
Image
⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗⊗
Offline
 Profile Chat  
 
United Kingdom Pegaz
PostPosted: Tue Aug 02, 2011 11:32 pm 
Abuse Manager
level4.png
User avatar
Featured Articles: 1 1000 posts +
Show user details
Male Plays Gmod Plays Minecraft
Unknown Unknown
Posts: 1422
I copied the lua for the money printer, i grasped it all after 20mins or so understanding what the actual codes am and what they do.

I can really get into this, thx dellkan.



________________
Image

I have a disease called ADW, it's an disease that makes the patient "(A) Able to (D) Do only what he (W) Wants to do."

"Nothing is True, Everything is permitted."
Offline
 Profile Chat  
 
United States Hat
PostPosted: Tue Aug 02, 2011 11:35 pm 
Moderator
level4.png
User avatar
1000 posts +
Show user details
Male Plays Gmod Plays Minecraft
Unknown Unknown
Posts: 1027

CURRENTLY SERVER BANNED
Thanks Dellkan. I've been trying to learn "gLua" for a while.



________________
"all girls have a penis...i have one" -TITAN
Offline
 Profile Chat  
 
United States Battlefield1113
PostPosted: Tue Aug 02, 2011 11:44 pm 
Battlefield
level4.png
User avatar
Global Moderator Abuse Manager Featured Articles: 1 2000 posts +
Show user details
Male Plays Gmod Plays Minecraft
Unknown Unknown
Posts: 2008
Damn it Dellkan now that you've posted a guide I have no more excuses to not learn it. :c



________________
Hat in a Cat: MY HEART IS METAPHORICALLY BLEEDING
battlefield1113: CALL A METOPHORICAL DOCTOR
battlefield1113: QUICK
Hat in a Cat: I DONT KNOW THE METAPHORICAL NUMBER
Image
Offline
 Profile Chat  
 
United Kingdom Pegaz
PostPosted: Wed Aug 03, 2011 12:05 am 
Abuse Manager
level4.png
User avatar
Featured Articles: 1 1000 posts +
Show user details
Male Plays Gmod Plays Minecraft
Unknown Unknown
Posts: 1422
been working on my own little quest, tell me if i made a mistake cuz i cant find 1 at all, think i done it right, created it from scratch.

Spoiler: Toggle


Last edited by Pegaz on Wed Aug 03, 2011 12:25 am, edited 2 times in total.


________________
Image

I have a disease called ADW, it's an disease that makes the patient "(A) Able to (D) Do only what he (W) Wants to do."

"Nothing is True, Everything is permitted."
Offline
 Profile Chat  
 
United States Erickarkos
PostPosted: Wed Aug 03, 2011 12:06 am 
Member
respected.png
User avatar
Show user details
Male Plays Gmod Plays Minecraft
Unknown Unknown
Posts: 71
08/02/11 17:11:05 Dellkan (STEAM_0:1:4542409): // You guys should totally go read my article. Learn lua. Take some of the work off my plate.

There's more to the tutorial :o



________________
Vladimir Lenin wrote:
Там может быть революции без террора
Offline
 Profile Chat  
 
United Kingdom Cherry
PostPosted: Wed Aug 03, 2011 12:11 am 
Cherry
owner.png
User avatar
2000 posts +
Show user details
Cherry Plays Gmod Plays Minecraft
Unknown Unknown
Posts: 3275
Should work Pegaz, but, kinda pointless. ;)

Also probably a good idea to make that variable local, since you won't be using it outside that script. ;)

Also, if you're going to be posting code, specifically Lua, use [ lua] [/ lua] tags.


Offline
 Profile Chat  
United Kingdom Pegaz
PostPosted: Wed Aug 03, 2011 5:46 am 
Abuse Manager
level4.png
User avatar
Featured Articles: 1 1000 posts +
Show user details
Male Plays Gmod Plays Minecraft
Unknown Unknown
Posts: 1422
After a nite studying that tutorial, i can read codes, i understand it, i can edit codes etc.

Even edited my own little Pegaz's Pistol and it worked xD

But cant create codes from scratch yet and to get to the point where i can help Dellkan coding will take months lol.


Last edited by Pegaz on Wed Aug 03, 2011 5:47 am, edited 1 time in total.


________________
Image

I have a disease called ADW, it's an disease that makes the patient "(A) Able to (D) Do only what he (W) Wants to do."

"Nothing is True, Everything is permitted."
Offline
 Profile Chat  
 
United States Gunz
PostPosted: Wed Aug 03, 2011 6:51 am 
Banned
guest.png
User avatar
Featured Articles: 1 1000 posts +
Show user details
Male Plays Gmod Plays Minecraft
Unknown Unknown
Posts: 1635
Hooray.

More people to do small bits of code.

:D



________________
Tired of your shit
Offline
 Profile Chat  
 
United Kingdom Cobra HJR
PostPosted: Wed Aug 03, 2011 7:47 am 
Moderator
respected.png
User avatar
Featured Articles: 1 1000 posts +
Show user details
Male Plays Gmod Plays Minecraft
Unknown Unknown
Posts: 1116
I want to learn this so much, but I know I will fail. Well, it's worth a shot anyway! Great article Dellkan :D



________________
There are no shorts in here, son.
Offline
 Profile Chat  
 
United States Frost
PostPosted: Wed Aug 03, 2011 1:03 pm 
Frost
level4.png
User avatar
Administrator Global Moderator 1000 posts +
Show user details
Male Plays Gmod Plays Minecraft
Unknown Unknown
Posts: 1915
Very nice article Dellkan!



________________
Baacconnnnn n stuffz
Offline
 Profile Chat  
 
United States Helios Arcos
PostPosted: Wed Aug 03, 2011 10:31 pm 
Member
respected.png
User avatar
250 posts +
Show user details
Male Plays Gmod Plays Minecraft
Unknown Unknown
Posts: 398
I love this Dellkan, Want to learn, but won't be doing to much for next 2 days on it for sure. Got shit to do >.<



________________
CCA 4 Life.


Image
Offline
 Profile Chat  
 
United Kingdom Tofty1996
PostPosted: Fri Aug 05, 2011 12:52 am 
Member
respected.png
User avatar
Featured Articles: 1 100 posts +
Show user details
Male Plays Gmod Plays Minecraft
Unknown Unknown
Posts: 223
I was considering learning this before, and this spurred me on to do so. I've been reading tutorials and with the use of a few pre made scripts I edited (I edited them quite a lot actually), I have managed to create 3 weapons :D They're pretty basic but when I master gLua they will be a lot better and far more interesting.



________________
The Golden Rule of Subservience:

Believe everything, question nothing.


Offline
 Profile Chat  
 
United States Allir
PostPosted: Fri Aug 05, 2011 5:35 pm 
Member
guest.png
Show user details
None specified Plays Gmod Plays Minecraft
Unknown Unknown
Posts: 1
I've been wanting to learn GLua for years, but i didn't like any existing tutorials, thank you so much


Offline
 Profile Chat  
 
United States Uberdude9001
PostPosted: Wed Aug 10, 2011 5:27 am 
Member
respected.png
User avatar
Featured Articles: 1 250 posts +
Show user details
None specified Plays Gmod Plays Minecraft
Unknown Unknown
Posts: 450
This guide is really helpful Delkan. I am very interested in making SWEPs however I have a few questions about them since they will be using custom models. Would you be willing to answer my questions over PM?



________________
Image

BLOOD FOR THE BLOOD GOD, SKULLS FOR THE SKULL THRONE, DEATH TO THE FALSE EMPEROR! KILL THE LOYALIST SCUM! KILL MAIM BURN!
Offline
 Profile Chat  
 
Display posts from previous:  Sort by  
 Page 1 of 2 [ 24 posts ] 

Go to page 1, 2  Next




Who is online

Users browsing this forum: No registered users and 0 guests



You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Search for:
Jump to:  

cron