Wire Expression2

From BunglistBuild Gmod Wiki

Jump to: navigation, search

Contents

Syntax

The syntax in the Expression 2 has changed a lot from the previous Expression Gate, which will take some getting used to, but will give you a lot more power over your expressions. Remember there is not just one way to code something, you can accomplish the same task in several ways.

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 A is true then do the first operation.
if () {} else {} if (A) {B = C} else {B = D} If A is true then do the first operation otherwise do the second operation.
if () {} elseif () {} if (A) {B = C} elseif (E) {B = D} If A is true then do the first operation otherwise check E, if E is true then do the second operation.
( ? : ) D = (A ? B : C) If A is true then return B otherwise return C.
& if (A & B) {C = 1} Returns 1 if A and B are true.
| if (A | B) {C = 1} Returns 1 if A or B are true.
! if (!A) {B = 1} Returns 1 if A is not true (same as "A == 0").
~ if (~Button & Button) {DO stuff} Returns 1 if the input caused the execution.
$ Opitch = Pitch + ($Pitch * 3) Returns the amount of the change of a variable between intervals (its Delta Δ). (Works on defined variables of the type number, vector, and angle) Note: Acceleration == $Velocity only when intervals are one second apart.

@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

Difference from Expression Gate

Expression Gate 1 documentation
The documentation for Expression Gate 1 very much applies to Expression 2, the only major difference between the languages are if-statements, which you can see below. Except for that, Expression 2 is basically superior in every way, and the basics are exactly the same, it also has a proper code editor!

Firstly we have the lines for variables, which is similar to the Expression Gate, but not quite. The variables in the expression must be declared before you can use them in the expression, so before it would look like:

N@variable example
I@A
O@B
A==1 -> C=!C;
B=(C==1 ? 2 : 1)

and after:

@name variable example
@inputs A
@outputs B
@persist C
if (A==1) {C=!C}
B=(C==1 ? 2 : 1)

You may notice the extra line @persist, which is a line for all variables not defined in inputs or outputs that need to retain their value. Outputs automatically persist. The reason that persistent variables now have to be defined this way, is because there are different types of variables. In Expression Gate, there were only numbers and packets, but there are many other types in Expression 2, like strings, vectors and more and specifying persistent variables allows typos and similar mistakes to be caught by the compiler instead of being treated as zero.

Cases in which persisting is needed: When using delta ($), when using an unassigned variable, when using +=.

New Features

@name vector example
@inputs A:vector
@outputs B:vector
C = vec(0,0,0)
if(A>C) {
    B = A:normalized() * 4
} else {
    B = C + A
}

Performance

Did some performance tests in garrysmod 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

Editor Shortcut Keys

Ctrl-Space Validate (and move cursor to error)
Ctrl-S Save
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-F Find
Ctrl-Q Close
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

Extensions

Core

Description

...

Commands

Function Returns Description
first() N Returns 1 if the expressions was spawned or reset
duped() N Returns 1 if the expressions was duplicated
reset() Reset the expression itself as if it was just spawned, stops execution
exit() Stops the execution of any code after it

Number

Description

Numbers, lots of them...

Commands

