Skip to content

Commit 3560691

Browse files
authoredApr 1, 2021
Add math.round and fix vector.round (#10803)
1 parent 1e4913c commit 3560691

File tree

4 files changed

+16
-4
lines changed

4 files changed

+16
-4
lines changed
 

‎.luacheckrc

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ read_globals = {
2020

2121
string = {fields = {"split", "trim"}},
2222
table = {fields = {"copy", "getn", "indexof", "insert_all"}},
23-
math = {fields = {"hypot"}},
23+
math = {fields = {"hypot", "round"}},
2424
}
2525

2626
globals = {

‎builtin/common/misc_helpers.lua

+9
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,15 @@ function math.factorial(x)
244244
return v
245245
end
246246

247+
248+
function math.round(x)
249+
if x >= 0 then
250+
return math.floor(x + 0.5)
251+
end
252+
return math.ceil(x - 0.5)
253+
end
254+
255+
247256
function core.formspec_escape(text)
248257
if text ~= nil then
249258
text = string.gsub(text,"\\","\\\\")

‎builtin/common/vector.lua

+3-3
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,9 @@ end
4141

4242
function vector.round(v)
4343
return {
44-
x = math.floor(v.x + 0.5),
45-
y = math.floor(v.y + 0.5),
46-
z = math.floor(v.z + 0.5)
44+
x = math.round(v.x),
45+
y = math.round(v.y),
46+
z = math.round(v.z)
4747
}
4848
end
4949

‎doc/lua_api.txt

+3
Original file line numberDiff line numberDiff line change
@@ -3163,6 +3163,7 @@ For the following functions, `v`, `v1`, `v2` are vectors,
31633163
* Returns a vector, each dimension rounded down.
31643164
* `vector.round(v)`:
31653165
* Returns a vector, each dimension rounded to nearest integer.
3166+
* At a multiple of 0.5, rounds away from zero.
31663167
* `vector.apply(v, func)`:
31673168
* Returns a vector where the function `func` has been applied to each
31683169
component.
@@ -3237,6 +3238,8 @@ Helper functions
32373238
* If the absolute value of `x` is within the `tolerance` or `x` is NaN,
32383239
`0` is returned.
32393240
* `math.factorial(x)`: returns the factorial of `x`
3241+
* `math.round(x)`: Returns `x` rounded to the nearest integer.
3242+
* At a multiple of 0.5, rounds away from zero.
32403243
* `string.split(str, separator, include_empty, max_splits, sep_is_pattern)`
32413244
* `separator`: string, default: `","`
32423245
* `include_empty`: boolean, default: `false`

0 commit comments

Comments
 (0)