# Wiki

Clone wiki# Core / vec4

**Back to Beyond the Codea in-app reference**

## vec4() function

### Introduction

The 'Vector' chapter of Codea's in-app reference documents most of the `vec4()`

function. The function is similar to the `vec3()`

function, except that it returns a userdata value that is a vector in four dimensions rather than three.

### Returning a four dimensional vector

The `vec4()`

function is used to return a new four-dimensional vector value as in the following examples:

```
v1 = vec4(x1, y1, z1, w1) -- x1, y1, z1, w1 contain numbers for the respective co-ordinates
print(vec4() == vec4(0, 0, 0, 1)) -- Output: true
```

If `vec4()`

is called without arguments it returns the origin in three-dimensional space, but in homogeneous co-ordinates (with the w co-ordinate equal to 1).

### Setting and getting individual coordinates

Indexing can be used to set and get individual coordinates, either by ordinal number or by letter - (x, y, z, w) or (r, g, b, a), as summarised in the table below:

Co-ordinate | Index scheme | Index scheme | Index scheme |
---|---|---|---|

First | `v1[1]` | `v1.x` or `v1["x"]` | `v1.r` or `v1["r"]` |

Second | `v1[2]` | `v1.y` or `v1["y"]` | `v1.g` or `v1["g"]` |

Third | `v1[3]` | `v1.z` or `v1["z"]` | `v1.b` or `v1["b"]` |

Fourth | `v1[4]` | `v1.w` or `v1["w"]` | `v1.a` or `v1["a"]` |

### Operators

As in the case of `vec3()`

, the result of the `vec4()`

function supports the `-`

(uniary), `*`

, `/`

, `+`

, `-`

, and `==`

operators, where the second operand is a number value in the case of `*`

(multiplication by a scalar) and `/`

(division by a scalar).

### Functions

The result also supports `tostring()`

to produce nicely-formatted output. Consequently, `print()`

also generates nicely-formatted output.

Also as in the case of `vec3()`

, the result of the `vec4()`

function supports the indexed functions `dot()`

, `cross()`

, `len()`

, `lenSqr()`

, `dist()`

and `distSqr()`

. For example:

```
v1 = vec4(1, -1, 3, 4)
v2 = vec4(-2, 5, -3, 0)
-- Calculate the dot (scalar) product of two vectors
d = v1.dot(v1, v2) -- This syntax is equivalent ...
d = v1:dot(v2) -- ... to this syntax, using Lua's colon notation.
-- Calculate the length (magnitude) of first vector
l = v1.len(v1) -- This syntax is equivalent ...
l = v1:len() -- ... to this syntax, using Lua's colon notation.
```

#### v1:cross(v2)

The `cross()`

function returns a four dimensional vector where the first three co-ordinates are the cross product of the three dimensional vectors corresponding to the first three co-ordinates of the two vectors and the fourth co-ordinate is `0`

.

Updated