Function Returns Description
N + N N Addition
N - N N Subtraction
N * N N Multiplication
N / N N Division
N ^ N N Exponentiation (N to the power of N)
N % N N Modulo, returns the Remainder after Argument 1 has been divided by Argument 2. Note "-1 % 3 = 2"
mod(N, N) N Modulo, returns the Remainder after Argument 1 has been divided by Argument 2. Note "mod(-1, 3) = -1"
sqrt(N) N Returns the Square Root of the Argument
cbrt(N) N Returns the Cube Root of the Argument
root(N, N) N Returns the Nth Root of the first Argument
e() N Returns Euler's Constant
exp(N) N Returns e to the power of the Argument (same as e()^N and it's shorter this way)
ln(N) N Returns the logarithm to base e of the Argument
log2(N) N Returns the logarithm to base 2 of the Argument
log10(N) N Returns the logarithm to base 10 of the Argument
log(N,N) N Returns the logarithm to base Argument 2 of Argument 1
abs(N) N Returns the Magnitude of the Argument
ceil(N) N Rounds the Argument up to the nearest Integer
ceil(N,N) N Rounds Argument 1 up to Argument 2's decimal precision
floor(N) N Rounds the Argument down to the nearest Integer
floor(N,N) N Rounds Argument 1 down to Argument 2's decimal precision
round(N) N Rounds the Argument to the nearest Integer
round(N,N) N Rounds Argument 1 to Argument 2's decimal precision
int(N) N Returns the Integer part of the Argument (same as floor)
frac(N) N Returns the Fractional part of the Argument (same as floor)
clamp(N,N,N) N If Arg1 <= Arg2 (min) returns Arg2; If Arg1 >= Arg3 (max) returns Arg3; otherwise returns Arg1.
sign(N) N Returns the sign of argument (-1,0,1) [sign(N) = N / abs(N) ]
min(N,N) N Returns the lowest value Argument.
min(N,N,N) N Returns the lowest value Argument.
min(N,N,N,N) N Returns the lowest value Argument.
max(N,N) N Returns the highest value Argument.
max(N,N,N) N Returns the highest value Argument.
max(N,N,N,N) N Returns the highest value Argument.
random() N Returns a random floating-point number between 0 and 1 [0 <= x < 1 ]
random(N) N Returns a random floating-point number between 0 and the specified value [0 <= x < a ]
random(N,N) N Returns a random floating-point number between the specified interval [a <= x < b ]
randint(N) N Returns a random integer from 1 to the specified value [1 <= x <= a ]
randint(N,N) N Returns a random integer in the specified interval [a <= x <= b ]
pi() N Returns the constant PI
toRad(N) N Converts Degree angles to Radian angles
toDeg(N) N Converts Radian angles to Degree angles
sin(N) N Returns the sine of N degrees
cos(N) N Returns the cosine of N degrees
tan(N) N Returns the tangent of N degrees
asin(N) N Returns the inverse sine of the argument, in degrees
acos(N) N Returns the inverse cosine of the argument, in degrees
atan(N) N Returns the inverse tangent of the argument, in degrees
sinh(N) N Returns the hyperbolic sine of N degrees
cosh(N) N Returns the hyperbolic cosine of N degrees
tanh(N) N Returns the hyperbolic tangent of N degrees
sinr(N) N Returns the sine of N radians
cosr(N) N Returns the cosine of N radians
tanr(N) N Returns the tangent of N radians
asinr(N) N Returns the inverse sine of the argument, in radians
acosr(N) N Returns the inverse cosine of the argument, in radians
atanr(N) N Returns the inverse tangent of the argument, in radians
atanr(N,N) N Returns the inverse tangent of the arguments (arg1 / arg2), in radians. This function accounts for positive/negative arguments, and arguments at or close to 0
sinhr(N) N Returns the hyperbolic sine of N radians
coshr(N) N Returns the hyperbolic cosine of N radians
tanhr(N) N Returns the hyperbolic tangent of N radians
A = B N Assignment (set A equal to B)
A++ N Assignment adding 1 (increases A by 1, same as "A += 1")
A-- N Assignment subtracting 1 (decreases A by 1, same as "A -= 1")
A += B N Assignment using addition (increases A by B, same as "A = (A + B)")
A -= B N Assignment using subtraction (decreases A by B, same as "A = (A - B)")
A /= B N Assignment using division
A %= B N Assignment using modulo
A ^= B N Assignment using exponentiation
A == B N Returns 1 if A is equal to B
A != B N Returns 1 if A is not equal to B
A > B N Returns 1 if A is greater than B
A < B N Returns 1 if A is less than B
A >= B N Returns 1 if A is greater or equal to B
A <= B N Returns 1 if A is less than or equal to B

String

Description

String-Support is a new feature to the Expression 2, which allows you to manipulate text. Text screens now have an input for strings.

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.

Function Returns Description
S:index(N) S Returns Nth letter of the string, formatted as a string.
S:length() N Returns the length of the string.
S:upper() S All characters are made uppercase.
S:lower() S All characters are made lowercase.
S:sub(N,N) S Returns a substring, starting at the first number argument and ending at the second.
S:left(N) S Returns N amount of characters starting from the leftmost character.
S:right(N) S Returns N amount of characters starting from the rightmost character.
S:find(S) N Returns the 1st occurrence of the string S, returns 0 if not found.
S:find(S, N) 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:explode(S) R Splits the string into an array, along the boundaries formed by the string S. See also String.Explode.
S:repeat(N) S Repeats the input string N times.
trim(S) S Trims away spaces at the beginning and end of a string.
S:trimLeft() S Trims away opening spaces on the string.
S:trimRight() S Trims away spaces at the end of a string.
S:replace(S,S) S Finds and replaces every occurrence of the first argument with the second argument.
S:toNumber() N Formats a number string as a number.
toString(N) S Formats a number as a string. (Numbers may be concatenated into a string without using this function)
toChar(N) S Returns a one-character string from its ASCII code.
toByte(S) N Returns the ASCII code of the 1st character in the string.
toByte(S,N) N Returns the ASCII code of the Nth character in the string.

Vector

Description

Vectors are now properly implemented in the Expression 2, which means that it is 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.

NEW! 2D and 4D vectors have been added to the vectors library. 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.

2D Vector Commands

Functions specific to 2D vectors

Function Returns Description
vec2(N,N) V2 Makes a 2D vector
vec2() V2 Same as vec2(0,0)
vec2(V) V2 Converts a 3D vector into a 2D vector (the z component is dropped)
vec2(V4) V2 Converts a 4D vector into a 2D vector (the z and w components are dropped)
V2:cross(V2) N Gets the 2D vector cross product/wedge product
shift(V2) V2 Swaps the vector's x,y components
V2:rotate(N) V2 Rotates a vector by the argument (given in degrees)
V2:toAngle() N Returns the 2D angle of the vector (given in degrees, -180 to 180)
V:dehomogenized() V2 Converts a 2D homogeneous vector (x,y,w) into a 2D cartesian vector

3D Vector Commands

Functions specific to 3D vectors

Function Returns Description
vec(N,N,N) V Makes a 3D vector
vec() V Same as vec(0,0,0)
vec(V2) V Converts a 2D vector into a 3D vector (the z component is set to 0)
vec(V2,N) V Converts a 2D vector into a 3D vector (the z component is set to the second argument)
vec(V4) V Converts a 4D vector into a 3D vector (the w component is dropped)
vec(A) V Changes an angle variable into a vector variable
V:cross(V) V Gets the 3D vector cross product
shiftL(V) V Shifts the vector's components left: shiftL( x,y,z ) = ( y,z,x )
shiftR(V) V Shifts the vector's components right: shiftR( x,y,z ) = ( z,x,y )
V:rotate(A) V Gets the rotated vector
V:rotate(N,N,N) V Gets the rotated vector
V:toAngle() A Gets the angles of the vector
V4:dehomogenized() V Converts a 3D homogeneous vector (x,y,z,w) into a 3D cartesian vector
V:isInWorld() N Returns 1 if the position vector is within the world, 0 if not

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".

Function Returns Description
vec4(N,N,N,N) V4 Makes a 4D vector
vec4() V4 Same as vec4(0,0,0,0)
vec4(V2) V4 Converts a 2D vector into a 4D vector (the z and w components are set to 0)
vec4(V2,N,N) V4 Converts a 2D vector into a 4D vector (the z and w components are set to the second and third arguments)
vec4(V2,V2) V4 Creates a 4D vector from two 2D vectors
vec4(V) V4 Converts a 3D vector into a 4D vector (the w component is set to 0)
vec4(V,N) V4 Converts a 3D vector into a 4D vector (the w component is set to the second argument)
shiftL(V4) V4 Shifts the vector's components left: shiftL( x,y,z,w ) = ( y,z,w,x )
shiftR(V4) V4 Shifts the vector's components right: shiftR( x,y,z,w ) = ( w,x,y,z )

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.

Function Returns Description
ceil(V) V Rounds XYZ up to the nearest integer
ceil(V,N) V Rounds XYZ up to argument 2's decimal precision
floor(V) V Rounds XYZ down to the nearest integer
floor(V,N) V Rounds XYZ down to argument 2's decimal precision
round(V) V Rounds XYZ to the nearest integer
round(V,N) V Rounds XYZ to argument 2's decimal precision
mod(V,N) V Returns the remainder after XYZ have been divided by argument 2
mod(V,V) V Returns the remainder after the components of vector 1 have been divided by the components of vector 2
clamp(V,V,V) V Clamps vector 1's XYZ between the XYZ of vector 2(min) and vector 3(max)
clamp(V,N,N) V Clamps vector 1's length between argument 2(min) and argument 3(max)
min(V,V) V Returns the vector with the smallest length
max(V,V) V Returns the vector with the greatest length
mix(V,V,N) V Combines vector 1's XYZ with vector 2's XYZ by a proportion given by argument 3 (between 0 and 1)
V:length() N Gets the length of the vector
V:length2() N Gets the squared length of the vector
V:distance(V) N Gets the distance between vectors
V:distance2(V) N Gets the squared distance between vectors
V:normalized() V Gets the normalized vector
V:dot(V) N Gets the vector dot (scalar) product
V:x() N Gets the x component of the vector
V:y() N Gets the y component of the vector
V:z() N Gets the z component of the vector
V:w() N Gets the w component of the vector
V:setX(N) V Returns a copy of the vector with X replaced (use as Vec = Vec:setX(...))
V:setY(N) V Returns a copy of the vector with Y replaced (use as Vec = Vec:setY(...))
V:setZ(N) V Returns a copy of the vector with Z replaced (use as Vec = Vec:setZ(...))
V:setW(N) V Returns a copy of the vector with W replaced (use as Vec = Vec:setW(...))
V:toString() S Gets the vector nicely formatted as a string "[X,Y,Z]"

Matrix

Developed by: Jimlad

Description

NEW: 4x4 matrices have been added! 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:

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() M2 Creates a 2x2 identity matrix
matrix2() M2 Creates a 2x2 zero matrix
matrix2(N,N,N,N) M2 Creates a matrix with values in order (i.j) of: (1,1), (1,2), (2,1), (2,2)
matrix2(V2,V2) M2 Creates a matrix with vectors by columns
matrix2(M) M2 Converts a 3x3 matrix into a 2x2 matrix - all (i,3) and (3,j) are omitted
matrix2(M4) M2 Converts a 4x4 matrix into a 2x2 matrix - all (i,3), (i,4), (3,j) and (4,j) are omitted
M2:swapRows() M2 Swaps rows
M2:swapColumns() M2 Swaps columns
M2:setRow(N,N,N) M2 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) M2 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) M2 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) M2 Sets the values of a column. The first argument given specifies the column, the vector contains the values to set

