Seeing as a few people on the server seem keen to learn E2, I'll link a few useful resources. If there's anything in particular you'd like me to write a tutorial for let me know and I'll see what I can do.
Last updated: 08/07/2012 - Added data management section.
1. Basic concepts and syntax
Let me begin by clarifying the syntax I will use and some of the basic concepts of Expression 2.
Keeping code readable I would advise you to keep your code well indented and not to write more than one action per line. This keeps your code clean and readable. To indent a section of code, use Ctrl + I. To delete an indent from a section, use Ctrl + Shift + I. The editor will auto-indent new lines that follow a { bracket.
Comments
I usually comment my code by the following method:
Code:
#This is a comment.
You may see code commented with more than one #, it makes no difference. Only one # is necessary for a line to be considered a comment.
To bulk comment a section, use the following syntax:
Code:
#[
Commented section
]#
I would advise you add comments to any major sections of code to explain what it is doing. This will help you if you ever leave it and come back to it, or if you are showing it to someone else. You can have the editor comment a section for you automatically by selecting the section and pressing Ctrl + K. It can uncomment the same section with Ctrl + Shift + K.
Main data types: Numbers
Unlike languages such as C++, Expression 2 only has one data type for numerical values. Numbers can be integers, long integers or floating point numbers, there is no distinction between them. Standard operations like addition, multiplication etc. are all defined for numbers.
Code:
N = 1.5
M = 2
O = N + M #O is 3.5.
Vectors (2D, 3D and 4D)
Vectors are formed from two, three or four number components. They have most standard operations defined. However, you cannot compare one vector to another in ways such as 'greater than'. Also, the multiplication operator * will multiply element by element, as will the division operator. This is not true vector calculus.
Strings
Strings are formed by encasing a set of characters with ". String addition will concatenate the values, subtraction, multiplication and division are undefined. You also cannot compare strings directly with the 'greater than', 'less than' etc. operators. Equality between strings is case sensitive.
Code:
String1 = "Cookies"
String2 = " and Milk!"
String3 = String1+String2 #String 3 is "Cookies and Milk!".
Entities
Entities are references to objects in the game world. Addition, subtraction, multiplication and division are not defined for entities. You cannot compare size of entities using 'greater than' or 'less than'. You can check if entities are equal.
Code:
Entity = entity()
Owner = owner()
if(Entity:owner() == Owner)
{
hint("You indeed own your E2 chip!",7)
}
True-false concepts in Expression 2
In Expression 2, true is generally given by an output of 1, false is an output of 0. There is no boolean data type. Examples of what is considered 'true':
A number is considered 'true' if it is non-zero. Thus if(A) is equivalent to if(A != 0).
A string is considered 'true' if it has length more than 0. Thus if(String) is equivalent to if(String != "").
A vector is considered 'true' if it is not (0,0,0). Thus if(Vector) is equivalent to if(Vector != vec(0,0,0)). Similar for 2-dimensional and 4-dimensional vectors.
An entity is considered 'true' if the entity is not null. Thus if(Ent) is equivalent to if(Ent != noentity()).
Operators
Expression 2 has numerous operators, I have listed them below.
Code:
A = B #Assign operator, sets the variable A to the value of B. NOT the same as ==.
A & B #'And' operator, returns 1 if both A and B are true.
A | B #'Or' operator, returns 1 if either of A or B or both are true.
A == B #'Equal' operator, returns 1 if A is the same as B.
A != B #'Not equal' operator, returns 1 if A is different from B.
A > B #'Greater than' operator, returns 1 if A is larger than B (not defined for all data types).
A < B #'Less than' operator, returns 1 if A is less than B (not defined for all data types).
A <= B #'Less than or equal' operator, returns 1 is A is less than or equal to B (not defined for all data types).
A >= B #'Greater than or equal' operator, returns 1 if A is greater than or equal to B (not defined for all data types).
!A #'Not' operator, returns 1 if A is false, 0 if A is true.
$A #Returns by how much A changed since the last execution. Only works for a variable stored in @persist that has subtraction defined.
~A #Returns 1 if the current execution was caused by a change in the input A.
->A #Returns 1 if the input A is wired. If A is an output, it returns how many inputs A is wired to.
A && B #Bitwise 'and' operator. Checks if both A and B are true per bit.
A || B #Bitwise 'or' operator. Checks if either A or B or both are true per bit.
A ^^ B #Bitwise 'exclusive or' operator. Only returns 1 if either A or B but NOT both are true.
A << B #Performs a bitwise left shift on the first number by the amount of the second number.
A >> B #Performs a bitwise right shift on the first number by the amount of the second number.
If statements
The way I code E2 (and any similar languages with the if() {} syntax) is as follows:
Code:
if(Condition)
{
action()
}
If you prefer, you may write if statements differently, a common alternative is:
Code:
if(Condition) {
action()
}
There is no difference between them in the way they are executed, only in the way they look in the editor and the amount of lines taken up. Write however you feel comfortable, though I will be using the former method throughout this set of tutorials.
If statements can, but do not have to, include an else statement. This is written as follows:
Code:
if(Condition)
{
action1()
}
else
{
action2()
}
They may also include elseif statements, which are ran only if both the above statement(s) is false and the condition given in the elseif statement is true.
Here, if 'Condition' is false and 'Condition2' is true, then 'action2' will be executed. Otherwise, if both 'Condition' and 'Condition2' are false, 'action3' is executed. I will go into an alternate notation for this in section 2 (see 'Switch statement').
Arrays, Tables and Wirelinks
Arrays, tables and wirelinks have similar syntax and follow similar ideas. They assign a collection of data (not necessarily the same type) to a set of key values, which index each element. Arrays are limited to only integer values for keys, i.e 1, 2, 3. Tables and wirelinks can be indexed by strings or integers.
Retrieving values:
Code:
#Newer syntax
Value = Array[Number Index, type] #This will retrieve the value stored in the given index with the given data type.
Value = Table[Number/String Index, type] #This will retrieve the value stored in the given index or string index with the given data type.
Value = Wirelink[Wire Output, type] #This will retrieve the value of the wire output of the given name and type.
#Old, deprecated syntax
Value = Array:type(Number Index)
Value = Table:type(Number/String Index)
Value = Wirelink:type(Wire Output)
Setting values:
Code:
#Newer syntax
Array[Number Index, type] = Value #Sets the value in the array at the given index to Value.
Table[Number/String Index, type] = Value #Sets the value in the table at the given index or string index to Value.
Wirelink[Wire Input, type] = Value #Sends Value to the given input of the wirelinked entity.
#Old, deprecated syntax
Array:setType(Number Index) = Value
Table:setType(Number/String Index) = Value
Wirelink:setType(Wire Input) = Value
2. Loops/Statements
These are covered on the wiki but I don't think it's quite clear how they work. Each of these loops is ran every execution, as in, the chip must get through the entire loop before it will execute the chip again. It will never stop a loop halfway and start again unless you tell it to.
The for loop
First of all, the for loop. What this does is, you set a number to start with, you set a number that you want it to finish on, and you set the amount to increase the number you have each iteration. For example,
Code:
for(I = 1, 5) #Start at 1, go until 5. Increase by 1 each time as that's the default.
{
hint("We're on iteration "+I,7) #Create a hint that says what iteration we're on.
}
This will display a hint that on the first run says "We're on iteration 1", then it will add 1 to I and run through the loop again, this time hinting "We're on iteration 2" and so on, until I = 5. Once it reaches the iteration where I = 5, it will hint "We're on iteration 5" and then end, doing nothing more.
You can change the amount to increase 'I' by each time, and you can call 'I' whatever you want.
Code:
for(Cookie = 1, 11, 2) #Start on 1, go until 11, increase by 2 each time.
{
hint("We're on iteration "+((Cookie+1)/2),7) #Create a hint that says what iteration we're on, not the value of Cookie.
}
The for loop is generally used for acting upon part or all of an array, as arrays have elements indexed by a number. You can also use it to act upon a table if the table's elements are indexed by a number, but not if they are indexed by a string. That is where the foreach loop is used.
The foreach loop
This loop has a similar idea to the for loop, however, it is made to iterate specifically over tables. What it allows you to do is iterate over every element of a table of a given type. The foreach loop is used for elements with a string index in a table, whereas the for loop is for elements with a numerical index. The foreach loop can also loop through an array and it can be easier to use than the for loop, but it will NOT retain order. Thus, if going through indexes of an array in order is important, use the numeric for loop instead.
Code:
@name For each example
@persist Table:table
if(first()) #Create our table of values.
{
Table["One",string] = "1"
Table["Two",string] = "2"
Table["Three",string] = "3"
Table["Four",string] = "4"
}
foreach(K, V:string=Table) #For every table entry in 'Table' of type string, create a hint of its value.
{
hint(K+" = "+V,7) #Will hint K = V for every pair K and V. K is the key, i.e "One", "Two", etc. whilst V is the value, i.e "1", "2" etc.
}
The above code will create hints saying One = 1, Two = 2, Three = 3 and Four = 4. Note however that it is not going to be in any order, it will simply iterate through the table as it sees fit.
Like the for loop, you can change K and V to whatever you like.
The while loop
This loop is probably the least used and the most prone to causing a chip to exceed the ops quota. This is because you can very easily create an infinite loop that will never end, thus causing E2 to shut down your chip.
Essentially, the while loop says, while certain conditions hold, keep on doing something until those conditions no longer hold. If the conditions will always hold, then you will have an infinite loop and your E2 will shut down.
An example of a bad while loop:
Code:
I = 0
while(I == 0) #As long as I is 0, keep running the code.
{
J++
}
I is not being changed, so it will always be 0 and thus the loop will forever continue until the ops quota is exceeded, at which point it will terminate the chip.
An example of a good while loop:
Code:
I = 0
while(I < 500) #As long as I is less than 500, keep running the code.
{
I++
}
This will keep on adding 1 to I each iteration until I reaches 500, at which point the conditions in the while statement no longer hold and thus the while loop is completed.
If you are unsure as to whether your while loop's condition will be false in time to stop it, you can add the perf() condition. This will stop the loop if it is about to exceed the ops quota. For example:
Code:
I = 0
while(I == 0 & perf()) #As long as I is 0 and we're not going to exceed the ops quota, keep running the code.
{
J++
}
This will increase J up until the ops quota is reached, at which point the while loop will stop, but your E2 will keep running.
Breaking loops
Sometimes you may wish to have criteria that will end a loop before it would normally do so, for instance, you wish to iterate over a table of players until you find one with the name you're looking for. Rather than let the loop carry on until completion, if you have what you want you can end the loop.
Here we wanted J to be above 10, so we can end the loop once that occurs, saving it from looping further.
The switch statement
This statement is not listed on the Wiremod wiki and seems to be somewhat of a hidden gem. In C++ and other languages, you can use the switch statement instead of long lists of elseifs to deal with multiple cases concerning a single variable.
Note: In my testing, it would appear the default case is not executed correctly, thus you may wish to omit it, or use if, elseifs and else if you need it.
An example:
Code:
@name Switch Test
@inputs N
switch(N) #We're looking at the N variable.
{
case 0, #If N is 0, say so.
hint("N is zero.",7)
break #Stop here.
case 4, #If N is 4 then say N is an even number.
hint("N is an even number.",7)
case 1,
case 9, #If N is 9, or 1, or 4, then say N is a perfect square.
hint("N is a perfect square.",7)
break
case 2, #If N is 2, then say N is an even number.
hint("N is an even number.",7)
case 3,
case 5,
case 7, #If N is 2, 3, 5 or 7, then say N is a prime number.
hint("N is a prime number.",7)
break #Stop.
case 6,
case 8, #If N is 6 or 8, then say N is an even number.
hint("N is an even number.",7)
break #Stop.
default, #If N is not one of the above, then say only single-digit numbers are allowed.
hint("Only single-digit numbers are allowed.",7)
}
Note that it is imperative you break the end of each case you want to finish on, otherwise the value will fall through until it reaches 'break', executing every case between. Also remember the comma after each case and 'default'.
Switch is not just for numbers, you can use it for strings, vectors, entities and anything else you can compare in an if statement too.
As a side not of interest, Lua doesn't have a native switch statement.
3. Expression 2 Graphics Processor v3
For learning EGP, I'll outline some of the basic ideas here. This guide assumes you've read at least the beginner's guide linked above.
How does EGP work?
EGP works by creating elements. These can be some text, a box, a box outline, a circle, a circle outline, a triangle, a triangle outline etc. Each element must be given an index, every EGP command will start with this index so that it knows which element to work with.
Each element must then be given a position on the screen, which is 512x512 units. The positioning works a little oddly, the first co-ordinate is how far along the screen to go, then the second is how far down to go. The point (0,0) is the top left of the screen, the point (512,512) is the bottom right. In order to edit an EGP screen, you need to create a wirelink input for it which is then used to control it.
For instance:
Code:
@name EGP Test
@inputs EGP:wirelink
EGP:egpText(1,"Hello World!",vec2(256,256)) #Creates a text element with index 1, with text "Hello World!" and at the position (256,256).
EGP:egpFont(1,"Trebuchet",16) #Gives the element 1 the font "Trebuchet" and makes the text size 16.
EGP:egpAlign(1,1) #Aligns the text element 1 to the centre. You can use (1,0) to align left or (1,2) to align right. The second number determines alignment.
would create text in the middle of the screen saying "Hello World!".
Note the syntax to all EGP functions, egpFunction(Index, Arguments). The index, which is 1 in the above code, is a number that you assign the element you are creating with the egpText(), egpBox(), egpCircle() etc. functions. Then whenever you want to edit it (for instance using egpAlpha()) you must first tell the function which element it is using, by giving it the index, then how you want to change it.
You can have up to 300 elements, so your indexes must be an integer (whole number) between 1 and 300 inclusive. Any lower or higher will be clamped into that range, meaning if you had an element with index 301, it would in fact be the element of index 300.
How should I create each element?
This is a key point in EGP. It won't matter so much for small chips if you have them creating elements every time they're executed, but as you add more and more to a chip, you have to start thinking about how much it will have to process each time.
So the idea is, you create all the elements on the first execution of the chip once it's connected to the screen. This means EGP only has to make them once, then you can just change them around later on. To achieve this, simply use:
Code:
~EGP #will check to see if the chip is running because the EGP input changed, if it is, it will return true.
->EGP #will check to see if the EGP input is wired. If it is, it will return true.
first() #will return true if the chip is executing for the first time.
To see this in practice:
Code:
@name Hello World!
@inputs EGP:wirelink #We need to connect to the EGP screen using a wirelink, standard practice is to put it in the inputs, not outputs.
if((~EGP & ->EGP) | first()) #If the chip has been executed because we've changed the EGP input and we're connected to the screen, or if it is the first execution (i.e the chip was just updated) then make our "Hello World!" text.
{
EGP:egpText(1,"Hello World!",vec2(256,256))
EGP:egpFont(1,"Trebuchet",16)
EGP:egpAlign(1,1)
}
If you create all the elements you need in this statement, then you will avoid problems later on with the screen becoming laggy and unresponsive. The first() part makes sure that any changes you make to the values in the statement are sent to the screen if you update the chip after spawning it.
How do I edit an element?
Editing an element is as easy as creating one. You simply use the commands you want to set the colour, change the size or the font, change the position or even edit the text. You will rarely ever need to recreate an element, only ever edit it.
An example of how not to code it:
Code:
@name Hello World!
@inputs EGP:wirelink Button
@trigger all
if((~EGP & ->EGP) | first()) #As before, we create the element using the egpText command but only the first execution after we connect to the screen.
{
EGP:egpText(1,"Hello World!",vec2(256,256))
EGP:egpFont(1,"Trebuchet",16)
EGP:egpAlign(1,1)
}
if(~Button & Button) #If someone pressed the button, then change the text to say "You pressed the button!" and change its colour to red.
{
EGP:egpRemove(1) #This will remove the element with index 1, thus meaning you need to recreate it in order to use it again.
EGP:egpText(1,"You pressed the button!",vec2(256,256)) #This recreates the text, indexes it to 1 and resets its position. All of which is unnecessary.
EGP:egpFont(1,"Trebuchet",16)
EGP:egpAlign(1,1)
EGP:egpColor(1,255,0,0,255)
}
elseif(~Button & !Button) #If the button's off, then set our text back to "Hello World!" and make it white.
{
EGP:egpRemove(1)
EGP:egpText(1,"Hello World!",vec2(256,256))
EGP:egpFont(1,"Trebuchet",16)
EGP:egpAlign(1,1)
EGP:egpColor(1,255,255,255,255)
}
Coding EGP like this will make your screen very slow to update and will not be able to keep up with changing inputs. It will recreate the text in the centre every time you change the button input, which not only is a lot slower to do than just changing the text, it is extremely inefficient and not necessary.
Instead, do something like this:
Code:
@name Hello World!
@inputs EGP:wirelink Button
@trigger all
if((~EGP & ->EGP) | first()) #As before, we create the element using the egpText command but only the first execution after we connect to the screen.
{
EGP:egpText(1,"Hello World!",vec2(256,256))
EGP:egpFont(1,"Trebuchet",16)
EGP:egpAlign(1,1)
}
if(~Button & Button) #If someone pressed the button, then change the text to say "You pressed the button!" and change its colour to red.
{
EGP:egpSetText(1,"You pressed the button!")
EGP:egpColor(1,255,0,0,255)
}
elseif(~Button && !Button) #If the button's off, then set our text back to "Hello World!" and make it white.
{
EGP:egpSetText(1,"Hello World!")
EGP:egpColor(1,255,255,255,255)
}
Notice how I used egpSetText() to change the text. This is something you should always do, just use the commands to change its text, or its position or colour or whatever it is you want to change. Using the egpSetText() function to change the text or egpPos() to change the position is much faster to update on the screen than removing or recreating the element with egpText()!
If you don't want an element to be seen on the screen but you will use it later, then instead of removing it, just hide it using:
Code:
EGP:egpAlpha(1,0) #Set the alpha to 0, which makes it invisible.
You can then bring it back into view later using the alpha command again with value 255. Changing the alpha is a lot faster than removing and recreating, you should only remove elements you are sure you will not use again.
Using the Stargate (and other) fonts:
If you want to use the Stargate fonts with EGP, you have to modify a Lua file if you want them in singleplayer. The file to modify is found in
4. Use of variables
You will notice that in the code above, I defined the position of each element using numbers directly in the code. This is inefficient and means you cannot easily change things later on if you have a much larger chip. Instead, consider creating variables which store, for instance, the position of your "Hello World!" text and the colours you want when the button is on and off.
In E2, we use @persist variables in order to store the information we want. Persist variables, as the name implies, persist between executions. That is, they will not be discarded when the chip runs again, so they will remain as what they are set to until changed.
An example:
Code:
@name Hello World!
@inputs EGP:wirelink Button
@persist [OnCol OffCol]:vector4 HWPos:vector2 #Make available two 4D vectors and a 2D vector for use.
@trigger all
if(first()) #On first execution, store our persist variables as the following.
{
OnCol = vec4(255,0,0,255) #Stores the 4D vector (255,0,0,255) as the OnCol variable. This will be used to make the text red.
OffCol = vec4(255,255,255,255) #Stores the 4D vector (255,255,255,255) as the OffCol variable. This will be used to make the text white.
HWPos = vec2(256,256) #Stores the 2D vector (256,256) as the HWPos variable. This will be used to place the text in the centre of the screen.
}
if((~EGP & ->EGP) | first())
{
EGP:egpText(1,"Hello World!",HWPos) #Make our text in the HWPos position.
EGP:egpFont(1,"Trebuchet",16)
EGP:egpAlign(1,1)
}
if(~Button & Button)
{
EGP:egpSetText(1,"You pressed the button!")
EGP:egpColor(1,OnCol) #Set the colour to OnCol.
}
elseif(~Button & !Button)
{
EGP:egpSetText(1,"Hello World!")
EGP:egpColor(1,OffCol) #Set the colour to OffCol.
}
Now imagine if we had a much longer chip where we used those two colours and that position many times over. If you ever wanted to tweak it and you didn't use variables, you'd have to go through every single colour and position command and change the numbers. Using variables means you only need to change the variable at the top of the chip and then every time you use it, it will use the new one instead.
5. Data Management (Arrays and Tables)
When you want to store a lot of information, making tens of individual persist variables is usually a very bad idea. This is where arrays and tables are useful.
What is an array?
The most basic definition of an array is simply an ordered list of values. Each one has an integer (whole number) index which references the point in the array it is stored. Arrays in Expression 2 can store multiple data types in a single array.
Their structure is as follows:
Code:
Array[ Number Index, value type ] = Stored Variable
Each element needs a number index. Arrays have elements stored in order from 1 up to the max array size, which is 1048576 entries. The index tells Expression 2 where to find the element in the array when it needs to access it. Each element also needs a type, these types are the same ones you use for inputs and outputs. This tells Expression 2 what type of variable to expect at the given index.
An example of how to set a few different array elements:
Code:
@name Array of stuff
@persist Array:array
Array[1,string] = "cake" #Element 1 is the string "cake"
Array[2,entity] = owner() #Element 2 is the chip's owner entity.
Array[3,number] = 8880 #Element 3 is the number 8880
Array[4,vector] = vec(0,0,1) #Element 4 is the vector (0,0,1)
print( Array[1,string] ) #This will print 'cake', as we got the first entry in the array.
Note however that usually an array contains elements which are all the same type, such as the players() array, which returns an array with every player on the server as an entity.
An example of why an array is useful:
Code:
@name Address Log
@inputs Open DialAddr:string
@persist Addresses:array
if(~Open & Open) #If the gate's open, then add the address to the array.
{
Addresses:pushString(DialAddr) #Add the string to the end of the array.
}
This will store every address a Stargate dials into the Addresses array, which you can then display it on an EGP screen. So when you first dial a gate, it makes Addresses[1,string] = the dialled address. Then when you dial again, Address[2,string] is the address and so on.
If you want to know how many elements are in an array, then use:
Code:
NumberOfElements = Array:count()
This won't work correctly if an array has gaps in it, it will only be correct for arrays that have 1, 2, 3, ... n elements, with each index holding a value.
Iterating over an array
Arrays are perfect to use with the for loop as they're indexed by numbers. An example:
Code:
@name Iterating Example
@persist Array:array Count
Array = array("cake","pizza","cookies","milk") #Make an array with 4 string elements.
Count = Array:count() #Count how many elements there are.
for(Index = 1, Count) #Iterate from Index == 1 to Index == Count, we add 1 to Index each time we run through the loop.
{
if(Array[Index,string] == "cookies" | Array[Index,string] == "milk") #If the value in the array we're looking at is "cookies" or "milk"
{
hint("Good choice.",7) #Tell the player they made the right choice.
}
}
What is a table?
A table is an extension to arrays. Instead of only allowing numerical indexes, you can also store values at string indexes. This allows you to organise data in more ways than an array.
Examples of table entries:
Code:
Table["Cake",string] = "Chocolate" #The string indexed by "Cake" is "Chocolate".
Table[owner():name(),string] = owner():steamID() #The string indexed by the owner's name is their Steam ID.
Table["Owner",entity] = owner() #The entity indexed by "Owner" is the owner entity.
Note how they can be indexed by strings as well as numbers.
An example of the difference:
Code:
@name Player SteamID storage
@persist Table:table
Players = players()
for(I =1, Players:count()) #For every player on the server.
{
local Player = Players[I,entity] #This makes things a bit less messy.
Table[Player:name(), string] = Player:steamID() #Store their Steam ID in the table, with index of their player name.
}
Combine this with the file extension and vON which I cover later and you can have permenant storage of player's SteamIDs to use with dupe protection or other access restrictions.
6. Controlling chip execution
By default, an Expression 2 chip will execute every time an input is changed and that's it. This is fine for simple chips which have a few wire inputs, but for chips using wirelinks or maybe no inputs at all, this is not enough. This is where the runOn*(), interval() and timer() commands come in. You may also wish for the chip to execute only when certain inputs change, not all of them.
The @trigger section
At the top of a chip you will usually have @name, @inputs, @outputs and @persist. If you want to control which inputs trigger a chip execution, then you need to add @trigger.
Code:
@name Trigger Test
@inputs Button1 Button2
@outputs String:string
@trigger all #Trigger an execution for all input changes. This is the default behaviour, this line does not need to be added.
if(Button1)
{
String = "Button 1 pressed"
}
if(Button2)
{
String = "Button 2 pressed"
}
Here the code will run if Button1 changes or if Button2 changes, which will mean if you turn button 1 on then 2, the string will read "Button 2 pressed". However, if you press button 2 then button 1, the string will still read "Button 2 pressed", as it runs the code in the order it is written, meaning it will set the String to "Button 1 pressed" then to "Button 2 pressed" again.
You may wish instead for it to only trigger when Button1 is pressed.
Code:
@name Trigger Test
@inputs Button1 Button2
@outputs String:string
@trigger Button1 #Trigger an execution only when Button1 changes.
if(Button1)
{
String = "Button 1 pressed"
}
if(Button2)
{
String = "Button 2 pressed"
}
Now if you press button 1 then 2, it will say "Button 1 pressed", as it never executed again when Button2 changed.
From the EGP section of this guide, you can see I use ~Input to detect if the chip is executing because of an input change. This can be very useful if you wish to increment a value only when the Button1 input changes, for instance:
Code:
@name Trigger Test
@inputs Button1 Button2
@outputs Value
@trigger all #Trigger an execution for all input changes.
if(~Button1 & Button1) #If the current execution is because 'Button1' changed and 'Button1' is on then increase 'Value' by 1.
{
Value++
}
Now when we press button 1, it will increase the value output by 1, but if we press button 2, the value will not change as the execution will not have been caused by a change in the Button1 input.
If you would prefer, you can stop all input based execution by adding:
Code:
@trigger none
to the top of your E2 code. You will have to use the functions below to get the chip to execute again after the first time.
Intervals
The next most commonly used way to execute a chip is an interval. What this does is execute the chip every given amount of milliseconds regardless of any input changes. This is required for wirelinks as they do not cause the chip to execute if a value in the wirelink changes.
One thing to note about intervals is to not set them too low. The more times the chip executes per second, the more the ops count will grow and for more complicated chips, it can cause noticeable server lag. Only set the interval as fast as you need it.
For example:
Code:
@name Interval Test
@inputs Input:wirelink
@outputs Value
interval(100) #Execute the chip every 100ms, which is every tenth of a second. This is generally the fastest you will want to set an interval.
Value = Input["Number",number] #Set the 'Value' output to that of the 'Number' output retrieved from the wirelink.
Without the interval, the chip would execute once when spawned then once when the input is wired and then stop. It will only retrieve the initial value for the "Number" value in the wirelink regardless of whether it then changes. The interval means it will check that "Number" value every tenth of a second and change the 'Value' output to match it each time.
Much like inputs, you can check to see if the chip is executing because of the interval using the clk() function.
Code:
@name Interval Test
@inputs Button
@outputs Value1 Value2
interval(100) #Execute the chip every 100ms, which is every tenth of a second.
if(clk()) #If the chip is executing because of the interval, then increase 'Value1' by 1.
{
Value1++
}
if(~Button & Button) #If the chip is executing because 'Button' changed and the button is pressed, then increase 'Value2' by 1.
{
Value2++
}
This code will ensure Value1 is increasing only when the chip is executing because of the interval so it increases at a constant rate. Meanwhile Value2 will only increase when the button causes a chip execution and the button is not sending 0.
An important ability with intervals is the ability to stop them. This is key to creating chips that don't waste ops working when there's nothing to work with. For example:
Code:
@name Interval Test
@inputs Input
@outputs Value1
if(!->Input) #If we have no input connected, then stop the interval.
{
stoptimer("interval")
}
else
{
interval(100) #Execute the chip every 100ms, which is every tenth of a second.
if(clk()) #If the chip is executing because of the interval, then increase 'Value1' by 1.
{
Value1++
}
}
This code will only run on an interval if the 'Input' input is wired. Otherwise it stops any running interval and does nothing.
Timers
Timers are a lot like intervals in the sense that they cause a chip execution every set amount of time. Unlike intervals however, they can be given names and thus used to only run specific code in specific time frames.
For example:
Code:
@name Timer Test
@outputs Value1 Value2
timer("Value1",100)
timer("Value2",1000)
if(clk("Value1")) #If the chip is executing because of the "Value1" timer, then increase 'Value1' by 1.
{
Value1++
}
if(clk("Value2")) #If the chip is executing because of the "Value2" timer, then increase 'Value2' by 1.
{
Value2++
}
This code will increase 'Value1' by 1 every 100ms whilst increasing 'Value2' by 1 every second.
Much like intervals, you can also stop timers once you are finished with them using:
Code:
stoptimer("TimerName") #Stops the timer with the name "TimerName"
Function timers
An extension I've added to the server is function timers. They are very similar to timers in Lua, in the sense that you set a repeat time, number of times to repeat, a unique name and the function to repeat.
RepeatTime controls how often to run the given function. Loops sets how many times to loop through the timer until stopping, 0 will mean it loops forever until removed. The "timername" is just a unique name you give the timer to identify it. The 'type' parts are the types given in the E2 helper, such as n, s, v etc. Finally, the arguments are the arguments you want to pass to the function.
An example.
Code:
@name Function timer test
@inputs A B C
function midPoint(A, B) #Hint the mid point between the numbers A and B.
{
hint( toString( ( A + B / 2 ), 7 ) )
}
#After one second and only once, run the midPoint() function with arguments given by the inputs A and B.
timer(1000,1,"midpoint","midPoint(nn)",A, B)
function entity:checkID(ID) #Hint if the number given matches the entity's ID.
{
if(This:id() == ID)
{
hint("ID: "+ID+" matched.",7)
}
else
{
hint("ID did not match.",7)
}
}
#Every 5 seconds, repeated infinitely, run the checkID function on the owner with argument given by the input C.
timer(5000,0,"IDCheck","checkID(e:n)",owner(),C)
Note how to define when the function is an entity method, you put e:typetype... in the brackets. Also note that functions need to be given as strings, you can't just put the function name in. Further, note how the arguments are given. First the object you are applying it to (if there is one), then the arguments of the function in order, separated by commas.
To remove a function timer, you use:
Code:
removetimer("timername")
Useful for if you want to make a timer repeat infinitely until a certain condition is met.
Run on tick
This is a lot like the interval command, in fact, interval(10) is essentially the same as runOnTick(1). Basically what the command does is it executes the chip every server tick, thus on a 66 tick server (the default), the chip will execute 66 times per second.
As you can tell, executing this many times per second can be very ops intensive and for complicated things like holograms or applyForce, can cause significant server lag. Thus this command should only be used when it is absolutely essential.
An example:
Code:
@name Run On Tick Test
@inputs Button
@outputs Value1 Value2
runOnTick(1) #Tells the chip to execute every server tick.
if(tickClk()) #If the chip is executing because of runOnTick(1) then increase 'Value1' by 1.
{
Value1++
}
if(~Button & Button) #If the chip is executing because the 'Button' input changed, increase 'Value2' by 1.
{
Value2++
}
This code will increase Value1 in sync with the server's tick rate, whilst increasing 'Value2' only when the button is pressed.
Run on chat
This lets you execute your chip every time someone says something in the text chat, which allows you to monitor the chat and do something if someone says something specific. Note that it will execute no matter who spoke, not just when you speak. However, you can check to see if the chip executed because a specific player spoke.
For example:
Code:
@name Chat Test
runOnChat(1) #Execute the chip whenever someone speaks in the text chat.
if(chatClk(owner()) & owner():lastSaid():upper() == "COOKIES")
#If the chip executed because the owner spoke and if the last thing the owner said when made uppercase was "COOKIES", then display a hint saying 'Delicious!'.
{
hint("Delicious!",7)
}
Note the use of chatClk(entity), where entity is the player whose chat you wish to monitor. If you wish you can use just chatClk() to run code whenever anyone speaks rather than a specific player.
7. User Defined Functions and including
Only a fairly recent addition to E2, functions are a powerful way to program and allow you to create much more efficient chips that are easier to read and understand. A function is essentially a set of instructions that, when given variables to apply them to, will perform operations and can return an output that you can then use. All function names must start with a lower case letter.
Let's start with a simple example:
Code:
@name Cookies or get out
@inputs Input:string
@outputs Output:string
@trigger all
function string cookies(Input:string) #Define a function cookies(), which will output a string and takes a string input.
{
if(Input:upper() == "COOKIES") #If "COOKIES" was the input after making it all caps, then output the string "Delicious!".
{
return "Delicious!"
}
else #Otherwise, output "Cookies or get out."
{
return "Cookies or get out."
}
}
Output = cookies(Input) #Set our Output variable to the result of our function.
This chip will inspect your eating habits and inform you of the error in your cookie-less ways should you require it. In all seriousness, it takes whatever string you input, checks to see if it's "COOKIES" when made uppercase, and then outputs a string depending on whether it was or not.
It doesn't seem all that useful, but imagine if you wanted to perform an operation like this on many strings throughout your chip. If you didn't use functions, you'd have to type out this code every time, whereas with the function defined, you simply type cookies(String) and it's done.
Local variables:
Next thing to note about functions are local variables. These are variables that you set in the function, but are not saved once the function has been executed. This way the name is free to be used further on in the chip without conflicting.
Code:
@name Cookies or get out
@inputs Input:string
@outputs Output:string
@persist Milk:string
@trigger all
Milk = " Don't forget the milk!"
function string cookies(Input:string)
{
local Milk = "Good choice." #Inside the function, Milk is "Good choice.", outside the function, it is still " Don't forget the milk!".
if(Input:upper() == "COOKIES")
{
return "Delicious!"
}
else
{
return "Cookies or get out."
}
}
Output = cookies(Input)+Milk #Output will be either "Delicious! Don't forget the milk!" or "Cookies or get out. Don't forget the milk!".
This chip will output the result of the cookies function and add on " Don't forget the milk!", despite the fact the function sets Milk to be "Good choice.". This is because Milk is treated as a local variable in the function, so the change isn't saved outside the function.
Another side note regarding Lua is that local variables can be set to functions as well as data. This actually speeds up execution as accessing the local copy of the function is faster than accessing it from the global table. E2 however cannot do this, nor would it help.
Including another file
Expression 2 now supports including of multiple files anywhere in given chip's code. This allows you to write one central chip containing all your useful functions which you then include into any new chips you code.
An example of this:
Code:
@name FuncLibrary
function array findByClassToOwner(Class:string, Owner:entity)
{
local Find = array() #Array to store find results.
local Ret = array() #Array to return.
if(!Owner:isPlayer()) #Can't find props belonging to a non-player entity...
{
return Ret #Return a blank array.
}
if(!Class) #Can't find anything without a class to look for.
{
return Ret #Return a blank array.
}
if(findCanQuery()) #If we can use the find functions, do so, else we'll return a blank array.
{
findByClass(Class) #Find our class.
Find = findToArray() #Store the results in the Find array.
for(I = 1, Find:count()) #Iterate through the Find array.
{
if(Find[I,entity]:owner() == Owner) #If the current entity's owner matches the Owner we want, add it to the Ret array.
{
Ret:pushEntity(Find[I,entity]) #Adds the entity to the end of the Ret array.
}
}
}
return Ret #Return whatever we found.
}
This is one function I find useful, which lets you find a specific class of entity and return an array of entities of that class that belong to the given entity owner. Now if you want to use this on a chip you are writing, you can include the file it is in instead of copy-pasting it into the chip. You need to have saved the above chip to a file in order to be able to include it.
Code:
@name Include example
@inputs Class:string
@outputs AmountFound
if(first())
{
#On first execution, include the chip with file name "FuncLibrary.txt".
#include "FuncLibrary"
}
AmountFound = findByClassToOwner( Class, owner() ):count()
This will output how many entities of the given class, belonging to the chips owner, that are found on the map.
Note that the position of the #include directive in a file determines where the file you are including will be placed. Think of it as essentially copying and pasting in the included file exactly where you put #include.
8. Coding chips for multiple servers
Our server runs a modified version of an old Stargate Expression 2 extension that enables the use of many functions that help with Stargates. However, if you visit other servers or play in singleplayer, you may not have these functions available. You can code your chips to check for and account for this very easily, assuming an equivalent method is possible with the default Expression 2 functions.
Code:
@name If def example
@outputs Count
@persist Rings:array
#If there exists a function 'getAllRings()', then use it to get an array of all rings on the map.
#ifdef getAllRings()
Rings = getAllRings()
Count = Rings:count()
hint("Stargate extension present.",7)
#Otherwise, use the built in 'findByClass' function to do it, which is slower.
#else
findByClass("ring_base_*")
Rings = findToArray()
Count = Rings:count()
hint("Stargate extension not present.",7)
#End the function check statement.
#endif
Note here that like #include, #ifdef, #else and #endif are not comments. They're statements just like if( ){ }else{ }. Slightly confusing, but the editor will highlight them pink to differentiate them from the grey comments. Note you do not use { } brackets to contain an #ifdef statement, instead you have to end it with #endif.
Also, you cannot have more than one #ifdef statement at any one time, i.e
9. The File Extension and VON Saving and loading files
Expression 2 includes quite a powerful file saving and loading extension that allows you to store string data to a text file in your Garry's mod data folder. This allows you to keep persistent data so that a chip has access to it without needing to have it input or retrieved every time you spawn the chip and join a server. The only downsides to it are that you must send the file to the server first and there is a file size limit.
To create a file:
Code:
@name File creation
@inputs String:string
if(fileCanWrite())
{
fileWrite("test.txt", String) #Writes whatever string is being inputted into the chip to a text file called test.txt
}
else
{
hint("Cannot write to file at the moment, try again in a few seconds...",7)
}
Note the use of fileCanWrite() to ensure we can write a file, though generally unless you are writing multiple files in a short time you will always be able to.
Now, let's say we have a file that we want to load as a persist variable in our chip. To do this is a little more complicated than saving.
Code:
@name File loading
@persist LoadedFile:string
if(first()) #On first execution, tell the chip to execute on file load and to load the test.txt file.
{
runOnFile(1)
fileLoad("test.txt")
}
if(fileClk() & fileLoaded()) #Check to see if the file has loaded.
{
LoadedFile = fileRead() #Read the file and set LoadedFile to the string of the file's contents.
hint("File test.txt loaded.",7)
}
Here, fileClk() is called because of runOnFile(1) and fileLoaded() is called when a file is successfully loaded.
Vercas' Object Notation (vON)
So now you know how to save and load basic strings from a text file. However, this isn't really too useful, as most of the time a string is hardly something worth saving as you can just save it in the Expression 2 file itself. This is where vON comes in. vON allows you to encode almost any data type, including multi-dimensional tables and arrays, into one string which can then be written to a text file. Then when you want to load it from the text file, vON can decode the string it saved back into the original data type ready for Expression 2 to use.
@name vON test
@persist Table:table
if(first())
{
runOnFile(1)
Table[owner():name(),string] = owner():steamID() #Set a string entry in the table with the player's name as the key and their Steam ID as the value.
VON = vonEncode(Table) #Encode the table using vON.
fileWrite("steamid.txt", VON) #Write the encoded string to the file steamid.txt
Table:clear() #Clear all entries in the Table persist variable.
fileLoad("steamid.txt") #Load the steamid.txt file we just saved.
}
if(fileClk() & fileLoaded()) #Check to see if the file has loaded.
{
LoadedFile = fileRead() #Read the file and set LoadedFile to the string of the file's contents.
Table = vonDecodeTable(LoadedFile) #Decode the contents of the file using vON into the Table persist variable.
hint("File steamid.txt loaded and decoded.",7)
foreach(K,V:string=Table)
{
print(_HUD_PRINTCONSOLE, K+" = "+V)
}
}
This code saves a vON encoded table containing an entry indexed by your player name and containing your Steam ID into a file called steamid.txt. It then wipes the Table variable in memory and reloads it from the text file using vON. Finally, it prints the table to console. Check to see that the table is indeed encoded and decoded successfully.
A few ideas that could use this include saving a list of Steam IDs that you want to exclude from dupe protection, saving a list of vector locations or saving a log. See the Wiremod wiki for the full list of file extension functions and vON functions.
vON can also be applied in GLua (Garry's mod Lua). I use it a lot for storing data on the server.
10. Signals and Data Signals
When creating Expression 2 chips, sometimes there is no way to avoid needing multiple chips to accomplish a task. This however presents a problem. How do you send data between chips and have them communicate? One way is to create wirelinks on each chip and then have lots of inputs and outputs that they manipulate on each other but this is messy and impractical. This is where the signal and data signal extensions are very useful.
Simple execution from a signal
Say you have a chip that performs a certain operation. When it is complete, you want to inform one or multiple other chips that it is complete. To do this we use signals.
Sender chip:
Code:
@name Signal Sender
@persist Time
interval(1000)
if(clk())
{
Time++
}
if(Time == 60)
{
signalSend("minute",0) #Send a signal to all chips belonging to the owner only.
Time = 0
}
Receiver chip:
Code:
@name Signal Receiver
@persist Count
if(first())
{
runOnSignal("minute",0,1) #Execute the chip when it receives the "minute" signal from a chip belonging the owner only.
}
if(signalClk("minute")) #If the chip is executing because of the minute signal, then add one to Count.
{
Count++
}
The sender chip is counting seconds, once it reaches 60 it sends a signal with the name "minute" to all chips belonging to the owner. The receiver chip waits for this signal, then increases its Count variable by 1 when it receives it, thus counting minutes.
0 will only run if the signal came from one of the owner's chips.
1 will run if it came from the owner's chips or another player's chip.
2 will run if it came from another player's chip only.
The boolean at the end of runOnSignal determines whether to run or not. So if you had previously told the chip to run then you wanted it to stop running on the given signal, setting Boolean to 0 would tell it to no longer run when it receives that signal.
See the Wiremod wiki for the full list of functions.
Data signals
Data signals are a way of doing more than just causing an execution. They allow you to send variables to another chip, meaning you can send a chip an entity, a table, an array, a vector or any other data type. Much like signals they have a scope, but they also require a group to be set in addition to the scope.
Sender chip:
Code:
@name Data signal sender
@persist Prop:entity
Prop = entity():isConstrainedTo() #Get the entity the chip is constrained to.
dsSend("prop", "proplist", Prop) #Send this entity as the data signal "prop" to the group "proplist".
Receiver chip:
Code:
@name Data signal receiver
@persist Props:table I
if(first())
{
I = 0
dsJoinGroup("proplist") #Join the "proplist" group.
dsSetScope(0)
}
if(dsClk("prop")) #Run when executing because of the "prop" data signal.
{
I++
Props[I,entity] = dsGetEntity() #Get the entity sent by the data signal.
}
Note the syntax:
Code:
dsJoinGroup("groupname") #Joins the "groupname" group.
dsSetScope(Scope) #See below.
dsClick("signalname") #Called when the chip executes because of the data signal called "signalname".
dsSend("signalname", "groupname", Data) #Sends a data signal (containing the Data variable) called "signalname" to the "groupname" group.
dsGet*() #Used to get the data from the data signal. Examples are dsGetEntity(), dsGetTable(), dsGetVector() etc.
As with signals, the scope can be 0, 1 or 2:
0 will only run if the signal came from one of the owner's chips.
1 will run if it came from the owner's chips or a chip belonging to someone on the owner's prop protection buddy list.
2 will run if it came from any other player's chip.
You'll notice that it is possible for multiple player's E2 chips to send information to each other as long as they all join the same group and set their scope correctly. This can allow for some very interesting creations. You can also dynamically change the scope, join more than one group and leave a group at any time. See the Wiremod wiki for the full list of functions.
11. Holograms
Holograms are essentially props you can spawn in the game using Expression 2 code that are not affected by physics and cannot be touched by players. You can set their size in all three dimensions, change their colour or texture, move them around the world and change them based on inputs.
Using holograms requires an understanding of the three-dimensional Cartesian co-ordinate system, whose co-ordinates form vectors in ℝ3. In simpler terms, you need to understand a vector (X, Y, Z) defines a position that is X units along the X-axis, Y units along the Y-axis and Z units along the Z-axis. If you are having trouble getting your head around it, have a read of this: http://en.wikipedia.org/wiki/Three-dimensional_space
You also should bear in mind that positions are defined as world positions, i.e, (0,0,0) is generally the centre of a Spacebuild map. So if you want to place holograms around your chip you will need to get the chip's position then add on a vector which defines where you want the hologram to be in relation to the chip.
Creating holograms
In a way, creating and manipulating holograms follows the same ideas as creating and manipulating objects in EGP. Holograms are given an index, then you can set the model, position, size, colour and more using the hologram functions. Unlike EGP however, you simply create a hologram then choose its model. There are no predefined shape functions like there are for EGP, such as egpCircle() or egpBox().
Let's start with the basic syntax.
Code:
@name Hologram example
holoCreate(1) #Create a hologram with index 1.
holoModel(1, "hq_sphere") #Set the hologram with index 1's model to the "hq_sphere" model.
holoPos(1, entity():toWorld(vec(0,0,100))) #Set the position of the hologram to be 100 units above the E2 chip.
holoScale(1, vec(5,5,5)) #Scale the model 5 times larger in each direction.
holoColor(1, vec4(255,0,0,255)) #Set the hologram's colour to red.
This will make a red sphere above where you spawn the chip.
Manipulating holograms
Much like with EGP, it is imperative that you do not keep removing and recreating holograms as there is a limit to how many can be spawned at once. When you wish to remove a hologram, unless you are absolutely sure that you will never use it again, use the holoAlpha() function to hide it.
Code:
@name Hologram example
@inputs Button
if(first())
{
holoCreate(1) #Create a hologram with index 1.
holoModel(1, "hq_sphere") #Set the hologram with index 1's model to the "hq_sphere" model.
holoPos(1, entity():toWorld(vec(0,0,100))) #Set the position of the hologram to be 100 units above the E2 chip.
holoScale(1, vec(5,5,5)) #Scale the model 5 times larger in each direction.
holoColor(1, vec4(255,0,0,255)) #Set the hologram's colour to red.
}
if(~Button) #If the button caused the chip to execute.
{
if(Button) #If the button is on, then hide the hologram.
{
holoAlpha(1, 0)
}
else #otherwise if it's off, show the hologram.
{
holoAlpha(1, 255)
}
}
This code will spawn the same sphere as before but when you input a button, it will hide the sphere.
Advanced manipulations
Some more advanced ways to manipulate holograms are clipping and parenting.
Clipping
Clipping lets you essentially cut a hologram along one or more planes, which means you can have more complicated shapes using the basic hologram models.
Code:
@name Hologram example
@inputs Button
if(first())
{
holoCreate(1) #Create a hologram with index 1.
holoModel(1, "hq_sphere") #Set the hologram with index 1's model to the "hq_sphere" model.
holoPos(1, entity():toWorld(vec(0,0,100))) #Set the position of the hologram to be 100 units above the E2 chip.
holoScale(1, vec(5,5,5)) #Scale the model 5 times larger in each direction.
holoColor(1, vec4(255,0,0,255)) #Set the hologram's colour to red.
}
if(~Button) #If the button caused the chip to execute.
{
if(Button) #If the button is on, then clip the hologram.
{
holoClipEnabled(1,1) #Enable clipping on the hologram with index 1.
holoClip(1, vec(0,0,0), vec(1,0,0), 0) #Clip the hologram with the plane defined from the centre of it and along the X-axis.
}
else #otherwise if it's off, show the hologram.
{
holoClipEnabled(1,0) #Disable clipping for the hologram with index 1.
}
}
This code will clip the hologram through the centre to cut the sphere in half. Note that the sphere isn't hollow so you'll see right through the clipped part.
The index is as with all other holo functions. The position to clip from defines where to start the clipping. The direction defines a vector direction to clip along. The last argument, the 'GlobalVectors' number, defines whether the position and direction are local to the hologram, so vec(0,0,0) would be its centre and the direction vec(1,0,0) is the local X direction. If you set it to global, you would have to get the holo's world position to get its centre and then work out the X direction for it.
Parenting
Parenting allows you to attach a hologram to another hologram, an entity, or an attachment position of an entity. This means the hologram will move in sync with the entity it is parented to, as if you welded them together.
Code:
@name Hologram example
@inputs Button
if(first())
{
holoCreate(1) #Create a hologram with index 1.
holoModel(1, "hq_sphere") #Set the hologram with index 1's model to the "hq_sphere" model.
holoPos(1, entity():toWorld(vec(0,0,100))) #Set the position of the hologram to be 100 units above the E2 chip.
holoScale(1, vec(5,5,5)) #Scale the model 5 times larger in each direction.
}
You should find the sphere follows you when you press the button.
The entire list of all available hologram functions can be found on the Wiremod wiki.