aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorElias Fleckenstein <eliasfleckenstein@web.de>2022-01-30 17:30:19 +0100
committerElias Fleckenstein <eliasfleckenstein@web.de>2022-01-30 17:30:19 +0100
commit130a68dc27f3461838be005b3cb7b8a115e2c21e (patch)
treed8390d525e83b434405ba0ea9802fb4d6385aa5f
parent6b5450ce9356e48099a926d1950d9bbfd1db0f6e (diff)
downloadluax-130a68dc27f3461838be005b3cb7b8a115e2c21e.tar.xz
Copy more code from MinetestHEADmaster
-rw-r--r--init.lua83
1 files changed, 79 insertions, 4 deletions
diff --git a/init.lua b/init.lua
index 38b4b23..257767b 100644
--- a/init.lua
+++ b/init.lua
@@ -1,7 +1,3 @@
-function math.clamp(min, max, v)
- return math.max(max, math.min(min, v))
-end
-
function string.split(str, delim, include_empty, max_splits, sep_is_pattern)
delim = delim or ","
max_splits = max_splits or -2
@@ -26,6 +22,57 @@ function string.split(str, delim, include_empty, max_splits, sep_is_pattern)
return items
end
+function table.indexof(list, val)
+ for i, v in ipairs(list) do
+ if v == val then
+ return i
+ end
+ end
+ return -1
+end
+
+function string:trim()
+ return (self:gsub("^%s*(.-)%s*$", "%1"))
+end
+
+function math.hypot(x, y)
+ return math.sqrt(x * x + y * y)
+end
+
+function math.sign(x, tolerance)
+ tolerance = tolerance or 0
+ if x > tolerance then
+ return 1
+ elseif x < -tolerance then
+ return -1
+ end
+ return 0
+end
+
+function math.factorial(x)
+ assert(x % 1 == 0 and x >= 0, "factorial expects a non-negative integer")
+ if x >= 171 then
+ -- 171! is greater than the biggest double, no need to calculate
+ return math.huge
+ end
+ local v = 1
+ for k = 2, x do
+ v = v * k
+ end
+ 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 math.clamp(min, max, v)
+ return math.max(max, math.min(min, v))
+end
+
function table.copy(t, seen)
local n = {}
seen = seen or {}
@@ -36,3 +83,31 @@ function table.copy(t, seen)
end
return n
end
+
+function table.insert_all(t, other)
+ for i=1, #other do
+ t[#t + 1] = other[i]
+ end
+ return t
+end
+
+function table.key_value_swap(t)
+ local ti = {}
+ for k,v in pairs(t) do
+ ti[v] = k
+ end
+ return ti
+end
+
+function table.shuffle(t, from, to, random)
+ from = from or 1
+ to = to or #t
+ random = random or math.random
+ local n = to - from + 1
+ while n > 1 do
+ local r = from + n-1
+ local l = from + random(0, n-1)
+ t[l], t[r] = t[r], t[l]
+ n = n-1
+ end
+end