3x3 Matrix Commands

Functions specific to 3x3 matrices

Function Returns Description
identity() M Creates a 3x3 identity matrix
matrix() M Creates a 3x3 zero matrix
matrix(N1,N2... N9) M Creates a matrix with 9 values in the following order (i.j): (1,1), (1,2), (1,3), (2,1) etc.
matrix(V,V,V) M Creates a matrix with vectors by columns
matrix(M2) M Converts a 2x2 matrix into a 3x3 matrix - all (i,3) and (3,j) are filled with 0's
matrix(M4) M Converts a 4x4 matrix into a 3x3 matrix - all (i,4) and (4,j) are omitted
M:swapRows(N,N) M Swaps the two rows specified
M:swapColumns(N,N) M Swaps the two columns specified
M:setRow(N,N,N,N) M Sets the values of a row. The first argument given specifies the row(j), the following arguments are the values 1j, 2j, 3j
M:setRow(N,V) M Sets the values of a row. The first argument given specifies the row, the vector contains the values to set
M:setColumn(N,N,N,N) M Sets the values of a column. The first argument given specifies the column(i), the following arguments are the values i1, i2, i3
M:setColumn(N,V) M Sets the values of a column. The first argument given specifies the column, the vector contains the values to set
M:setDiagonal(N,N,N) M Sets the elements of the leading diagonal
M:setDiagonal(V) M Sets the elements of the leading diagonal from the components of a vector
matrix(E) M Creates a reference frame matrix from an entity's local direction vectors by columns in the order ( x, y, z )
M:x() V Returns the local x direction vector from a 3x3 coordinate reference frame matrix ( same as M:column(1) )
M:y() V Returns the local y direction vector from a 3x3 coordinate reference frame matrix ( same as M:column(2) )
M:z() V Returns the local z direction vector from a 3x3 coordinate reference frame matrix ( same as M:column(3) )
mRotation(V,N) M Creates a 3x3 rotation matrix, where the vector is the axis of rotation, and the number is the angle (anti-clockwise) in degrees. Example*: to rotate a vector (7,8,9) by 50 degrees about the axis (1,1,0), you would write V = mRotation(vec(1,1,0), 50) * vec(7,8,9)

* 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 3x3 matrices

Function Returns Description
identity4() M4 Creates a 4x4 identity matrix
matrix4() M4 Creates a 4x4 zero matrix
matrix4(N1,N2... N16) M4 Creates a matrix with 16 values in the following order (i.j): (1,1), (1,2), (1,3), (1,4), (2,1) etc.
matrix4(V4,V4,V4,V4) M4 Creates a matrix with vectors by columns
matrix4(M2) M4 Converts a 2x2 matrix into a 4x4 matrix - all (i,3), (i,4), (3,j) and (4,j) are filled with 0's
matrix4(M2,M2,M2,M2) M4 Constructs a 4x4 matrix from four 2x2 matrices
matrix4(M) M4 Converts a 3x3 matrix into a 4x4 matrix - all (i,4) and (4,j) are filled with 0's
M4:swapRows(N,N) M4 Swaps the two rows specified
M4:swapColumns(N,N) M4 Swaps the two columns specified
M4:setRow(N,N,N,N,N) M4 Sets the values of a row. The first argument given specifies the row(j), the following arguments are the values 1j, 2j, 3j, 4j
M4:setRow(N,V4) M4 Sets the values of a row. The first argument given specifies the row, the vector contains the values to set
M4:setColumn(N,N,N,N,N) M4 Sets the values of a column. The first argument given specifies the column(i), the following arguments are the values i1, i2, i3, i4
M4:setColumn(N,V4) M4 Sets the values of a column. The first argument given specifies the column, the vector contains the values to set
M4:setDiagonal(N,N,N,N) M4 Sets the elements of the leading diagonal
M4:setDiagonal(V4) M4 Sets the elements of the leading diagonal from the components of a vector
matrix4(E) M4 Creates a 4x4 reference frame matrix from an entity's local direction vectors by columns in the order (x, y, z, pos), with the bottom row (0,0,0,1)
M4:x() V Returns the local x direction vector from a 4x4 coordinate reference frame matrix ( same as M:column(1) )
M4:y() V Returns the local y direction vector from a 4x4 coordinate reference frame matrix ( same as M:column(2) )
M4:z() V Returns the local z direction vector from a 4x4 coordinate reference frame matrix ( same as M:column(3) )
M4:pos() V Returns the position vector from a 4x4 coordinate reference frame matrix ( same as M:column(4) )
inverseA(M4) M4 Finds the matrix inverse of a standard 4x4 affine transformation matrix ( the type created by matrix4(E) ). This should only be used on matrices with a particular format, where the top left 3x3 specifies rotation, the rightmost 3-column specifies translation, and the bottom row is (0,0,0,1)

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

