Wire Expression2
From GMod Wiki
This wiki has been created so that everyone can contribute to the documentation, so please do. If what you are looking for isn't listed here, use this thread at the Wiremod forums.
Contents
|
Features
Syntax
The syntax in the Expression 2 will take some time to get used to, but will give you a lot of power over your expressions. Remember there is not just one way to code something, you can accomplish the same task in several ways.
In Expression 2 conditionals, numbers are considered false if they equal 0. Otherwise, they are considered true. Functions and methods which conceptually return "true" or "false" return 1 and 0 respectively.
Syntax Example Description # #This is a comment Anything written after "#" on the same line will be treated as a comment (it will be ignored when the chip runs) if () {} if (A) {B = C} If the value (the condition) between the parentheses is true, then run the statements between the braces. else {} else {A = B} Must be preceded by if () {} or elseif () {}. If the previous condition was false then run the statements between the braces. elseif () {} elseif (A) {B = C} Must be preceded by if () {} or elseif () {}. If the previous condition was false and the value between the parentheses is true, then run the statements between the braces. ( ? : ) D = (A ? B : C) If A is true then return B otherwise return C. Note: [A ?: B] = [A ? A : B] & if (A & B) {C = 1} Returns 1 if both A and B are true. | if (A | B) {C = 1} Returns 1 if A or B is true. ! if (!A) {B = 1} Must precede a value. Returns 1 if A is false (same as "A == 0"). ~ if (~Button & Button) {DO stuff} Must precede an input variable. Returns 1 if the current execution was caused by a change in the input variable. $ Opitch = Pitch + $Pitch * 3 Must precede an input/output/persistent variable which has a subtraction operator. Returns the current value of the variable minus the value of the variable at the end of the last execution. Note: Acceleration == $Velocity only when intervals are one second apart. Can also be used to check if a variable has changed.
-> ->Input Must precede an input. Returns 1 if the input is wired to something.
Variables
In Expression 2, all variables must start with a capital letter. For instance:
Syntax Description @persist variable This will not work, as the "variable" does not begin with a capital letter. @persist Variable This, however, will work, as "Variable" begins with a capital letter.
@trigger-directive
The trigger directive can selectively enable or disable inputs from triggering executions. Possible values are all/none, but also a list of inputs.
@trigger all # old behaviour, inputs always trigger executions @trigger none # will never trigger from inputs, only timers, etc @trigger Time Button # will only trigger if Time or Button has changed
@model-directive
The model directive can be used to set the model of your expression chip.
@model *model path*
Loops
E2 features one type of loop: while loops. These allow instructions to be repeated many times in one execution, rather than relying on multiple executions to perform repeat tasks. Be aware that loops that perform too many instructions during an execution will exceed the E2's op quota and cause it to stop running (see "Performance" below).
Syntax Example Description while () {} while (A) {B++} Any instructions between the braces will repeat, as long as the condition between the parentheses is true. If the condition is false, the instructions will be skipped and the E2 will continue from the end of the loop. Note that the condition is only checked at the very start of each loop. for () {} for (I = A, B[, C]) {} Adds a value C to a Variable over every iteration until it equals a value B. If a step C is not specified it will be set to one. Note that A and B are evaluated only once - if they are calculated from variables that the loop sets to new values, this will not change the number of iterations. foreach () {} foreach(K,V:type=Table) {} Loops over each element of the specified type in Table. Assigns the key to K and the value to V. Elements that are not of the specified types are skipped. Elements can be added, removed, or modified, however elements that are added will not be processed in the current loop. continue if (A) {continue} Can only be used within a while/for/foreach loop. This will immediately return to the start of the loop, skipping any following instructions. break if (A) {break} Can only be used within a while/for/foreach loop. This will immediately go to the end of the loop and exit it, skipping any following instructions.
Performance
Did some performance tests in Garry's Mod to see what it could churn out:
~3.000.000/s arithmetic operations (+-*/) on numbers, 2000 ops, 200 executions in 0.13s
~850.000/s arithmetic operations (+-*/) on vectors, 2000 ops, 100 executions in 0.23s
Although E2 can do a lot, it has quotas to prevent servers from lagging. If the amount of ops used in a tick exceeds the tickquota, then the expression shuts down. Every tick, the ops used minus the softquota is added to a counter, if that counter exceeds the hardquota, then the expression shuts down. If your expression is shutting down, then it is recommended you learn better coding practices, such as storing commonly used values in a variable.
Editor Shortcut Keys
Shortcut Description Ctrl-Space Validate (and move cursor to error) Ctrl-S Save Ctrl-Q Close Ctrl-Z Undo Ctrl-Y Redo Ctrl-X Cut Ctrl-C Copy Ctrl-V Paste Ctrl-A Select all Ctrl-I / Tab Indent Ctrl-O / Shift-Tab Outdent Ctrl-K Comment the selected block Ctrl-Shift-K Uncomment the selected block Ctrl-F Find Ctrl-H Replace Ctrl-Up Scroll up Ctrl-Down Scroll down Ctrl-Left Jump one word left Ctrl-Right Jump one word right Ctrl-Home Go to first line Ctrl-End Go to last line
Tutorials
If you make a guide related to E2, please feel free to add it to this list!
- UltimateWire's YouTube channel
- Revan's Expression Gate 2 Guide - The Basics
- In-depth guide by Matte
- Expression 2 Guide
- Expression 2 Examples
- E2 And Plugs with Buttons
Console Commands
Command Description wire_expression2_model <model> Manually changes the expression's model. wire_expression2_reload Reloads all E2 extensions, useful for debugging your own extensions. Keep in mind that client-side files will be taken from gmod's cache in multi-player mode. wire_expression2_debug 0/1 Toggles debug mode, which shows info that might be useful for the developers. You need to do "wire_expression2_reload" after changing for this to have any effect.
Datatypes
Expression2 uses several datatypes and to keep the wiki at a reasonable size we use a shorthand for those datatypes, here is a list of all the shorthands used and the datatype they represent.
Shorthand Datatype
Number
/
/
2D / 3D / 4D Vector
Angle
String
Entity
Array
Table
Ranger Data
Bone
/
/
2x2 / 3x3 / 4x4 Matrix
Wirelink
Complex number
Quaternion
Number
Description
Numbers, lots of them...
Commands
String
Description
String support allows you to manipulate text with E2. Text screens now have an input for strings.
Related Examples
Commands
Create a string by wrapping the text in quotation marks, for example; "text goes here". Equal (==) and Not equal (!=) operators are available, as is concatenation (+), for joining strings and numbers in any order. Concatenation returns a string. The first character of a string has the index 1. Negative indices are counted from the end of the string, with the last character being -1. Positive indices will be capped to the string's length.
Function Returns Description S[N]
Returns Nth letter of the string, formatted as a string. Read-only. S:index(N)
Returns Nth letter of the string, formatted as a string. S:length()
Returns the length of the string. S:upper()
All characters are made uppercase S:lower()
All characters are made lowercase S:sub(N)
Returns a substring, starting at the number argument and ending at the end of the string S:sub(N,N)
Returns a substring, starting at the first number argument and ending at the second S:left(N)
Returns N amount of characters starting from the leftmost character S:right(N)
Returns N amount of characters starting from the rightmost character S:find(S)
Returns the 1st occurrence of the string S, returns 0 if not found S:find(S, N)
Returns the 1st occurrence of the string S starting at N and going to the end of the string, returns 0 if not found S:findRE(S)
Returns the 1st occurrence of the string S using REGEX functions, returns 0 if not found S:findRE(S, N)
Returns the 1st occurrence of the string S starting at N and going to the end of the string using REGEX functions, returns 0 if not found S:explode(S)
Splits the string into an array, along the boundaries formed by the string S. See also String.Explode S:repeat(N)
Repeats the input string N times S:trim()
Trims away spaces at the beginning and end of a string S:trimLeft()
Trims away opening spaces on the string S:trimRight()
Trims away spaces at the end of a string S:replace(S,S)
Finds and replaces every occurrence of the first argument with the second argument S:replaceRE(S,S)
Finds and replaces every occurrence of the first argument using REGEX with the second argument S:reverse()
Returns a reversed version of S S:toNumber()
Parses a number from a string. S:toNumber(N)
Parses a number from a string. The argument given is the base. I.e. toNumber(16) will parse hex. toString(N)
Formats a number as a string. (Numbers may be concatenated into a string without using this function) toString(N,N)
Formats a number as a string, using argument 2 as the base. i.e. using 16 for base would convert the number to hex. toChar(N)
Returns a one-character string from its ASCII code, where 32 ≤ argument 1 ≤ 255. An empty string is returned for numbers outside that range. toByte(S)
Returns the ASCII code of the 1st character in the string toByte(S,N)
Returns the ASCII code of the Nth character in the string format(S,...)
Formats a values exactly like Lua's string.format. Any number and type of parameter can be passed through the "...". Prints errors to the chat area. S:match(S2)
runs string.match(S, S2) and returns the sub-captures as an array. S:match(S2,N)
runs string.match(S, S2, N) and returns the sub-captures as an array. S:matchFirst(S2)
runs string.match(S, S2) and returns the first match or an empty string if the match failed. S:matchFirst(S2,N)
runs string.match(S, S2, N) and returns the first match or an empty string if the match failed.
Entity
Description
These entity functions allow you to get information from, and directly manipulate, entities in the game world (such as props). Entities can be found using many methods, from target finders, entity markers and even the expression itself with entity() from selfaware.
Since the expression collects the data directly from the entity, it is much faster to handle calculations from within the E2 than having a beacon-sensor send its information to the gate.
A valid entity will return true in an if-statement. This is helpful for preventing LUA errors resulting from using entity commands on entities which have been destroyed.
Related Examples
Commands
The only operators available for entities are equal and not equal. In addition, if(Entity) will return true only if there is a valid entity.
- 1) This is not the stored amount, no known weapon has a secondary clip, the AR2 and smg only have a storage, not a clip
- 2) For most valid entities, E:
E:toLocal(E:pos()+E:forward()) == vec(1, 0, 0)
E:toLocal(E:pos()+E:right()) == vec(0,-1, 0)
E:toLocal(E:pos()+E:up()) == vec(0, 0, 1)
- Some entities (vehicles for instance) have differing axes.
Attachment documentation at http://www.wiremod.com/forum/wiremod-tutorials/14813-e2-entity-attachment-documentation.html
Vector
Description
Vectors are now properly implemented in the Expression 2, which means that they are as easy to work with as numbers. For those that know what vectors are, and how to use them, this is a great tool for creating many things.
2D and 4D vectors are also supported by E2. These include all the standard functions of 3D vectors listed here. If you're doing 2D vector operations, you can now do things much more efficiently. 4D vectors work in conjunction with matrices, and can be used as homogeneous representations of 3D vectors.
Operational functions can be used between numbers and vectors, e.g. N*V. Note that operations cannot be performed between two vectors of different size, for example multiplication between a 2D and a 3D vector.
Related Examples
2D Vector Commands
Functions specific to 2D vectors
3D Vector Commands
Functions specific to 3D vectors
4D Vector Commands
Functions specific to 4D vectors. From a mathematics standpoint these are treated as 4D Cartesian vectors, where the 4th component is referred to as "w".
Common Vector Commands
Functions that apply to 2D and 3D vectors. They are written here in terms of 3D vectors, but apply to 2D and 4D vectors in the same way, also returning 2D or 4D vectors where applicable.
Matrix
Developed by: Jimlad
Description
2x2, 3x3 and 4x4 matrices are now supported in Expression 2. These are for more advanced manipulations involving vectors and numbers. As with vectors, for those with the relevant knowledge these can be very useful tools.
Basic operations supported:
- Matrix addition and subtraction
- Multiplication by scalars, vectors and matrices
- Division by a scalar
- Exponentiation (only integers between -1 and 2)
- Delta of a matrix (returns a matrix)
NOTES:
Similarly to vectors, 3x3 matrix commands are referred to using "matrix", whereas 2x2 and 4x4 matrix commands use "matrix2" and "matrix4"
The "set" and "swap" functions are like the 3D vector "set" functions; they do not affect the original matrix.
Remember that operations will only work on vectors/matrices of a similar size. You cannot, for example, multiply a 3x3 matrix by a 2D vector. Also, all vectors are treated as column vectors for the purposes of matrices, so M*V will return a vector but V*M is undefined.
2x2 Matrix Commands
Functions specific to 2x2 matrices
Function Returns Description identity2()
Creates a 2x2 identity matrix matrix2()
Creates a 2x2 zero matrix matrix2(N,N,N,N)
Creates a matrix with values in order (i.j) of: (1,1), (1,2), (2,1), (2,2) matrix2(V2,V2)
Creates a matrix with vectors by columns matrix2(M)
Converts a 3x3 matrix into a 2x2 matrix - all (i,3) and (3,j) are omitted matrix2(M4)
Converts a 4x4 matrix into a 2x2 matrix - all (i,3), (i,4), (3,j) and (4,j) are omitted M2:swapRows()
Swaps rows M2:swapColumns()
Swaps columns M2:setRow(N,N,N)
Sets the values of a row. The first argument given specifies the row(j), the following arguments are the values 1j, 2j M2:setRow(N,V2)
Sets the values of a row. The first argument given specifies the row, the vector contains the values to set M2:setColumn(N,N,N)
Sets the values of a column. The first argument given specifies the column(i), the following arguments are the values i1, i2 M2:setColumn(N,V2)
Sets the values of a column. The first argument given specifies the column, the vector contains the values to set 2x2 Matrix Commands
Functions specific to 2x2 matrices
3x3 Matrix Commands
Functions specific to 3x3 matrices
* If you want to create a rotation matrix about the axes (1,0,0), (0,1,0) or (0,0,1), either use the V:rotate function, or construct a standard rotation matrix.
4x4 Matrix Commands
Functions specific to 4x4 matrices
Common Matrix Commands
Functions that apply to 2x2, 3x3 and 4x4 matrices. They are written here in terms of 3x3 matrices, but apply to 2x2's and 4x4's in the same way.
Operations will only return vectors/matrices of similar sizes. For example, the row() function on a 2x2 matrix will return a 2D vector
NOTE: To get the inverse of a matrix, simply raise the matrix to the power of -1. Use this sparingly as it can be computationally expensive! Remember that if your matrix is orthogonal (e.g. rotation matrices), the inverse is equal to the transpose, so use the transpose instead if you can. Inverse is not available for 4x4 matrices. Instead, see usage of the inverseA(M4) function.
Angle
Description
Like 3 different directions can be expressed as a Vector, the angles of Pitch, Yaw and Roll can be expressed as an angle Vector. This in the least has the advantage that when performing functions which use angles, such as vector rotation or creating vectors from angles, you don't have to write the Pitch, Yaw and Roll components, only the Angle.
Commands
Table
Description
Tables are a way to create dynamic variables, store large numbers of data points and so on. It may be thought of as a list of data, where each bit of data is addressed with an index string. This is a string which is unique to each element of a datatype (a number element and a vector element may have identical indices without problems, but two number elements cannot). Tables can contain any datatype except table and array.
Assigning one table variable to equal another will make them both refer to the same table. If you want to make a new copy of a table which will thereafter be set and retrieved from independently of the original table, you must use clone().
Related Examples
Commands
In the interest of brevity, some commands which have many variants are shown as a pattern. <type> may be substituted with the capitalized name of any supported datatype, and * is the corresponding datatype symbol. For instance, R:push<type>(*) can mean R:pushNumber(N), or R:pushString(S).
Array
Thanks to: Erkle
Description
Same as table, but with much less memory footprint and is numerically indexed instead. It is similar to E1's packet support. Arrays can contain any datatype except table and array.
The index 0 and even negative and non-integer indices can be used, but to get the most out of the array functions it is advisable to start at index 1 and not to leave any gaps.
If you don't follow these guidelines, push/pop/count might misbehave.
An array automatically deletes elements that you fill with 0/""/noentity()/nobone()/noranger() or any other zero element.
Related Examples
Commands
In the interest of brevity, some commands which have many variants are shown as a pattern. <type> may be substituted with the capitalized name of any supported datatype, and * is the corresponding datatype symbol. For instance, R:push<type>(*) can mean R:pushNumber(N), or R:pushString(S).
Bone
Developed by: TomyLobo
Description
This extension gives E2 support for bone entities. A bone can be any part of any ragdoll (head, left arm, right leg, etc).
You can get a bone's position, orientation, velocity, etc, much like with regular props (although some things are missing).Array and table functions for bones are also provided.
Related Examples
Commands
Wirelink
Description
Wirelinks are an alternative to normal wires that offer a number of advantages. Any number of inputs or outputs on a component can be manipulated with one Wirelink, and you can also use it to retrieve the entity of a wirelinked component. Since all Wirelinks are capable of two-way communication, wirelinks are not clear-cut inputs or outputs. As such, to avoid ambiguity wirelinks which the expression should be able to manipulate are always declared in the @inputs of the expression. To connect this input to another component, you must use the Wirelink tool on the component to create a new output on it of the type Wirelink, then wire the input to the output as normal.
Related Examples
Commands
Equal and Not Equal operators are available. XWL here means the Wirelink input.
For Wired Graphics Processor Commands, see this wiki page.
Function Returns Description XWL:isHiSpeed()
Returns true if the linked component is high-speed capable. XWL:entity()
Returns the entity of the linked component. XWL:hasInput(S)
Returns true if the linked component has an input of the specified name. XWL:hasOutput(S)
Returns true if the linked component has an output of the specified name. XWL[S,<type>] <type> Retrieves the component's output of the specified name. XWL[S,<type>]=X Sets the component's input of the specified name equal to X. XWL:setNumber(S,N)Deprecated. Use XWL[S,number]=X instead. XWL:number(S)
Deprecated. Use XWL[S,number] instead. XWL:setVector(S,V)Deprecated. Use XWL[S,vector]=X instead. XWL:vector(S)
Deprecated. Use XWL[S,vector] instead. XWL:setString(S,S)Deprecated. Use XWL[S,string]=X instead. XWL:string(S)
Deprecated. Use XWL[S,string] instead. XWL:setXyz(V) Sets the X/Y/Z to the corresponding values in the vector. XWL:xyz()
Retrieves the X/Y/Z as the corresponding values in the vector. XWL:setEntity(S,E)Deprecated. Use XWL[S,entity]=X instead. XWL:entity(S)
Deprecated. Use XWL[S,entity] instead. XWL:writeCell(N,N)
Deprecated. Use XWL[N]=X instead. XWL:readCell(N)
Deprecated. Use XWL[N] instead. XWL[N]
Returns contents of the specified memory cell. XWL[N]=X Writes the value to the memory cell specified by the index. XWL:writeString(S,N,N) A helper function for using the Wired Console Screen. The string will be written to the screen in white text on black background. The number arguments specify the starting position - X/Horizontal (0-29 recommended) and Y/vertical (0-17). XWL:writeString(S,N,N,N) As above, with an extra argument for the text colour. This is in the form of a 3-digit RGB code. 0 is black, while 999 is white, 900 is pure red and so on. XWL:writeString(S,N,N,N,N) As above, with an extra argument for background colour. 3-digit RGB again. XWL:writeString(S,N,N,N,N,N) As above, with an extra argument for flashing text. 0 or 1 is recommended. XWL:writeString(N,S)
Writes a null-terminated string to the given address. Returns the next free address or 0 on failure. XWL:readString(N)
Reads a null-terminated string from the given address. Returns an empty string on failure. XWL:writeArray(N,R)
Writes an array's elements into a piece of memory. Strings and sub-tables (angles, vectors, matrices) are written as pointers to the actual data. Strings are written null-terminated. XWL:inputs()
Returns an array of all the inputs that XWL has without their types. Returns an empty array if it has none XWL:outputs()
Returns an array of all the outputs that XWL has without their types. Returns an empty array if it has none XWL:inputType(S)
Returns the type of input that S is in lowercase. ( "NORMAL" is changed to "number" ) XWL:outputType(S)
Returns the type of output that S is in lowercase. ( "NORMAL" is changed to "number" )
Complex
Developed by: Fizyk
Description
Complex numbers are an extension of real numbers to include roots of negative numbers as well.
They support all basic operations, like addition, subtraction, multiplication, division and raising to a power. Also operations with real numbers are supported, like N+C etc.
There are comparison operators == and !=, no < and > though, as those are undefined for complex numbers.Related Examples
Commands
Quaternion
Developed by: Fizyk
Description
Quaternions are an extension of complex numbers. Instead of a+bi, they are of form a+bi+cj+dk, where a, b, c, d are real numbers, and i, j, k are imaginary units. The imaginary units can be used as a basis in a 3D space, allowing quaternions to represent rotations.
Like on real and complex numbers, on quaternions you can perform addition, subtraction, multiplication and division. Operations that take a quaternion and a real/complex number are also supported (N+Q, Q*C, etc.). Beware: quaternion multiplication isn't commutative!
Note: Because multiplication isn't commutative with quaternions, there are two ways of dividing them. Q1/Q2 is the same as Q1*inv(Q2), the second way is inv(Q2)*Q1.
The extension also supports multiplying quaternions by vectors for the purpose of rotations. If you want to rotate vector V using quaternion Q, use this code:
V2 = vec(Q*V*inv(Q))A short guide on quaternions can be found here: [1]
Related Examples
Commands
Basic extensions
Core
Description
This is where things directly related to E2 are kept
Commands
Self-Aware
Description
With entity() you can use Entity-Support to get all the data from the expression-entity. With concmd() you can execute console commands.
Also, the chip has the ability to force itself. Forces aren't dispersed over a certain amount of time, all forces applied to an object within a tick are added up and then applied to the object. Force commands are best used with runOnTick(N) because you won't end up applying more than 1 force per tick and it is easier to do things like defy gravity.
Related Examples
Commands
Function Returns Description entity()
Gets the entity of the expression concmd(S)
Takes a string and executes it in console. Returns 1 if it succeeded and 0 if it failed.
The client must enable this in the console with "wire_expression2_concmd 1". "wire_expression2_concmd_whitelist" allows you to choose which commands can be used.[2]applyForce(V) Applies force according to the vector given (Forces independently on each axis unlike a vector thruster) applyOffsetForce(V,V) Applies force to the expression according to the first vector from the location of the second selfDestruct() Removes the expression selfDestructAll() Removes the expression and all constrained props changed(*) Checks if the value or variable was changed. Accepts any type except table and array.
It detects changes by checking whether it was called with a different parameter at the same point in the last execution.
Multiple calls to changed() in the _same_ execution are independent of each other.select(N,*,...) * Returns the Nth value given after the index, *'s zero element otherwise. If you mix types, the behaviour is undefined.
Debug
Description
Contains various functions for displaying values to the user. print() and hint() allow you to display strings quickly on your screen.
Keep in mind that chat messages can be faked using E:printColorDriver(...) and E:printColorDriver(R). The game will display a warning message when first used on someone by a specific chip.
Related Examples
Commands
Function Returns Description print(S) Posts S to the chat area. print(...) Prints all arguments to the chat area, seperated by a tab. Automatically does toString for you (Can print arrays but not tables). Works just like lua's print). E:printDriver(S)
Posts a string to the chat of E's driver. Returns 1 if the text was printed, 0 if not. hint(S,N) Displays a hint popup with message S for N seconds (N being clamped between 0.7 and 7). E:hintDriver(S,N)
Displays a hint popup to the driver of vehicle E, with message S for N seconds (N being clamped between 0.7 and 7). Same return value as printDriver. print(N,S) Same as print(S), but can make the text show up in different places. N can be one of the following: _HUD_PRINTCENTER, _HUD_PRINTCONSOLE, _HUD_PRINTNOTIFY, _HUD_PRINTTALK. E:printDriver(N,S)
Same as EE:printDriver(S), but can make the text show up in different places. N can be one of the following: _HUD_PRINTCENTER, _HUD_PRINTCONSOLE, _HUD_PRINTNOTIFY, _HUD_PRINTTALK. printTable(T) Prints a table like the lua function PrintTable does, except to the chat area. printTable(R) Prints an array like the lua function PrintTable does, except to the chat area. printColor(...) Works like chat.AddText(...). Parameters can be any amount and combination of numbers, strings, player entities, color vectors (both 3D and 4D). printColor(R) Like printColor(...), except taking an array containing all the parameters. E:printColorDriver(...) Like printColor but prints to the driver of a specified vehicle. E:printColorDriver(R) Like printColorDriver but takes an array containing all the parameters.
Timer
Description
Timer functions are a way to trigger the expression to be run at a given time. Most interesting is the interval(N) function, that lets the expression be run continuously without needing triggering from inputs.
Commands
Function Returns Description runOnTick(N) If set to 1, the expression will execute once every game tick. See Admin#Tick and [[3]] For more information on how often this is run. tickClk()
Returns 1 if the current execution was caused by "runOnTick" curtime()
Returns the current game time since server-start in seconds* realtime()
Returns the current real time since server-start in seconds* interval(N) Causes the expression to execute every N milliseconds (minimum delay is 10 milliseconds) timer(S,N) Sets a one-time timer with entered name and delay in milliseconds stoptimer(S) Stops a timer, can stop interval with stoptimer("interval") clk()
Returns 1 if the current execution was caused by the interval clk(S)
Returns 1 if the current execution was caused by the inserted name
* Both curtime() and realtime() are given to 3 decimal places. Server lag will cause curtime() to slow down, but not realtime().
Unit Conversion
Description
All conversions are precise so it is recommended to round the result if it is going to be displayed (round()).
Related Examples
Commands
Units
Length Description mm millimeters cm centimeters dm decimeters m meters km kilometers in inches (default) ft feet yd yards mi miles nmi nautical miles
Speed Description m/s meters per second km/h kilometers per hour in/s inches per second (default) mi/h miles per hour mph miles per hour (more commonly used than mi/h) knots knots (correct term for nautical miles per hour) mach mach (times speed of sound) mm/x millimeters per time unit cm/x centimeters per time unit dm/x decimeters per time unit m/x meters per time unit km/x kilometers per time unit in/x inches per time unit ft/x feet per time unit yd/x yards per time unit mi/x miles per time unit nmi/x nautical miles per time unit substitute x for s (per second), m (per minute) or h (per hour)
Weight Description g grams kg kilograms (default) t tons oz ounces lb pounds
Server Information
Developed by: Beer
Description
The following functions allow you to get various information about the server, such as the current map name, gamemode, etc.
Commands
-
Tip:To get a list of all possible parameters for maxOfType(), open the console and type "find sbox_max". If you need "sbox_maxragdolls", you can simply pass "ragdolls" in the function.
Constraint
Developed by: ZeikJT
Description
The following functions get information about entities based on constraints
Commands
Constraint Types AdvBallsocket Axis Ballsocket Elastic Hydraulic Keepupright Motor Muscle NoCollide Pulley Rope Slider Weld Winch
Chat
Developed by: ZeikJT & Gwahir
Description
The following functions are for reading the chat log. This is similar to the text receiver.
Related Examples
Commands
Color
Developed by: Jimlad
Description
These commands allow E2 to find the color of an entity and change it. Changing color only works on entities you own.
Uses RGBA (Red, Green, Blue, Alpha) values, although when only RGB is specified, alpha will not be changed.
Note that color values have a range of 0 - 255, where (0,0,0,255) is black, and (255,255,255,255) is white.
Alpha is equivalent to opacity, where 0 is completely transparent and 255 is completely opaque.
Commands
Function Returns Description E:getColor()
Returns the color of an entity as a vector (R,G,B) E:getColor4()
Returns the color of an entity as a 4D vector (R,G,B,A) E:getAlpha()
Returns the alpha of an entity E:getMaterial()
Returns the material of an entity E:getSkin()
Gets E's current skin number. E:getSkinCount()
Gets E's number of skins. E:setColor(N,N,N) Changes the RGB color of an entity (leaves alpha alone) E:setColor(N,N,N,N) Changes the RGBA color of an entity E:setColor(V) Changes the RGB color of an entity (leaves alpha alone), using a vector with values (R,G,B) E:setColor(V,N) Changes the RGBA color of an entity, using a vector with values (R,G,B). The additional argument sets alpha E:setColor(V4) Changes the RGBA color of an entity, using a 4D vector with values (R,G,B,A) E:setAlpha(N) Changes the alpha of an entity E:setMaterial(S) Sets the material of an entity. E:setMaterial("") to reset material E:setSkin(N) Sets E's skin number. hsv2rgb(V)
Converts V from the HSV color space to the RGB color space rgb2hsv(V)
Converts V from the RGB color space to the HSV color space rgb2digi(V,N)
Converts an RGB vector V to a number in digital screen format. N Specifies a mode, either 0, 2 or 3, corresponding to Digital Screen color modes. rgb2digi(N,N2,N3,N4)
Converts the RGB color (N,N2,N3) to a number in digital screen format. N4 Specifies a mode, either 0, 2 or 3, corresponding to Digital Screen color modes.
Advanced extensions
Entity Discovery
Developed by: Gwahir, TomyLobo
Description
Use these to find and filter entities. The basic find functions will return how many entities were found but the actual entities are stored on the chip until they are accessed using find(), findResult(N), or findClosest(V)
There is a white list and a black list as well as functions for on the spot filtering and sorting White and black lists are always in effect and will be used automatically when you request a new list of entities. Control of the lists is achieved through the find[Exclude, Allow, Include, Disallow][Player, Prop, Model, Class] functions Exclude/Allow add/remove items from the black list while Include/Disallow do the same for the white list If the same object is covered by both the white list and the black list, the black list takes priority
In the case of names, classes and models, partial strings are acceptable.
Discovering entities is not cheap so suggested usage is to find what you're looking for an hold onto it in order to limit the number of queries you run. To prevent overuse of these features, two console variables have been included, wire_exp2_entFindRate and wire_exp2_playerFindRate. These are delays that control how often you can perform find queries, the ent variable is per chip, the player variable is for all chip owned by a specific player
Related Examples
Commands
Function Returns Description findUpdateRate()
Returns the minimum delay between entity find events on a chip findPlayerUpdateRate()
Returns the minimum delay between entity find events per player findCanQuery()
Returns 1 if find functions can be used, 0 otherwise. findInSphere(V,N)
Finds entities in a sphere around V with a radius of N, returns the number found after filtering findInCone(V,V,N,N)
Like findInSphere but with a [Spherical cone], arguments are for position, direction, length, and degrees (works now) findInBox(V,V)
Like findInSphere but with a globally aligned box, the arguments are the diagonal corners of the box findByName(S)
Find all entities with the given name findByModel(S)
Find all entities with the given model findByClass(S)
Find all entities with the given class findPlayerByName(S)
Returns the player with the given name, this is an exception to the rule findExcludeEntities(R) Exclude all entities from R from future finds findExcludeEntity(E) Exclude E from future finds findExcludePlayer(E) Exclude this player from future finds (put it on the entity blacklist) findExcludePlayer(S) Exclude this player from future finds (put it on the entity blacklist) findExcludePlayerProps(E) Exclude entities owned by this player from future finds findExcludePlayerProps(S) Exclude entities owned by this player from future finds findExcludeModel(S) Exclude entities with this model (or partial model name) from future finds findExcludeClass(S) Exclude entities with this class (or partial class name) from future finds findAllowEntities(R) Remove all entities from R from the blacklist findAllowEntity(E) Remove E from the blacklist findAllowPlayer(E) Remove this player from the entity blacklist findAllowPlayer(S) Remove this player from the entity blacklist findAllowPlayerProps(E) Remove entities owned by this player from the blacklist findAllowPlayerProps(S) Remove entities owned by this player from the blacklist findAllowModel(S) Remove entities with this model (or partial model name) from the blacklist findAllowClass(S) Remove entities with this class (or partial class name) from the blacklist findIncludeEntities(R) Include all entities from R in future finds, and remove others not in the whitelist findIncludeEntity(E) Include E in future finds, and remove others not in the whitelist findIncludePlayer(E) Include this player in future finds, and remove other entities not in the entity whitelist findIncludePlayer(S) Include this player in future finds, and remove other entities not in the entity whitelist findIncludePlayerProps(E) Include entities owned by this player from future finds, and remove others not in the whitelist findIncludePlayerProps(S) Include entities owned by this player from future finds, and remove others not in the whitelist findIncludeModel(S) Include entities with this model (or partial model name) in future finds, and remove others not in the whitelist findIncludeClass(S) Include entities with this class (or partial class name) in future finds, and remove others not in the whitelist findDisallowEntities(R) Remove all entities from R from the whitelist findDisallowEntity(E) Remove E from the whitelist findDisallowPlayer(E) Remove this player from the entity whitelist findDisallowPlayer(S) Remove this player from the entity whitelist findDisallowPlayerProps(E) Remove entities owned by this player from the whitelist findDisallowPlayerProps(S) Remove entities owned by this player from the whitelist findDisallowModel(S) Remove entities with this model (or partial model name) from the whitelist findDisallowClass(S) Remove entities with this class (or partial class name) from the whitelist findClearBlackList() Clear all entries from the entire blacklist findClearBlackEntityList() Clear all entries from the entity blacklist findClearBlackPlayerPropList() Clear all entries from the prop owner blacklist findClearBlackModelList() Clear all entries from the model blacklist findClearBlackClassList() Clear all entries from the class blacklist findClearWhiteList() Clear all entries from the entire whitelist findClearWhiteEntityList() Clear all entries from the player whitelist findClearWhitePlayerPropList() Clear all entries from the prop owner whitelist findClearWhiteModelList() Clear all entries from the model whitelist findClearWhiteClassList() Clear all entries from the class whitelist findResult(N)
Returns the indexed entity from the previous find event (valid parameters are 1 to the number of entities found) findClosest(V)
Returns the closest entity to the given point from the previous find event findToArray()
Formats the query as an array, R[Index,entity] to get an entity. find()
Equivalent to findResult(1) findSortByDistance(V)
Sorts the entities from the last find event, index 1 is the closest to point V, returns the number of entities in the list findClipToClass(S)
Filters the list of entities by removing all entities that are NOT of this class findClipFromClass(S)
Filters the list of entities by removing all entities that are of this class findClipToModel(S)
Filters the list of entities by removing all entities that do NOT have this model findClipFromModel(S)
Filters the list of entities by removing all entities that do have this model findClipToName(S)
Filters the list of entities by removing all entities that do NOT have this name findClipFromName(S)
Filters the list of entities by removing all entities that do have this name findClipToSphere(V,N)
Filters the list of entities by removing all entities NOT within the specified sphere (center, radius) findClipFromSphere(V,N)
Filters the list of entities by removing all entities within the specified sphere (center, radius) findClipToRegion(V,V2)
Filters the list of entities by removing all entities NOT on the positive side of the defined plane. (Plane origin, vector perpendicular to the plane) You can define any convex hull using this.
Global Variables
Developed by: Divran (Original idea by ZeikJT)
Description
Global variables are a way to exchange data between two expression chips without the need for any wiring at all.
All variables in a non-shared table will automatically be removed if you disconnect from the server. Remember that variables in a shared table will not automatically be removed, so don't spam too many of them.
Related Examples
Commands
Function Returns Description 'New' syntax The new syntax. Supports any type. Getting the gtable Get the gtable with which you use the regular table get and set syntax: "G[index,type]" gTable(S) GT Returns a non-shared gtable with the group S gTable(S,N) GT Returns a gtable with the group S. N determines whether or not it is shared. Remember that there are two tables: one which is shared and one which is not; values do not transition between the two. Removing Remove variables & clear tables GT:remove*(S) * Removes and returns the variable of the type * at the index S gRemoveAll*() - Removes all variables of the type * in your non-shared table. gRemoveAll*(S) - Removes all variables of the type * in your non-shared table in group S. gRemoveAll() - Resets the entire non-shared table (ie ALL your variables in every group) 'Old' syntax The old syntax. Only supports strings, numbers, vectors, angles and entities. Use the first three letters when specifying type. These functions are NOT recommended. Use the new syntax instead. Group control Change group & share or stop sharing your variables gSetGroup(S) - Sets the E2's current group. Does persist. gGetGroup() S Gets the E2's current group. gShare(N) - Sets wether or not you want to share the variables. (1/0) Remember that there are two tables for each group: one which is shared and one which is not; values do not transition between the two. gGetShare() N Returns 1/0 gResetGroup() - Resets the group back to "default". Getting and setting Save & load variables gSet*(S,*) - Sets a variable of the type * at index S in the current group. gGet*(S) * Gets a variable of the type * from index S in the current group. gSet*(N,*) - Exactly the same as "gSet*(N:toString(),*)" gGet*(N) - Exactly the same as "gGet*(N:toString())" Removing Remove variables & clear tables gDelete*(S) * Removes and returns the variable of the type * at the index S in the current group. gDelete*(N) * Exactly the same as gDelete*(N:toString()) gDeleteAll*() - Exactly the same as gRemoveAll*(S) (Except it removes in the group set by gSetGroup instead of using the group as an argument) (Remember that this function is only for compatibility)
Built-In Ranger
Developed by: ZeikJT
Description
The built-in ranger is based on Erkle's original ranger. There are however some new functionalities that can be found in the commands below. Keep in mind that if you want to apply an option you must set it before getting the ranger data. To make ranger settings (like filters, "ignore world", "hit water") persist, run rangerPersist(1).
This also introduces a new Variable type, the RD (defined as :ranger). It holds the data returned after a trace, you will need to use the trace data functions to retrieve useful data. These are to be used after you have done an actual trace.
I will add a simple example to showcase the syntax and functionality.
Related Examples
Commands
Sound Playback
Developed by: ZeikJT
Description
Allows Expression 2 to play sounds. NEW: Expression2 Now has a Sound Browser, Use it instead!
The Duration is in seconds. If the sound is meant to be looped, set the duration to zero. If a sound is not designed to be looped (i.e: actor talking), it won't loop. The path must contain slashes '/' and not backslashes '\'. The soundPlay functions can optionally play from an entity that you own.
Commands
NPC control
Developed by: Bobsymalone
Description
These functions allow you to control NPCs. You can create secondary AI systems responding to wire by telling NPCs how to feel about certain things, where to go, etc. You can also equip them with weapons.
Related Examples
Commands
Signals
Developed by: Gwahir, TomyLobo
Description
These functions allow you to remotely execute exp2 chips, provided that chip is set to receive the given signal
Scope
Signals are restricted to certain scopes (only you, anyone, only others) (0,1,2)
Simplified, true = anyone, false = only you.
Scopes are used to restrict both who can receive your signal and who's signal you can receive.
Scopes are always relative to the owner of the chip. So if player A sends to scope 1 and player B only receives from scope 0, he/she won't receive it, but player B will receive it with scopes 1 or 2
Group
Set the chip's group with signalSetGroup(S) before calling the related runOnSignal, sendSignal, or signalSetOnRemove function
The chip's signal group is always "default" at the start of every execution.
runOnSignal() will subscribe to the given signal within the current group, this applies to sent signals as well.
Any signal the chip receives will run the chip regardless of its current group (so long as it subscribed to the signal and group of the sent signal)
A chip will never run because of a signal it sent itself.Signals are issued 10ms after the first unissued signal was sent.
There can only ever be one unissued signal/group combination per receiver in each scope.Related Examples
Commands
Data Signals
Developed by: Divran
Description
This extension allows you to transmit data and execute E2s remotely.
Remember: When sending a table or array, it only sends the table reference. This means that if you then edit the table back on the first E2, the table will also be edited on the second E2. To fix this, if needed, use the clone() function before or after sending.
Scope
As mentioned above, you can set the scope of the E2 itself in order to choose which signals it should allow. If you set the scope of the E2 itself, the following will happen:
- 0: Only allow signals from E2s you own.
- 1: Allow signals from E2s you own and from people in your prop protection friends list.
- 2: Allow signals from anyone.
You can also choose which scope to send a signal to when you call the send functions. If you choose the scope while calling the function, the following will happen:
- 0: Only send to your E2s.
- 1: Send to your E2s and the people who have you in their prop protection friends list.
- 2: Send to everyone.
The default scope is 0.
Group
When I said "send to everyone" above, I didn't mean every single E2 on the map. It sends to everyone in a specific group. You can change the group of the E2 at any time, and you can specify which group to send a signal to. The E2 is not in a group by default, and you must join a group in order to receive any non-direct signals.
Signal Names
Signal names serve no other purpose than to identify the signal so that the recieving E2 can know what to do with the data.
Commands
Note that * can be replaced by any variable type.
GLON
Developed by: TomyLobo
Description
This extension allows you to serialize (=turn into a string) an array or table of values. Unsupported element types are:
- Bone
- some entity types (Vehicle, NPC, Weapon)
- ranger data if the ranger was pointed at one of the entity types mentioned previously.
Related Examples
Commands
Function Returns Description glonEncode(R)
Encodes R into a string, using GLON. glonEncode(T)
Encodes T into a string, using GLON. glonDecode(S)
Decodes S into an array, using GLON. glonDecodeTable(S)
Decodes S into a table, using GLON.
3D Holograms
Developed by: McLovin & ZeikJT
Description
Adds the ability to project 3D objects. These objects can't be interacted with like most props; the only way to manipulate them is to use these functions.
When using the holoCreate function, bear in mind that there is a delay associated with spawning holograms to avoid lagging servers. Avoid using holoCreate every execution. In general you should only ever use the holoCreate function once for each hologram in your code, for example by using the first() condition. Use the other functions like holoPos to update them thereafter.
Note that except for wire_holograms_display_owners, wire_holograms_block_client and wire_holograms_unblock_client all other console commands are useable by admins only!
Console Variables
Function Returns Description wire_holograms_display_owners Shows the owner of each hologram. wire_holograms_block_client Hide all holograms spawned by the specified player from the display_owners list. wire_holograms_unblock_client Un-hide/show all holograms spawned by the specified player on the display_owners list. wire_holograms_remove_all Removes all holograms on the map wire_holograms_block Input a name (or part of a name) to prevent a player from spawning holograms wire_holograms_unblock Input a name (or part of a name) to allow a player to spawn holograms again wire_holograms_block_id Input a SteamID to prevent a player from spawning holograms wire_holograms_unblock_id Input a SteamID to allow a player to spawn holograms again wire_holograms_max Defines the maximum number of hologams a player can have at once wire_holograms_size_max Defines the maximum size of holograms according to the holoScale function
Related Examples
World Orientation (by coder0xff)
Commands
List of holo models
List of high quality holo models File Functions
Developed by: IamMcLovin
Description
The file functions are used to write text to files, stream files from client to server, and edit files.
Warning: Double quotation marks (") are replaced with single quotation marks (') in uploaded files. This is not intended behavior. Files saved within E2 do not exhibit this problem until they are removed with fileRemove() and re-uploaded with fileLoad().
Files cannon contain a null byte (0x00). Binary files lacking a null byte can be loaded and parsed, but there are no functions to assist with that in E2.
Commands
Important: All the filenames must end in *.txt!
Files are loaded from the "garrysmod/data/e2files" folder.See Also
- Expression 2 Formatting
- Expression 2 Unofficial Addons
- Expression 2 Bugs
- Expression 2 Examples
- Expression 2 Wishlist
- Expression 2 Guide
- How to write custom extensions
- Wire Expression2:Differences to Expression1
- Expression 2 syntax higlighting for Notepad++
- Wiremod
Credits
I would like to extend thanks to all of the following people who have made contributions to Expression 2 in one way or another, making it into what it is today.
Shandolum, ZeikJT, Jimlad, Beer, Magos Mechanicus, Gwahir, chinoto, pl0x, Turck3, Ph3wl, Hunter234564, Fishface60, GUN, Bobsymalone, TomyLobo, Tolyzor, Jeremydeath, I am McLovin, Fizyk, Divran
And of course all you others out there who use it, provide constructive feedback or help others become familiar with it!
Thank you! // Syranide
P.S. I'm sorry if I forgot to mention someone!
