Skip to content

Commit

Permalink
Add math.round and fix vector.round (#10803)
Browse files Browse the repository at this point in the history
  • Loading branch information
v-rob committed Apr 1, 2021
1 parent 1e4913c commit 3560691
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 4 deletions.
2 changes: 1 addition & 1 deletion .luacheckrc
Expand Up @@ -20,7 +20,7 @@ read_globals = {

string = {fields = {"split", "trim"}},
table = {fields = {"copy", "getn", "indexof", "insert_all"}},
math = {fields = {"hypot"}},
math = {fields = {"hypot", "round"}},
}

globals = {
Expand Down
9 changes: 9 additions & 0 deletions builtin/common/misc_helpers.lua
Expand Up @@ -244,6 +244,15 @@ function math.factorial(x)
return v
end


function math.round(x)
if x >= 0 then
return math.floor(x + 0.5)
end
return math.ceil(x - 0.5)
end


function core.formspec_escape(text)
if text ~= nil then
text = string.gsub(text,"\\","\\\\")
Expand Down
6 changes: 3 additions & 3 deletions builtin/common/vector.lua
Expand Up @@ -41,9 +41,9 @@ end

function vector.round(v)
return {
x = math.floor(v.x + 0.5),
y = math.floor(v.y + 0.5),
z = math.floor(v.z + 0.5)
x = math.round(v.x),
y = math.round(v.y),
z = math.round(v.z)
}
end

Expand Down
3 changes: 3 additions & 0 deletions doc/lua_api.txt
Expand Up @@ -3163,6 +3163,7 @@ For the following functions, `v`, `v1`, `v2` are vectors,
* Returns a vector, each dimension rounded down.
* `vector.round(v)`:
* Returns a vector, each dimension rounded to nearest integer.
* At a multiple of 0.5, rounds away from zero.
* `vector.apply(v, func)`:
* Returns a vector where the function `func` has been applied to each
component.
Expand Down Expand Up @@ -3237,6 +3238,8 @@ Helper functions
* If the absolute value of `x` is within the `tolerance` or `x` is NaN,
`0` is returned.
* `math.factorial(x)`: returns the factorial of `x`
* `math.round(x)`: Returns `x` rounded to the nearest integer.
* At a multiple of 0.5, rounds away from zero.
* `string.split(str, separator, include_empty, max_splits, sep_is_pattern)`
* `separator`: string, default: `","`
* `include_empty`: boolean, default: `false`
Expand Down

0 comments on commit 3560691

Please sign in to comment.