Function Returns Description
M:row(N) V Returns the row as a vector
M:column(N) V Returns the column as a vector
M:element(N,N) N Returns the element with indices (i,j)
M:setElement(N,N,N) M Sets an element's value. The first two arguments specify the indices (i,j), the third argument is the value to set it to
M:swapElements(N,N,N,N) M Swaps two elements, specified by indices ( i1, j1, i2, j2 )
diagonal(M) V Returns a vector comprising the elements along the leading diagonal
trace(M) N Returns the trace of a matrix
det(M) N Returns the determinant of a matrix (Does not work for 4x4 matrices)
transpose(M) M Returns the transpose of a matrix
adj(M) M Returns the adjugate of a matrix (Does not work for 4x4 matrices)

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

Function Returns Description
ang(N,N,N) A Makes an angle
ang() A Same as ang(0,0,0)
ang(V) A Changes a vector variable into an angle variable
ceil(A) A Rounds PYR up to the nearest integer
ceil(A,N) A Rounds PYR up to argument 2's decimal precision
floor(A) A Rounds PYR down to the nearest integer
floor(A,N) A Rounds PYR down to argument 2's decimal precision
round(A) A Rounds PYR to the nearest integer
round(A,N) A Rounds PYR to argument 2's decimal precision
mod(A,N) A Returns the remainder after PYR have been divided by argument 2
mod(A,A) A Returns the remainder after the components of angle 1 have been divided by the components of angle 2
clamp(A,A,A) A Clamps angle 1's PYR between the PYR of angle 2(min) and angle 3(max)
clamp(A,N,N) A Clamps angle 1's PYR between argument 2(min) and argument 3(max)
mix(A,A,N) A Combines angle 1's PYR with angle 2's PYR by a proportion given by argument 3 (between 0 and 1)
shiftL(A) A Shifts the angle's components left: shiftL( p,y,r ) = ( y,r,p )
shiftR(A) A Shifts the angle's components right: shiftR( p,y,r ) = ( r,p,y )
angnorm(A) A Gets the normalized angle of an angle
angnorm(N) N Gets the normalized angle of a number
A:pitch() N Gets the pitch of the angle
A:yaw() N Gets the yaw of the angle
A:roll() N Gets the roll of the angle
A:setPitch(N) A Returns a copy of the angle with Pitch replaced (use as Ang = Ang:setPitch(...))
A:setYaw(N) A Returns a copy of the angle with Yaw replaced (use as Ang = Ang:setYaw(...))
A:setRoll(N) A Returns a copy of the angle with Roll replaced (use as Ang = Ang:setRoll(...))
A:toString() S Gets the angle nicely formatted as a string "[P,Y,R]"
A:toVector() V Simply transforms the values of the angle to a vector - same as vec(A)

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. hint() allows you to display strings quickly on your screen.

Also, the chip has the ability to thrust itself. Beware of the interval you're choosing for your contraption, because of the time response. (The thrust lasts for 10ms)

Commands

Function Returns Description
entity() E Gets the entity of the expression
concmd(S) N 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".
hint(S,N) Displays a hint popup with message S for N seconds (N being clamped between 0.7 and 7)
print(S) Posts string to chat
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

Entity

Description

This is a new feature to the Expression 2, which allows direct information on an entity. Entities can be found from target-finders, entity-markers and even the expression itself with entity() from selfaware. Since the expression now 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.

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.

Function Returns Description
entity(N) E Gets the entity associated with the id
owner() E Gets the owner of the expression ( same as entity():owner() )
E:id() N Gets the numeric id of an entity
noentity() E Returns an invalid entity
E:type() S Gets the class of an entity
E:model() S Gets the model of an entity
E:owner() E Gets the owner of an entity
E:name() S Gets the name of a player
E:steamID() S Gets the steam ID of the player (currently bugged)
E:pos() V Gets the position of the entity
E:eye() V Gets a players view-direction else entity forward direction
E:eyeTrace() RD Equivalent to rangerOffset(16384, E:shootPos(), E:eye()), but faster (causing less lag)
E:shootPos() V Returns a players shoot position
E:aimEntity() E Returns the entity that the entity is aiming at
E:aimBone() B Returns the bone the player is currently aiming at.
E:aimPos() V Returns the point that the entity is looking at
E:aimNormal() V Returns a normalized directional vector perpendicular to the surface pointed at.
E:frags() N Returns the number of frags the player is carrying
E:team() N Returns the team number a player is on
teamname(N) S Returns the name of the team associated with the team number
E:forward() V Gets the forward direction of the entity
E:right() V Gets the right direction of the entity
E:up() V Gets the up direction of the entity
E:vel() V Gets the velocity of the entity
E:velL() V Gets the local velocity of the entity
E:boxCenter() V Gets the center of the entity's bounding box, as a local position vector
E:boxMax() V Gets the maximum local XYZ of the entity's bounding box (the "highest" corner), as a local position vector
E:boxMin() V Gets the minimum local XYZ of the entity's bounding box (the "lowest" corner), as a local position vector
E:boxSize() V Gets the dimensions of the entity's bounding box as a vector (length, width, height)
E:toWorld(V) V Turning a vector from local to world from the entity.
E:toLocal(V) V Turning a vector from world to local from the entity.
E:angVel() A Gets the angular velocity of the entity
E:angles() A Gets the pitch, yaw and roll of the entity
E:radius() N Gets the size of the object (not precisely, but useful)
E:height() N Gets the height of a player or npc
E:bearing(V) N Gets the bearing from the entity via the vector
E:elevation(V) N Gets the elevation from the entity via the vector
E:health() N Gets the health of the entity
E:armor() N Gets the armor of the player
E:mass() N Gets the mass of the entity
E:timeConnected() N Returns a players time connected to a server
E:massCenter() V Gets the Center of Mass of the entity
E:massCenterL() V Gets the local Center of Mass of the entity
E:setMass(N) Sets the mass of the entity (between 0.001 and 50,000)
E:inertia() V Gets the principal components of the entity's inertia tensor in the form ( Ixx, Iyy, Izz )
E:applyForce(V) Applies force to the entity according to the given vector's direction and magnitude
E:applyOffsetForce(V,V) Applies force to the entity according to the first vector from the location of the second
E:applyAngForce(A) Applies torque to the entity according to the given angle
E:isPlayer() N Is the entity a player
E:isOnFire() N Is the entity on fire
E:isWeapon() N Is the entity a weapon
E:isNPC() N Is the entity a NPC
E:isFrozen() N Is the entity frozen
E:isVehicle() N Is the entity a vehicle
E:inVehicle() N Is the player in a vehicle
E:isWorld() N Is the entity the world
E:isOnGround() N Is the entity resting on something, only works on players and NPCs
E:isUnderWater() N Is the entity under water
E:isPlayerHolding() N Is the entity being held by a player
E:isAlive() N Is the player or NPC alive
E:isCrouch() N Is the player crouching
E:hintDriver(S,N) 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). Returns 1 if the hint has been sent.
E:printDriver(S) N Posts S to the chat of the driver of vehicle E. Returns 1 if the text was printed, 0 if not.
E:driver() E Returns the driver of the vehicle if there is one, nil otherwise
E:passenger() E Returns the passenger of the vehicle if there is one, in single seat pods this will return the driver.
E:lockPod(N) 1 locks and 0 unlocks vehicle
E:ejectPod() Ejects player in vehicle
E:killPod() Kills player in vehicle
E:weapon() E Returns the weapon that player E is currently holding
E:clip1() N Returns the amount of ammo in the primary clip of weapon E, -1 if there is no primary clip
E:clip2() N Returns the amount of ammo in the secondary clip of weapon E, -1 if there is no secondary clip*
E:primaryAmmoType() S Returns the type of primary ammo of weapon E as a number in a string
E:secondaryAmmoType() S Returns the type of secondary ammo of weapon E as number in a string
E:ammoCount(S) N Returns the amount of stored ammo of type S on player E, excluding current clip
E:removeTrails() Removes the trail from entity.
E:setTrails(startSize, endSize, length, string material, vector color, alpha) Adds a trail to entity with the specified attributes.
E:lookupAttachment(string attachmentName) N Returns entity's attachment ID associated with attachmentName
E:attachmentPos(attachmentID) V Returns entity's attachment position associated with attachmentID
E:attachmentAng(attachmentID) A Returns entity's attachment angle associated with attachmentID
E:attachmentPos(string attachmentName) V Same as E:attachmentPos(E:lookupAttachment(attachmentName))
E:attachmentAng(string attachmentName) A Same as E:attachmentAng(E:lookupAttachment(attachmentName))
*This is not the stored amount, no known weapon has a secondary clip, the AR2 and smg only have a storage, not a clip

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 may contain number and vector data.

