Синтаксис Expression 2 сильно изменился со времен прошлого Expression Chip, придется изучить немного больше команд, но это сделает ваши постройки намного более функциональными. Помните что как правило существует несколько способов написания кода, и задача может быть решена несколькими путями.
Синтаксис
Пример
Упрощенный
Описание
#
#this is comment
Все, что находится за знаком # считается комментарием и не учитывается при обработке кода
if () {} else {}
if (A) {D=B} else {D=C}
if (A) {D=B}
если A истина то выполняем первую операцию, иначе вторую. else {} не обязателен, например: "if (A) {C=B}"
elseif () {}
elseif (A) {B = C}
Впереди обязательно должен быть if или elseif. Дополнительная проверка в случае ложности исходного утверждения
~
if(~Time & Time == 0) {DO stuff}
Изменялось ли значение на входе между выполнениями?
$
Opitch = Pitch + ($Pitch *3)
Возвращает разницу между выполнениями в виде числа. (Работает только с объявленными переменными типа number, vector, and angle)
Любые инструкции в фигурных скобках будет повторяться, пока условие в круглых скобках, истинно. Если условие ложно, инструкции будут пропущены и E2 будет продолжаться с конца цикла. Заметим, что условие проверяется только в самом начале каждого цикла.
for () {}
for () {}
Добавляет значение C переменной для каждой итерации, пока она равна значению B. Если шаг C не указан, то он будет установлен на единицу. Обратите внимание, что А и В вычисляются только один раз - если они рассчитываются из переменных, что цикл устанавливает новые значения, это не изменит число итераций.
foreach () {}
foreach(K,V:type=Table) {}
Проверяет каждый элемент указанного типа в таблице. Назначает ключ к К и значение V. Элементы, которые не имеют определенного типа будут пропущены. Элементы могут быть добавлены, удалены или изменены, однако элементы, которые добавляются не будут обрабатываться в текущем цикле. Только цикл по строке индексов при использовании таблицы.
continue
if (A) {continue}
Может быть использовано только в while/for/foreach цикле. Эта команда позволяет немедленно вернуться к началу цикла, пропуская следующие инструкции.
break
if (A) {break}
Может быть использовано только в while/for/foreach цикле. Эта команда позволяет немедленно вернуться к выходу из цикла, пропуская следующие инструкции
Возводит число Эйлера в степень аргумента (можно и e()^, однако так быстрее)
ln()
Возвращает логарифм числа по основанию e (число Эйлера)
log2()
Возвращает логарифм числа по основанию 2 (двоичный)
log10()
Возвращает логарифм числа по основанию 10(десятичный)
log(,)
Возвращает логарифм первого аргумента по основанию второго
abs()
Возвращает модуль числа
ceil()
Округляет аргумент до ближайшего большего целого числа [ceil(5.5) = 6]
ceil(,)
Округляет аргумент с десятичной точностью до второго аргумента [ceil(5.05) = 5.1]
floor()
Округляет аргумент до ближайшего меньшего целого числа [floor(5.5) =5]
floor(,)
Округляет аргумент с десятичной точностью до второго аргумента [floor(5.14) = 5.1]
round()
Округление [round(5.5) = 6; round(5.4) = 5]
round(,)
Округление с десятичной точностью до второго аргумента
int()
Возвращает целую часть числа (как floor)
frac()
Возвращает дробную часть числа (как floor)
clamp(,,)
Если Arg1 <= Arg2 (минимальное) возвращает Arg2; если Arg1 >= Arg3 (максимальное) возвращает Arg3; иначе возвращает Arg1.
inrange(,2,3)
Возвращает 1 если находится в интервале [2; 3], иначе 0.
sign()
Возвращает знак числа (-1,0,1) [sign() = / abs() ]
min(,)
Возвращает значение минимального аргумента
min(,,)
Возвращает значение минимального аргумента
min(,,,)
Возвращает значение минимального аргумента
max(,)
Возвращает значение максимального аргумента
max(,,)
Возвращает значение максимального аргумента
max(,,,)
Возвращает значение максимального аргумента
random()
Возвращает случайное число с плавающей точкой между 0 и 1 [0 <х <1]
random()
Возвращает случайное число с плавающей точкой между 0 и указанным значением [0 <= X <]
random(,)
Возвращает случайное число с плавающей точкой в указанном интервале [A < х < B]
randint()
Возвращает случайное целое число между 1 и указанным значением [1 <= x <= a ]
randint(,)
Возвращает случайное целое число в указанном интервале [a <= x <= b ]
pi()
Возвращает постоянную ПИ
toRad()
Переводит градусную меру угла в радианную
toDeg()
Переводит радианную меру угла в градусную
sin()
Возвращает синус числа (из градусной меры)
cos()
Возвращает косинус числа (из градусной меры)
tan()
Возвращает тангенс числа (из градусной меры)
asin()
Возвращает арксинус числа (из градусной меры)
acos()
Возвращает арккосинус числа (из градусной меры)
atan()
Возвращает арктангенс числа (из градусной меры)
sinh()
Возвращает гиперболический синус степеней
cosh()
Returns the hyperbolic cosine of degrees
tanh()
Returns the hyperbolic tangent of degrees
sinr()
Возвращает синус числа (из радианной меры)
cosr()
Возвращает косинус числа (из радианной меры)
tanr()
Возвращает тангенс числа (из радианной меры)
asinr()
Возвращает арксинус числа (из радианной меры)
acosr()
Возвращает арккосинус числа (из радианной меры)
atanr()
Возвращает арктангенс числа (из радианной меры)
atanr(,)
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()
Returns the hyperbolic sine of radians
coshr()
Returns the hyperbolic cosine of radians
tanhr()
Returns the hyperbolic tangent of radians
A = B
Присваивание (присвоить переменной A число B)
A++
Увеличить на 1 (добавить к A единицу, упрощенно "A += 1")
A--
Уменьшить на 1 (вычисть из A единицу, упрощенно "A -= 1")
A += B
Увеличить на число (увеличить A на B, упрощенно "A = (A + B)")
A -= B
Уменьшить на число (уменьшить A на B, упрощенно "A = (A - B)")
Создает строку из помещенной в кавычки, например,"text goes here" Доступны операторы равенства (==) и неравенства, также как и конкатенации(+), для объединения строк и чисел в любом порядке. Операция конкатенации возвращает строку. Первый символ строки имеет номер 1. Отрицательные индексы отсчитываются от конца строки, в которой последний символ -1. Положительные индексы привязаны к длине строки.
Function
Returns
Description
S:index(N)
S
Возвращает N-нный символ из строки
S:length()
Возвращает длину строки
S:upper()
S
Делает все буквы у строки большими
S:lower()
S
Делает все буквы у строки маленькими
S:sub(N,N)
S
Возвращает подстроку, начиная с первого аргумента и заканчивая вторым
S:left(N)
S
Возвращает первые символов строки
S:right(N)
S
Возвращает последние символов строки
S:find(S)
Возвращает 1 если в строке найдена подстрока S, или 0 если не найдена
S:find(S, N)
Возвращает 1 если в строке найдена подстрока S начиная с Nого символа, или 0 если не найдена
S:explode(S)
R
Разбивает строку через разделитель S и записывает результат в массив. Подробнее string.Explode
S:repeat(N)
S
Повторяет N раз, вход S
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(1S,2S)
S
В строке S, находит все 1S, и заменяет их на 2S
S:reverse()
S
Возвращает перевернутую строку S
S:toNumber()
Переводит строку в числа
toString(N)
S
Переводит число в строку. (Числа могут быть преобразованы в строку без этой функции)
toChar(N)
S
Возвращает ASCII-код из , при условии что там помещен один знак.
toByte(S)
Возвращает ASCII-код от первого знака в начале строки.
toByte(S,N)
Возвращает ASCII-код знака из S, на позиции N
S:match(S2,N)
R
Запускает функцию string.match(S, S2, N) garrysmod и возвращает в виде массива.
S:match(S2)
R
Запускает функцию string.match(S, S2) garrysmod и возвращает в виде массива.
S:matchFirst(S2,N)
S
Запускает функцию string.match(S, S2, N) garrysmod и первое совпадение или пустую строку в случае ошибки.
S:matchFirst(S2)
S
Запускает функцию string.match(S, S2) garrysmod и первое совпадение или пустую строку в случае ошибки.
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.
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.
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(,,,)
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,,)
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,)
V4
Converts a 3D vector into a 4D vector (the w component is set to the second argument)
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,)
V
Rounds XYZ up to argument 2's decimal precision
floor(V)
V
Rounds XYZ down to the nearest integer
floor(V,)
V
Rounds XYZ down to argument 2's decimal precision
round(V)
V
Rounds XYZ to the nearest integer
round(V,)
V
Rounds XYZ to argument 2's decimal precision
mod(V,)
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,,)
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,)
V
Combines vector 1's XYZ with vector 2's XYZ by a proportion given by argument 3 (between 0 and 1)
positive(V)
V
Returns a vector containing the positive value of each vector component, equivalent to abs()
V:length()
Gets the length of the vector
V:length2()
Gets the squared length of the vector
V:distance(V)
Gets the distance between vectors
V:distance2(V)
Gets the squared distance between vectors
V:normalized()
V
Gets the normalized vector
V:dot(V)
Gets the vector dot (scalar) product
V:x()
Gets the x component of the vector
V:y()
Gets the y component of the vector
V:z()
Gets the z component of the vector
V:w()
Gets the w component of the vector
V:setX()
V
Returns a copy of the vector with X replaced (use as Vec = Vec:setX(...))
V:setY()
V
Returns a copy of the vector with Y replaced (use as Vec = Vec:setY(...))
V:setZ()
V
Returns a copy of the vector with Z replaced (use as Vec = Vec:setZ(...))
V:setW()
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]"
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.
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(,)
M
Swaps the two rows specified
M:swapColumns(,)
M
Swaps the two columns specified
M:setRow(,,,)
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(,V)
M
Sets the values of a row. The first argument given specifies the row, the vector contains the values to set
M:setColumn(,,,)
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(,V)
M
Sets the values of a column. The first argument given specifies the column, the vector contains the values to set
M:setDiagonal(,,)
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 )
matrix(A)
M
Returns a 3x3 reference frame matrix as described by the angle A. Multiplying by this matrix will be the same as rotating by the given angle.
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,)
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.
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(,)
M4
Swaps the two rows specified
M4:swapColumns(,)
M4
Swaps the two columns specified
M4:setRow(,,,,)
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(,V4)
M4
Sets the values of a row. The first argument given specifies the row, the vector contains the values to set
M4:setColumn(,,,,)
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(,V4)
M4
Sets the values of a column. The first argument given specifies the column, the vector contains the values to set
M4:setDiagonal(,,,)
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)
matrix4(A)
M4
Returns a 4x4 reference frame matrix as described by the angle A. Multiplying by this matrix will be the same as rotating by the given angle.
matrix4(A,V)
M4
Returns a 4x4 reference frame matrix as described by the angle A and the position V. Multiplying by this matrix will be the same as rotating by the given angle and offsetting by the given vector.
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)
Функции, которые работают для матриц 2x2, 3x3 and 4x4. В данном случае написано для матриц 3*3, но применимы для матриц 2х2 и 4х4.
Операции возвращают вектора/матрицы того же размера. Например, функция row() возвращает 2D вектор.
Функция
Возвращает
Описание
M:row()
V
Возвращает строку, как вектор
M:column()
V
Возвращает столбец, как вектор
M:element(,)
Возвращает элемент с индексами(i,j)
M:setElement(,,)
M
Устанавливает значение элемента. Первые 2 аргумента - индексы (i,j), третий элемент - значение, которое надо вставить.
M:swapElements(,,,)
M
Меняет 2 элемента местами ( i1, j1, i2, j2 )
diagonal(M)
V
Returns a vector comprising the elements along the leading diagonal
trace(M)
Returns the trace of a matrix
det(M)
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.
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.
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().
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(), or R:pushString(S).
Function
Returns
Description
table()
T
Creates an empty table
T:clone()
T
Creates an independent copy of a table
T:count()
Returns the number of used indexes in the table
invert(R)
T
Returns a lookup table for R. Usage: Index = T:number(toString(Value)) Don't overuse this function, as it can become expensive for arrays with > 20 entries!
invert(T)
T
Returns a lookup table for T. Usage: Key = T:string(toString(Value)) Don't overuse this function, as it can become expensive for tables with > 10 entries!
T:<type>(S)
Retrieves the requested datatype element from the indexed string. Returns the default value for the datatype if the index is nil.
T:set<type>(S,*)
Saves the value as a table element with the specified index string
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.
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(), 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()
Returns the number of used indexes in the array
R:sum()
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()
Gives the average of all numbers in array
R:min()
Returns the smallest number in array
R:minIndex()
Returns the index of the smallest number in array
R:max()
Returns the largest number in array
R:maxIndex()
Returns the index of the largest number in array
R:<type>()
*
Retrieves the array element indexed with the number. Returns the default value for the datatype if the element is nil.
R:set<type>(,*)
Saves the datatype 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()
Deletes 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>(,*)
*
Inserts the data into the specified index; all entries after this index will move up to compensate
R:remove<type>()
*
Deletes and returns the specified entry, moving subsequent entries down to compensate
R:remove()
Deletes the specified entry, moving subsequent entries down to compensate
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.
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.
Equal and Not Equal operators are available.
XWL here means the Wirelink input.
Function
Returns
Description
XWL:isHiSpeed()
Returns true if the linked component is high-speed capable.
XWL:entity()
E
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:setNumber(S,)
Sets the component's input of the specified name equal to the number.
XWL:number(S)
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(,)
Writes the second argument to the memory cell specified by the first argument. Returns true if successful.
XWL:readCell()
Returns contents of the specified memory cell.
XWL:writeString(S,,)
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,,,)
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,,,,)
As above, with an extra argument for background colour. 3-digit RGB again.
XWL:writeString(S,,,,,)
As above, with an extra argument for flashing text. 0 or 1 is recommended.
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]
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)
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,)
Displays a hint popup with message S for seconds ( being clamped between 0.7 and 7)
print(S)
Posts string to chat
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.
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.
Timer functions are a way to trigger the expression to be run at a given time. Most interesting is the interval() function, that lets the expression be run continuously without needing triggering from inputs.
Returns the latency (Player:ping() for individual player)
isSinglePlayer()
Returns 1 if singleplayer, 0 if multiplayer
isDedicated()
Returns 1 if server is dedicated, 0 if listen
numPlayers()
Returns the number of players currently in the server
maxPlayers()
Returns the max number of players allowed in the server
maxOfType(S)
Returns the maximum allowed of a certain type of entity, i.e. maxOfType("wire_thrusters"). Returns 0 if you enter an invalid parameter.
playerDamage()
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)
Give a console command such as "sbox_godmode" and it returns the set value
time(S)
Returns numerical time/date info from the server. Possible arguments: "year", "month", "day", "hour", "min", "sec", "wday" (weekday, Sunday is 1), "yday" (day of the year), and "isdst" (daylight saving flag 0/1)
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.
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(), 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
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,)
Finds entities in a sphere around V with a radius of , returns the number found after filtering
findInCone(V,V,,A)
Like findInSphere but with a cone, arguments are for position, direction, length, and degrees (currently bugged, because the underlying function is bugged)
findInBox(V,V)
Like findInSphere but with a globally aligned box, the arguments are the diagonal corners of the box
findByame(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)
E
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()
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)
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,)
Filters the list of entities by removing all entities NOT within the specified sphere (center, radius)
findClipFromSphere(V,)
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 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.
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(,S)
Stores the string into the current group under the index specified by the number
gSetNum()
Stores a number into the current group, use with gGetNum()
gSetNum(S,)
Stores the number into the current group under the index specified by the string
gSetNum(,)
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()
S
Returns the string under the current group stored in the input number index, use with gSetStr(,S)
gGetNum()
Returns the number under the current group stored only by gSetNum()
gGetNum(S)
Returns the number under the current group stored in the input string index, use with gSetNum(S,)
gGetNum()
Returns the number under the current group stored in the input number index, use with gSetNum(,)
gDeleteStr()
S
Like gGetStr() but deletes the value after retrieval
gDeleteStr(S)
S
Like gGetStr(S) but deletes the value after retrieval
gDeleteStr()
S
Like gGetStr() but deletes the value after retrieval
gDeleteNum()
Like gGetNum() but deletes the value after retrieval
gDeleteNum(S)
Like gGetNum(S) but deletes the value after retrieval
gDeleteNum()
Like gGetNum() 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()
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()
gDeleteAll()
Deletes all of the global values stored under the current group, including the ones stored by gSetStr(S) and gSetNum()
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.
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 '\'.
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.
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,)
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,)
Same as above, but sets relationship to an entire class specified by the first string. Example: "npc_manhack", "prop_physics".
E:npcRelationshipByOwner(E,S,)
Sets the NPC's relationship to all currently existing NPCs owned by player E. Returns number of entities added to relationships.
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
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.
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, all other console commands are useable by admins only!
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.