Stormworks: Build and Rescue

Stormworks: Build and Rescue

81 ratings
Coding / Lua Basics [Beginner Guide]
By Momox
This shall be your start as a (Lua) coder. (For absolute beginners)
3
   
Award
Favorite
Favorited
Unfavorite
Introduction
Hi there!
So you are already hyped for the new Lua blocks, but you don't know how to code? Well I'll try to give you a complete and basic Lua / Coding tutorial.
Be aware: This guide was written on the day of announcement, I did not have any exact information on the implementation of Lua in Stormworks.
Update: Now he have them implemented so this will be updated

Here are some things you have to consider first
- I'll teach you Lua, not lua and especially not LUA (don't call it that, please)
- This is for people who never/rarely worked with anything related to coding before
- I'm far away from being an expert, however I got a decent amateur-level knowledge, which hopefully does the job
- Feel free to correct, criticize or improve this guide/me, however:
- If you are one of those 'pro devs' that just call everyone else's code sh*tty and refuses to state any constructive criticism, feel free to find another guide to trashtalk, this is unwanted here. This guide is from learners for learners, if you don't want to help here, you're on the wrong end. Sorry for the rough words, but I made my experiences...

About me
(Skip if you want, unrelated to coding)
Hi there, to get to a bit of a personal level, let me introduce you, I'm Momox, 19 years old and I happen to live in Germany (excuse me for any grammar flaws/mistakes). I do consider my self an allrounder for technical stuff and been doing a lot of stuff, including Lua.
I've gotten into Lua around 2015. It started out in 2014 when I played Garry's Mod, a Sandbox game which happens to have a similar Logic Concept like Stormworks. There is a mod (Wiremod) I've been working with, starting out with plain Logic (wiring up gates and stuff, just like in Stormworks) and I've preferred it for for years, until someone made me look into E2, a even more simplified version of Lua. I used it for creating custom gates mostly, but then also for creating HUD's and graphical inputs. These were my first steps into easy scripting, some time later, I've gotten into Lua (more exact: gLua, the Lua Garry's Mod used/customized. It's a little bit easier than default Lua, however very much the same).
I made a few gLua gmod Addons (just look at my Workshop) ranging from simple ammo dispensers, to my most complex project: A 2500 line IP Geo Blocker. This was my peak with Lua, however it had a bad end and at the same time, I lost my interest in Gmod. Basically haven't touched it since 2017.
So I have some experience, I can create stuff. Now since Stormworks has similar conditions, I hope your way will be as pleasant as mine.
I want to help people and a "thank you" is more than enough for me. Feel free to ask me anything on Discord :P (Momox#6997)

What you will need (to know)
- Practice is key. I can explain you everything, but it's better for you to learn it in steps: Read, Learn, Try it out. Do some easy stuff and it'll eventually become more advanced.
You might be able to understand simple programs after reading this guide, but the rest it up to you. if you practice, this guide will be enough for you to stand on your own feet.
- Use the wiki to look up syntax of everything, it is your most valuable tool!
- Have someone take a look at your code and give you proper feedback. I'll try but I'm not really shining at that...
- Lua in Microcontroller is pretty much written logic, instead of placing blocks and drawing lines, you will write functions and conditions.

Ready? Let's go.
The very basic of Coding
Oh hey, you are still there, nice to see you haven't already given up :D

Let's go. It's a bit of a read.

How Lua works
From the microcontrollers you are pretty much used to a linear chain, going from left to right, where in the beginning (left side) you can find all of your initial conditions and in the end a final result. All of this is updates each tick (IIRC 60 times per second). So having and add gate of 1 + 2 will calculate that 60 times per seconds, since one of these values could be changed any time and a new result must be there immediatel.
Well it's quite similar in Lua, except you no longer work from left to right, but rather from top to bottom. The compiler (= translates your written code to instructions for the program (stormworks)) runs from top to bottom, every tick once. Making it stuck somewhere will cause the program to freeze there.

Variables
On of the most important part of programming languages are variables.
They are pretty much the same, as memory register blocks, except way more plastic, you can store whatever you want.
Lua makes this very easy, in other languages it is more complex, since you have to declare memory sizes and stuff.

So basically variables are like buckets. You can store something inside of them, read that later on and edit/override it's value or empty it at any time.

First of all you need to declare a variable, meaning you have to tell the system, that you now created a new variable it needs to keep track of, basically you are creating the bucket, you are also telling the programm what kind of bucket is. Does it store numbers? Does it store a boolean (true / false) or maybe a text? This is the only thing you need to tell Lua, it does the rest all alone. How you define it is a bit odd tho, when you declare a variable, it will be fixed to the type of value, you define it with first.
So basically in most programming languages you'd see something like this:
public boolean myBooleanName = false;
Huh. What's that? Let's break it apart word by word:
1: public. Most languages (including Lua) can have public or private buckets (variables). Public (or sometimes global) meaning they can be called, read out or edited from anywhere in the program, private or local would mean it only exists in this very part of the code (for example inside a function).
2: boolean: The type of the variables, what do you want to store in this. Normally there are booleans (true/false condition), numbers (which are divided into subtypes, like integers, floats and others types (defining what kind of number it is (integer would be for example a 3, while a float can be a 2.99). Forget about all of that, you don't need that in Lua :P
3: myBooleanName, you'll want to give your Bucket a name, so you later use it to get it's contents or edit it
4: = false; <-- this set's the initial value of the boolean myBooleanName to false. From now on this is the very same thing. If you asked what the bucket myBooleanName is... it's false, that's it.

So in lua it is a lot easier:
myBoolean = false or myNumber = 21 or myNumber = 1241241.1241
Oh, your first Lua code. Do you already see how much easier it is?
here you can see several buckets being created. They are bound to their intial value type, meaning "myNumber" could always get a new value, as long as it is a number, doesn't matter what. HOWEVER, you can't just try to set it to false or true. Doesn't make sense right? It is a number bucket where only numbers fit in, take a boolean bucket if you want to store a boolean.

That's declaring and defining a variable.
Now the most important part is probably reading them. You don't store a value for nothing.
myBoolean = false a single '=' assigns a value to a variable now a ''==" is a comparison sign. It asks, is the left and the right of it really the same, if so, it is equal to a boolean (true or false) Basically: myNumber = 15 <- assigns a value to a variable myNumber == 15 <- Checks if that is true. This whole line is equal to a simple true boolean once the compiler read over it.
So what's the use of that? The next big part:

if-statements
Now we get going, this is the most important part for controlled logic. Think of a 'greater than gate' or maybe a 'threshold gate'. What do they do? They check for a certain condition and if it is true, they output an on signal. The simple difference in Lua is, that you can check for several different conditions all at the same time and if they are true (or false) you can do a variety of stuff

Now let's get to the syntax, Lua also makes this very easy we need a variable first of all: currentMoney = 50 let's check if someone has enough money: if ( currentMoney > 30 ) then *do something* end

Note *do something* is a placeholder and no actual code, it would't run in Lua!

The above is the simple logic, for a 'greater than gate'. If the variable we declared earlier is greater than 30, it does whatever is in between the 'then' and 'end'
Let's break the syntax down word by word
1: if, declaring we will now do an if statement
2: ( current Money > 30) this is our condition. You actually don't need the brackets, but for the sake of readability, you should get used to setting them anyway.
3: then, telling the compiler our if-condition is finished. If the condition is true, just execute whatever comes before the 'end' and after the 'then'. If not: just skip until after the 'end'
4: end, basically explained above, it marks the end of the if condition

Remember when I explained the meaning of '=='? This is where you will use it most of the time.

This is what we write if ( currentMoney > 30 ) then *do something* end and this is what the compiler makes out of it when it processes it: if ( true ) then *do something* end or if the condition is not met: if ( false ) then *do something* end

if only has boolean in the condition, we just write them differently, as comparisons between numbers and variables mostly.

The next big part: 'else'
Say a condition is met in an if-clause, when coding we are free to define what happens if it's not met

if ( currentMoney > 30) then *tell the player he is rich* else *tell him he's poor* end
Just remember, when using else, one of those to conditions (the if or the else) will always be true and therefore executed.
I hope this was clear enough.

Functions
Functions are your best friends. They are like little workers for you. When you create them, you assign them a task, something they do everytime you call them.
Basically, you create an empty function, give it something to do and once you call them by their 'nickname' they do the task you previously assigned them.

The simplest function is print()
This will work somewhat similar in 90% of coding languages: print("Hello world")
This will output the words 'Hello world' somewhere. Where is currently unknown, usually coding languages are in console views where you can just see that very word.

If you have ever worked with Window's CMD or Powershell Tools, this is what you could expect
instead of print("text") the function for CMD is called echo.

Lua has a lot of pre-made functions. Like math functions:
math.sin(3) will return the sin of 3. (Don't get confused by the . between math and sin, it just means you are calling the function sin of the category math)

But, the most interesting thing are custom functions.

function myNewFunction() end This would define an empty function, which does nothing. Let's give it something to do function myNewFunction() currentMoney = 999999 print("You are now mega-rich") end Now our function has a task, it will execute whenever we call it like that: myNewFunction() Running this line anywhere in the code will exactly do what we assigned the function to.
head over to part 2!
The very basics of coding (part 2)
Well, Steam Guides do have a word limit per section. Annoying. Let's continue.

just now we called a function.

function myNewFunction() currentMoney = 999999 print("You are now mega-rich") end executing myNewFunction() would just be the same as typing currentMoney = 999999 print("You are now mega-rich") anywhere in the program, however you bundled different tasks into one function

That's cool. So functions just bundle tasks and saves me time? Nope. This isn't quite their primary task.

If you had functions and their graphs in math classes, you know the syntax:
f(x) = x² + 3
this is an easy mathematical function. What does it do?
For every x value you enter, it returns you a new value for y (f(x))
So basically:
f(5) = 5² + 3 = 28

What is so important about that you ask? It's the x. f(x). Function f(). You know what the x is? It's a function argument. This is what makes functions so interesting in Lua. Assigning them arguments.

function setPlayerMoney ( amountOfMoney ) currentMoney = amountOfMoney print("Your money amount has been changed") end

This is a function with the argument amountOfMoney.
amountOfMoney is like a local variable, that only exists within the function itself.

setPlayerMoney( 156347634 )

And this is how we call it. Now this function sets a variable to a certain value, a value well tell the function via arguments. Arguments can be anything. Numbers, booleans, whatever.

Can you see an issue here? Where do we define what type of argument we want to use?
Nothing would stop you from doing setPlayerMoney( false ), we never defined what 'amountOfMoney' is (think of the buckets).
Well one thing would stop you. The compiler. It will run into an issue

math.sin(false)

This would return you a compiler error. Probably something along the terms of.
lua: main.lua:1: bad argument #1 to 'sin' (number expected, got boolean)

So Lua trusts in you doing a proper job, otherwise your program might crash :P

Look at where we are

Seems like you've just gotten the basics of Lua. And yes I know, until now it was probably boring, pure infomation to read.

I have intentionally left out some stuff for advanced creations, we'll get to that later, but now I want you to learn on actual Lua code.

Just one more thing left to know: Comments.
You want to structure your code, so you will need comments. Comments are certain text parts which are just completely ignored by the program and are only for humans.
if a line starts with '--' everything after that will be ignored by the programm.
Doing '-- this function does that and that' is possible and recommended to do for learners
You can also do that multiline
--[[
Everything
between these signs
will be ignored
--]]
now everything back to normal.

Tip: if a part of your code does not work for unknown reasons, don't delete it, comment it out using multiline comments. That way the code is still there if you need it but it no longer causes errors as it is invisible to the compiler.

Let's combine all of the above into a neat little program

TITLE: Player Money System moneyPlayer = math.random(10, 1000) --math.random(lower, upper) returns a random number between the lower and upper one. applePrice = 10 --creating a simple number playerApples = 10--how many apples the player has function buyApples ( amount ) if (moneyPlayer > applePrice * amount) then moneyPlayer = moneyPlayer - applePrice * amount playerApples = amount else print("Sorry, you don't have enough money for that") end end

Now this is actual code, but there's a huge problem. You can barely read that on Steam, since there code formatting is pretty ... not good.
This makes it hard for me to indent the code. Indent? Whats that you ask? Well it's a nice habbit every developer should get used to. That's why you have a Tab key on your keyboard.
You use that to structure your code. I can't really explain you how you do it, but you'll grow a feeling for it. Here is the above code in proper structure:


Looks much cleaner and easier to read using colors and structure.
Other habits are leaving an empty line as I do (but not everyone likes that), inside of functions and if statements. It doesn't matter what other people like, its primary focus is so you can read it better and work on it.
Or you can leave a blankspace on the inside edge of brackets "function( Whatever )"
Enough of that.

By now I recommend you doing the practice part. I gotta admit, without the implementation of Lua ingame yet, this is rough. You can use a program like Sublime or Notepad++ to mess around, or sth I like: An online compiler, that tests your code ( this one is nice: https://www.tutorialspoint.com/execute_lua_online.php )
I'll try to update this.

The next part is a bit more advanced knowledge. If you feel like it, proceed, if you're stuck, feel free ask me on Discord (Momox#6997).



More advanced stuff
Oh hi, welcome back. Good to see I haven't lost you yet.

This section is focused on a more advanced stuff and further practice.

Variables
A little excourse on variables.

Variable
Description
Numbers
Numbers of any kind (like 1;2;3;4.2323;0.00003)
Booleans
true or false
Strings
"Text that's always in quotation marks!"

These are the 3 variables you will mostly be working with. Technically, even functions are variables, but that's another story.

There's something new. Strings. I have intentionally left them out, because I don't know how they will be implemented. But let's get to it.

print("This is a basic print") myText = "And this is a print using a variable." print(myText)

It is a fairly easy kind of variable.
The only thing special about it is combining.

myText1 = "I have currently " myNumber = 25 myText2 = " apples." print( myText .. my Number .. myText2) Output: console: I have currently 25 apples.

Using '..' combines strings with other variables (keep blankspaces in mind). It's also the way to convert numbers to strings.
Say you want to just print a number, this is not possible. The function print() uses a string as argument, not a number. An easy workaround:

print( 25 .. "")

Lua should accept that, as it just combines a number with an empty string. Which in the end, is just "25".

Tables
Tables are the equivalent of arrays if you are familiar with other coding languages.

They are a neat way to combine multiple variables and store them into a single one. Kinda.

myTable = { "This is the first Value", "Then comes the second", 5, "Even numbers or bools are possible", false} -- So how do I make any use of this? You can call them by their index: table[n] myTable[1] == "This is the first Value" myTable[3] == 5 myTable[5] == false

That's nice. But where would you use that? Data. Tables are your everything for storing, sorting and using data. Because you can add, remove and sort data inside tables:

myEmptyTable = {} table.insert(myEmptyTable, "This is a value") -- Now the Table has a value inside myEmptyTable[1] == This is a value -- annnnnddddd table.remove(myEmptyTable, 1) -- deletes the first entry in a table -- Now it's empty again :(

I'd love to teach you more about this, but I currently do not have any more suitable examples and I gotta admit, that I'm out of practice on that one.

Here's a bit from the official Lua wiki if you want to learn more: http://lua-users.org/wiki/TableLibraryTutorial

Advanced if conditions
You may have noticed a minor flaw. In the if-chapter I stated that you can use multiple conditions, but I never explained how.

-- lets change that myNumber = 24 mySecondNumber = math.random(0,24) if (mySecondNumber >= myNumber && mySecondNumber =< 25 || mySecondNumber == 24) then do something end
Let's brake it down. '&&' or 'and' is the same as AND Gate. If the condition left to it AND the conditon right to it are true, then you may proceed, if one of those is false, the whole condition is false '||' or 'or' is quite self-explaining. Shouldn't be too hard, right?
Useful Resources
Every developer has some sort of tool or knowledge-base. It takes a lot of time to know every function and it's syntax in a coding language, that's why there are usually wikis. Here's a collection of tools you might find useful:

Online Compiler
This site[lua.flaffipony.rocks] is the best way to learn Lua outside the game. It features a lot of documentation, an online compiler and various Stormworks related tools

The official Lua wiki
Link[lua-users.org]. This is the official Lua wiki. It features everything to know about Lua. However I'm not a big fan of it, it's rough for beginners.

The Gmod wiki
It is way more pleasant, features tutorials and code examples and is community based. Buuuuttt there's one clue. It's not entirely Lua. It's gLua, slightly modified and it features more functions. It's 80% the same as default Lua tho. It's is a great start and it is what I used to learn Lua.
I'd feel bad if I didn't mention even tho it might not fit 100%.
Here's the link.[wiki.garrysmod.com]. PS: Don't bug the Gmod / gLua Community with your questions. Ask me instead.

The official Lua handbook
This site[www.lua.org] features a short overview about everything there is in Lua.

An inofficial guide
This one[www.tutorialspoint.com] is quite nice if I couldn't do the job for you :P
The End
Another guide another end.

Thank you very much for reading this.
Seriously. In my opinion knowledge must be shared, that's why I write this. But if no one reads this, my mission was for nothing.

My personal inquiry to you

For anyone
If you spot any grammar issue or non-typical typos, aswell as issues with text signs, tell me! I have an English exam coming up in a few days so I wouldn't mind.
Also, I have a weird eye condition. I can see normally, however on some days my eyes are extremly dried out and I can't keep them open for longer than 2-3 seconds. This is/was the case of writing this guide, that's why I couldn't proof read everything again. (I know this sounds like a generic excuse, it isn't however, ensuring a base quality is important for me so it's annoying for me that I currently have a hard time doing so (just google for lipid deficiency or Dry eye disease)).
So just tell me and I'll make sure to fix any mistakes.

If you were a beginner, please provide me with feedback. This is vital. For me everything in this guide makes practical sense. Sure, but probably not for you. And I want to change that. But I need to find the issue spots first. Feel free to tell me on Discord (Momox#6997) if you encountered any problems or if you have ideas for improvement. Seriously, be honest, if you don't understand anything at all, don't talk around it.

If you are already experienced in Lua
wow, did you honestly read that? Yes? Great. I also invite you to provide me with feedback, especially if you noticed any mistakes. Just add me on Steam or Discord (Momox#6997).
I probably also need a few "experts" I can count on. It is possible that a lot of people will ask me questions and that's ok, but I have limited resources and time. If you are willing to, just tell me and I'll refer questions to you or note you down somewhere in the guide.

I'm thinking about expanding this depending on it's success. Maybe I'll do video tutorials or another guide on this matter... Just waiting for feedback currently.

Credits
- The people that taught me gLua way back in 2015-2017
- Queen for providing me with some seriously good music while writing this.
- Me for writing this I guess?
- You if you want to contribute ;P
27 Comments
wdubois.slz 14 Jun, 2024 @ 10:50pm 
I agree, Queen does provide excellent music for just about anything. Mamaaaaa!
Excelsior_Gaming 28 Mar, 2022 @ 4:43am 
Then you need help remembering
C-Corgi 4 Mar, 2022 @ 2:37pm 
ok ummm I think my account was hacked I do not remeber typing that comment on Apr 8, 2021
Momox  [author] 4 Mar, 2022 @ 11:01am 
I fully agree with you.
The guide has been written prior to the implementation of lua in the game so I had to blind guess. The purpose of it is to give you enough understanding and context to follow other guides and tutorials, hope it was helpful!
Excelsior_Gaming 4 Mar, 2022 @ 6:25am 
I was recently reading this and surface level it is pretty helpful but, the game has evolved to be very Lua inclusive and some of this information isn’t helpful regarding implementation. Ver coherent guide however and I may take my purposes elsewhere to a more specific guide.
C-Corgi 8 Apr, 2021 @ 10:11am 
ok
Momox  [author] 8 Apr, 2021 @ 9:49am 
Haha, cheers man. My English exam was 2 years ago so that worked out lol. Time to forget everything again :D
C-Corgi 8 Apr, 2021 @ 8:04am 
For anyone
If you spot any grammar issue or non-typical typos, aswell as issues with text signs, tell me! I have an English exam coming up in a few days so I wouldn't mind. you need to replace it with For anyone
If you spot any grammar issues or non-typical typos, as well as issues with text signs, tell me! I have an English exam coming up in a few days so I wouldn't mind.
Tucolol 19 Jul, 2019 @ 7:30am 
not to be rude or anything but at the end i remembered none of it but i liked the guide tho
Yurik2012 17 Jul, 2019 @ 9:17am 
go