Tables can be transferred by using T=T:clone() at the end of the expression.
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().

Commands

Function Returns Description
table() T Creates an empty table.
T:clone() T Creates an independant copy of a table.
T:count() N Returns the number of elements in the table.
T:number(S) N Retrieves the number table element indexed with the string. Returns 0 if no such element is found.
T:vector(S) V Returns the vector table element indexed with the string. Returns the 0-vector if no such element is found.
T:angle(S) A Returns the angle table element indexed with the string. Returns the 0-angle if no such element is found.
T:string(S) S Returns the string table element indexed with the string. Returns an empty string if no such element is found.
T:entity(S) E Returns the entity table element indexed with the string. Returns nil if no such element is found.
T:bone(S) B Returns the bone table element indexed with the string. Returns nil if no such element is found.
T:setNumber(S,N) Saves the number as a table element with the specified index string.
T:setVector(S,V) Saves the vector as a table element with the specified index string.
T:setAngle(S,A) Saves the angle as a table element with the specified index string.
T:setString(S,S) Saves the string as a table element with the specified index string.
T:setEntity(S,E) Saves the entity as a table element with the specified index string.
T:setBone(S,B) Saves the bone as a table element with the specified index string.

Array

Thanks to: Erkle

Description

NEW: 2D and 4D vectors and matrices have been added!

Same as table, but with much less memory footprint and is numerically indexed instead. It is similar to E1's packet support. Supports number, vector, matrix, angle, string, entity and bone data. Arrays can be transferred by using A=A:clone() at the end of the expression.

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).

Function Returns Description
array() R Creates an empty array
R:clone() R Creates an independant copy of an array
R:count() N Returns the number of elements in the array
R:sum() N Adds all numbers in the array together and returns result
R:concat() S Combines all strings and returns result
R:concat(S) S Combines all strings with specified string in between and returns result
R:average() N Gives the average of all numbers in array
R:min() N Returns the smallest number in array
R:minIndex() N Returns the index of the smallest number in array
R:max() N Returns the largest number in array
R:maxIndex() N Returns the index of the largest number in array
R:number(N) N Retrieves the number array element indexed with the number. Returns 0 if no such element is found
R:vector2(N) V2 Returns the 2D vector array element indexed with the number. Returns the 0-vector if no such element is found
R:vector(N) V Returns the 3D vector array element indexed with the number. Returns the 0-vector if no such element is found
R:vector4(N) V4 Returns the 4D vector array element indexed with the number. Returns the 0-vector if no such element is found
R:matrix2(N) M2 Returns the 2x2 matrix array element indexed with the number. Returns the 0-matrix if no such element is found
R:matrix(N) M Returns the 3x3 matrix array element indexed with the number. Returns the 0-matrix if no such element is found
R:matrix4(N) M4 Returns the 4x4 matrix array element indexed with the number. Returns the 0-matrix if no such element is found
R:angle(N) A Retrieves the angle array element indexed with the number. Returns 0-angle if no such element is found
R:string(N) S Returns the string array element indexed with the number. Returns an empty string if no such element is found
R:entity(N) E Returns the entity array element indexed with the number. Returns nil if no such element is found
R:bone(N) B Returns the bone array element indexed with the number. Returns nil if no such element is found
R:setNumber(N,N) Saves the number as an array element with the specified index number
R:setVector2(N,V2) Saves the 2D vector as an array element with the specified index number
R:setVector(N,V) Saves the 3D vector as an array element with the specified index number
R:setVector4(N,V4) Saves the 4D vector as an array element with the specified index number
R:setMatrix2(N,M2) Saves the 2x2 matrix as an array element with the specified index number
R:setMatrix(N,M) Saves the 3x3 matrix as an array element with the specified index number
R:setMatrix4(N,M4) Saves the 4x4 matrix as an array element with the specified index number
R:setAngle(N,A) Saves the angle as an array element with the specified index number
R:setString(N,S) Saves the string as an array element with the specified index number
R:setEntity(N,E) Saves the entity as an array element with the specified index number
R:setBone(N,B) Saves the bone as an array element with the specified index number
R:push<type>(*) Saves the data at the end of the array
R:pop<type>() * Deletes and returns the last entry in the array. Be sure not to use popNumber() on a vector or similar, as the data may be lost
R:pop() Delets the last entry in the array
R:unshift<type>(*) Adds the data to the beginning of the array. Will move all other entries up one address
R:shift<type>(*) * Deletes and returns the first element of the array, moving other entries down one address to compensate.
R:shift() Deletes the first element of the array; all other entries will move down one address
R:insert<type>(N,*) * Inserts the data into the specified index; all entries after this index will move up to compensate
R:remove<type>(N) * Deletes and returns the specified entry, moving subsequent entries up to compensate
R:remove(N) Deletes the specified entry, moving subsequent entries up to compensate

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
tickClk() N Returns 1 if the current execution was caused by "runOnTick"
curtime() N Returns the current 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() N Returns 1 if the current execution was caused by the interval
clk(S) N Returns 1 if the current execution was caused by the inserted name

Unit Conversion

Description

All conversions are precise so it is recommended to round the result if it is going to be displayed (round()).

Commands

Function Returns Description
toUnit(S,N) N Converts default garrysmod units to specified units
fromUnit(S,N) N Converts specified units to default garrysmod units
convertUnit(S,S,N) N Converts between two units

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

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.

Wirelink is not yet officially supported

Commands

Equal and Not Equal operators are available. XWL here means the Wirelink input.

Function Returns Description
XWL:isHiSpeed() N Returns true if the linked component is high-speed capable.
XWL:entity() E Returns the entity of the linked component.
XWL:hasInput(S) N Returns true if the linked component has an input of the specified name.
XWL:hasOutput(S) N Returns true if the linked component has an output of the specified name.
XWL:setNumber(S,N) Sets the component's input of the specified name equal to the number.
XWL:number(S) N Retrieves the component's output of the specified name.
XWL:setVector(S,V) Sets the component's input of the specified name equal to the vector.
XWL:vector(S) V Retrieves the component's output of the specified name.
XWL:setString(S,S) Sets the component's input of the specified name equal to the string.
XWL:string(S) S Retrieves the component's output of the specified name.
XWL:setXyz(V) Sets the X/Y/Z to the corresponding values in the vector.
XWL:xyz() V Retrieves the X/Y/Z as the corresponding values in the vector.
XWL:setEntity(S,E) Sets the component's input of the specified name equal to the entity.
XWL:entity(S) E Retrieves the component's output of the specified name.
XWL:writeCell(N,N) N Writes the second argument to the memory cell specified by the first argument. Returns true if successful.
XWL:readCell(N) N Returns contents of the specified memory cell.
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.

Entity Discovery

Developed by: Gwahir

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

Commands

Function Returns Description
findUpdateRate() N Returns the minimum delay between entity find events on a chip
findPlayerUpdateRate() N Returns the minimum delay between entity find events per player
findInSphere(V,N) N Finds entities in a sphere around V with a radius of N, returns the number found after filtering
findInCone(V,V,N,V) N Like findInSphere but with a cone, arguments are for position, direction, length, and degrees (currently bugged)
findInBox(V,V) N Like findInSphere but with a globally aligned box, the arguments are the diagonal corners of the box
findByName(S) N Find all entities with the given name
findByModel(S) N Find all entities with the given model
findByClass(S) N Find all entities with the given class
findPlayerByName(S) E returns the player with the given name, this is an exception to the rule
findExcludePlayer(E) Exclude this player from future finds
findExcludePlayer(S) Exclude this player from future finds
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
findAllowPlayer(E) Remove this player from the black list
findAllowPlayer(S) Remove this player from the black list
findAllowPlayerProps(E) Remove entities owned by this player from the black list
findAllowPlayerProps(S) Remove entities owned by this player from the black list
findAllowModel(S) Remove entities with this model (or partial model name) from the black list
findAllowClass(S) Remove entities with this class (or partial class name) from the black list
findIncludePlayer(E) Include this player in future finds, and remove others not in the white list
findIncludePlayer(S) Include this player in future finds, and remove others not in the white list
findIncludePlayerProps(E) Include entities owned by this player from future finds, and remove others not in the white list
findIncludePlayerProps(S) Include entities owned by this player from future finds, and remove others not in the white list
findIncludeModel(S) Include entities with this model (or partial model name) in future finds, and remove others not in the white list
findIncludeClass(S) Include entities with this class (or partial class name) in future finds, and remove others not in the white list
findDisallowPlayer(E) Remove this player from the white list
findDisallowPlayer(S) Remove this player from the white list
findDisallowPlayerProps(E) Remove entities owned by this player from the white list
findDisallowPlayerProps(S) Remove entities owned by this player from the white list
findDisallowModel(S) Remove entities with this model (or partial model name) from the white list
findDisallowClass(S) Remove entities with this class (or partial class name) from the white list
findClearBlackList() Clear all entries from the entire black list
findClearBlackPlayerList() Clear all entries from the black player list
findClearBlackPropList() Clear all entries from the black prop list
findClearBlackModelList() Clear all entries from the black model list
findClearBlackClassList() Clear all entries from the black class list
findClearWhiteList() Clear all entries from the entire white list
findClearWhitePlayerList() Clear all entries from the white player list
findClearWhitePropList() Clear all entries from the white prop list
findClearWhiteModelList() Clear all entries from the white model list
findClearWhiteClassList() Clear all entries from the white class list
findResult(N) E Returns the indexed entity from the previous find event (valid parameters are 1 to the number of entities found)
findClosest(V) E Returns the closest entity to the given point from the previous find event
findToArray() R Formats the query as an array, R:entity(Index) to get a entity, R:string to get a description including the name and entity id.
find() E Equivalent to findResult(1)
findSortByDistance(V) N 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) N Filters the list of entities by removing all entities that are not of this class
findClipFromClass(S) N Filters the list of entities by removing all entities that are of this class
findClipToModel(S) N Filters the list of entities by removing all entities that do not have this model
findClipFromModel(S) N Filters the list of entities by removing all entities that do have this model
findClipToName(S) N Filters the list of entities by removing all entities that do not have this name
findClipFromName(S) N Filters the list of entities by removing all entities that do have this name
findClipFromSphere(V, N) N Filters the list of entities by removing all entities within the specified sphere (center, radius)
findClipToRegion(V, V) N 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: ZeikJT

Description

Global variables are a way to exchange data between two expression chips without the need for any wiring at all.

The global variables will be sorted into groups so that you can avoid two chips overwriting each other's global data. By default a newly spawned chip will default to "default" as the group entry, but you can always change that by using the gSetGroup(s) function.

Remember, all global variables persist until you delete them or you leave the server. They will never automatically reset.

Using tables like this does isn't exactly a memory free deal, when using this on servers try to keep the amount of stored global variable at any one time down to a minimum.

As of right now the global group will be reset after every run. Also, try to keep the group setting down to a minimum as it can be costly.

Commands

Function Returns Description
gSetStr(S) Stores a string into the current group, use with gGetStr(S)
gSetStr(S,S) Stores the second string into the current group under the index specified by the first string
gSetStr(N,S) Stores the string into the current group under the index specified by the number
gSetNum(N) Stores a number into the current group, use with gGetNum(N)
gSetNum(S,N) Stores the number into the current group under the index specified by the string
gSetNum(N,N) Stores the second number into the current group under the index specified by the first number
gGetStr() S Returns the string under the current group stored only by gSetStr(S)
gGetStr(S) S Returns the string under the current group stored in the input string index, use with gSetStr(S,S)
gGetStr(N) S Returns the string under the current group stored in the input number index, use with gSetStr(N,S)
gGetNum() N Returns the number under the current group stored only by gSetNum(N)
gGetNum(S) N Returns the number under the current group stored in the input string index, use with gSetNum(S,N)
gGetNum(N) N Returns the number under the current group stored in the input number index, use with gSetNum(N,N)
gDeleteStr() S Like gGetStr() but deletes the value after retrieval
gDeleteStr(S) S Like gGetStr(S) but deletes the value after retrieval
gDeleteStr(N) S Like gGetStr(N) but deletes the value after retrieval
gDeleteNum() N Like gGetNum() but deletes the value after retrieval
gDeleteNum(S) N Like gGetNum(S) but deletes the value after retrieval
gDeleteNum(N) N Like gGetNum(N) but deletes the value after retrieval
gSetGroup(S) Sets the group that all global write, read, and delete functions will use, default is "default"
gGetGroup() S Returns the name of the current group for the chip
gShare(N) Determines whether or not the group you're in is available only to you or to all players. Defaults to 0. Any value but 0 will set your group to be accessible to all players. Be mindful that there are two groups with every name, one is shared, one is not; values do not transition between the two.
gResetGroup() Returns the current chip's group back to "default"
gDeleteAllStr() Deletes all of the global strings stored under the current group, including the one stored by gSetStr(S)
gDeleteAllNum() Deletes all of the global numbers stored under the current group, including the one stored by gSetNum(N)
gDeleteAll() Deletes all of the global values stored under the current group, including the ones stored by gSetStr(S) and gSetNum(N)

Built-In Ranger

Developed by: ZeikJT

Description

The built-in ranger is heavily 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 pre-ranging.

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.

Commands

Function Returns Description
Ranger Options To be used before an actual ranger trace
rangerHitWater(N) Default is 0, if any other value is given it will hit water
rangerIgnoreWorld(N) Default is 0, if any other value is given it will ignore world
rangerDefaultZero(N) If given any value other than 0 it will default the distance data to zero when nothing is hit
rangerFilter(E) Feed entities you don't want the trace to hit
Ranger Tracing Gathers data, if options are declared prior to this they will be used
ranger(N) RD You input max range, it returns ranger data
ranger(N,N,N) RD Same as above with added inputs for X and Y skew
rangerAngle(N,N,N) RD You input the distance, x-angle and y-angle (both in degrees) it returns ranger data
rangerOffset(V,V) RD You input two vector points, it returns ranger data
rangerOffset(N,V,V) RD You input the range, a position vector, and a direction vector and it returns ranger data
Ranger Data Retreval Accesses data stored in an RD container
RD:distance() N Outputs the distance from the rangerdata input, else depends on rangerDefault
RD:position() V Outputs the position of the input ranger data trace IF it hit anything, else returns (0,0,0)
RD:entity() E Returns the entity of the input ranger data trace IF it hit an entity, else returns nil
RD:hit() N Returns 1 if the input ranger data hit anything and 0 if it didn't
RD:hitNormal() V Outputs a normalized vector perpendicular to the surface the ranger is pointed at.

Sound Playback

Developed by: ZeikJT

Description

Allows Expression 2 to play sounds. You can find a list of Half-life 2 sounds here or use GCFScape to preview each sound.

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 '\'.

Commands

Function Returns Description
soundPlay(N,N,S) soundPlay(int Index, int Duration, string Path to File)
soundPlay(S,N,S) soundPlay(string Index, int Duration, string Path to File)
soundPlay(N,N,S,N) soundPlay(int Index, int Duration, string Path to File, int FadeTime)
soundPlay(S,N,S,N) soundPlay(string Index, int Duration, string Path to File, int FadeTime)
soundStop(N) Stops the sound stored at the integer index and removes the entry
soundStop(N,N) Fades the sound stored at the first input's integer index in the second input's amount of seconds and removes the entry
soundStop(S) Stops the sound stored at the string index and removes the entry
soundStop(S,N) Fades the sound stored at the string index in the integer input's amount of seconds and removes the entry
soundPitch(N,N) soundPitch(integer Index, integer Pitch) (default Pitch is 100)
soundPitch(S,N) Same as above but takes a string index instead of an integer index
soundVolume(N,N) soundVolume(integer Index, integer Volume) (default Volume is 1)
soundVolume(S,N) Same as above but takes a string index instead of an integer index
soundPurge() Clears the sound table and stops all sounds

Chat

Developed by: ZeikJT & Gwahir

Description

The following functions are for reading the chat log. This is similar to the text receiver.

Commands

Function Returns Description
lastSaid() S Returns what the last message was in the chat log.
lastSaidWhen() N Returns the time the last message was said
E:lastSaid() S Returns what the given player last said
E:lastSaidWhen() N Returns when the given player last said something
lastSpoke() E Returns the entity of the last player to speak
runOnChat(N) 1 will cause the chip to run on chat events, 0 stops the chip from running on chat events, only needs to be called once (not every execution)
chatClk() N Returns 1 if the chip is being executed because of a chat event, 0 otherwise
chatClk(E) N Returns 1 if the chip is being executed because of a chat event by the given player, 0 otherwise

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() V Returns the color of an entity as a vector (R,G,B)
E:getAlpha() N Returns the alpha of an entity
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:setAlpha(N) Changes the alpha of an entity
E:setMaterial(S) Sets the material of entity with material S

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

Function Returns Description
map() S Returns the current map name
hostname() S Returns the Name of the server
isLan() N Returns 1 if lan mode is enabled
gamemode() S Returns the name of the current gamemode
gravity() N Returns gravity
isSinglePlayer() N Returns 1 if singleplayer, 0 if multiplayer
isDedicated() N Returns 1 if server is dedicated
numPlayers() N Returns the number of players currently in the server
maxPlayers() N Returns the max number of players allowed in the server
maxOfType(S) N Returns the maximum allowed of a certain type of entity, i.e. maxOfType("wire_thrusters"). Returns 0 if you enter an invalid parameter.
playerDamage() N Returns 1 if player vs player damage is enabled on the server
convar(S) S Give a console command such as name and it returns the set value
convarnum(S) N Give a console command such as sbox_godmode and it returns the set value

Constraint

Developed by: ZiekJT

Description

The following functions get information about entities based on constraints

Commands

Function Returns Description
E:getConstraints() R Returns an array with all entities constrained to the given entity.
E:hasConstraints() N Returns the number of the constraints the entity has
E:hasConstraints(S) N Returns the number of the constraints of type specified the entity has
E:isConstrained() N Returns 1 if the entity has constraints, 0 if not
E:isWeldedTo() E Returns the first entity the input entity was welded to
E:isWeldedTo(N) E Returns the nth entity the input entity was welded to
E:isConstrainedTo() E Returns the first entity the input entity was constrained to
E:isConstrainedTo(N) E Returns the nth entity the input entity was constrained to
E:isConstrainedTo(S) E Returns the first entity the input entity was constrained to with the input type
E:isConstrainedTo(S, N) E Returns the nth entity the input entity was constrained to with the input type

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.

Commands

Function Returns Description
E:npcStop() Stops any anything the NPC is doing, including things it decided to do by itself
E:npcGoWalk(V) Tells the NPC to walk to position V
E:npcGoRun(V) Tells the NPC to run to position V
E:npcFace(V) This will rotate the NPC to face position V. This is purely aesthetic and can't be used to aim their weapon.
E:npcAttack() Tells the NPC to use their melee attack.
E:npcShoot() Tells the NPC to shoot their gun
E:npcGiveWeapon() Gives the NPC an SMG
E:npcGiveWeapon(S) Gives the NPC a weapon. Example: E:npcGiveWeapon("pistol"). Other arguments include "ar2", "crowbar", "357", "shotgun", "crossbow", "rpg", "frag", etc. Other such as the bugbait or slam may be buggy.
E:npcRelationship(E,S,N) Will set the NPC's relationship to the specified entity to the S input, priority N. Priority is any number between 0 and 999. The relationship string can be either "like" "neutral" "hate" or "fear". Same goes for all other relationship functions.
E:npcRelationship(S,S,N) Same as above, but sets relationship to an entire class specified by the first string. Example: "npc_manhack", "prop_physics".
E:npcRelationshipByOwner(E,S,N) N Sets the NPC's relationship to all currently existing NPCs owned by player E. Returns number of entities added to relationships.
E:npcDisp(E) S Returns the NPC's relationship to entity E.


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.

Commands

Function Returns Description
signalSetGroup(S) Sets the E-2's current signal group to S, this is applied during runOnSignal, signalSend, and signalSetOnRemove calls, so call it first.
signalGetGroup() S Gets the E-2's current signal group
runOnSignal(S,N,N2) If N2 == 0 the chip will no longer run on this signal, otherwise it makes this chip execute when signal S is sent by someone in scope N.
signalClk() N Returns 1 if the chip was executed because of any signal, regardless of name, group or scope. Returns 0 otherwise.
signalClk(S) N Returns 1 if the chip was executed because the signal S was sent, regardless of group or scope. Returns 0 otherwise.
signalClk(S,N) N Returns 1 if the chip was executed because the signal S was sent to the scope N, regardless of group. Returns 0 otherwise.
signalClk(S,S2) N Returns 1 if the chip was executed because the signal S2 was sent in the group S, regardless of scope. Returns 0 otherwise.
signalClk(S,S2,N) N Returns 1 if the chip was executed because the signal S2 was sent in the group S to the scope N. Returns 0 otherwise.
signalName() S Returns the name of the received signal.
signalGroup() S Returns the group name of the received signal.
signalSender() E Returns the entity of the chip that sent the signal.
signalSenderId() N Returns the entity ID of the chip that sent the signal. Useful if the entity doesn't exist anymore.
signalSetOnRemove(S,N) Sets the signal that the chip sends when it is removed from the world.
signalClearOnRemove() Clears the signal that the chip sends when it is removed from the world.
signalSend(S,N) Sends signal S to scope N. Additional calls to this function with the same signal will overwrite the old call until the signal is issued.
signalSendDirect(S,E) Sends signal S to the given chip. Multiple calls for different chips do not overwrite each other.
signalSendToPlayer(S,E) sends signal S to chips owned by the given player, multiple calls for different players do not overwrite each other

Bones

Developed by: TomyLobo

Description

This extension introduced a new type, bone. 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 entities (although some things are missing).

Array and table functions for bones are also provided.

Commands

Function Returns Description
E:bone(N) B Returns E's Nth bone.
E:bones() R Returns an array containing all of E's bones. This array's first element has the index 0!
E:boneCount() N Returns E's number of bones.
nobone() B Returns an invalid bone.
E:aimBone() B Returns the bone the player is currently aiming at.
B:entity() E Returns the entity B belongs to
B:index() N Returns B's index in the entity it belongs to. Returns -1 if the bone is invalid or an error occured.
B:pos() V Returns B's position.
B:forward() V Returns a vector describing B's forward direction.
B:right() V Returns a vector describing B's right direction.
B:up() V Returns a vector describing B's up direction.
B:vel() V Returns B's velocity.
B:velL() V Returns B's velocity in local coordinates.
B:toWorld(V) V Transforms V from local coordinates (as seen from B) to world coordinates.
B:toLocal(V) V Transforms V from world coordinates to local coordinates (as seen from B).
B:angVel() A Returns B's angular velocity.
B:angles() A Returns B's pitch, yaw and roll angles.
B:bearing(V) N Returns the bearing (yaw) from B to V.
B:elevation(V) N Returns the elevation (pitch) from B to V.
B:mass() N Returns B's mass.
B:massCenter() V Returns B's Center of Mass.
B:massCenterL() V Returns B's Center of Mass in local coordinates.
B:setMass(N) Sets B's mass (between 0.001 and 50,000)
B:inertia() V Gets the principal components of B's inertia tensor in the form vec(Ixx, Iyy, Izz)
B:applyForce(V) Applies force to B according to V's direction and magnitude
B:applyOffsetForce(V,V2) Applies force to B according to V from the location of V2
B:applyAngForce(A) Applies torque to B according to A
B:isFrozen() N Returns 1 if B is frozen, 0 otherwise

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

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!

Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox