Skip to content

Commit ea5e231

Browse files
authoredFeb 1, 2020
Add table.shuffle (#8299)
1 parent 2b3490d commit ea5e231

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed
 

Diff for: ‎builtin/common/misc_helpers.lua

+14
Original file line numberDiff line numberDiff line change
@@ -576,6 +576,20 @@ function table.key_value_swap(t)
576576
end
577577

578578

579+
function table.shuffle(t, from, to, random)
580+
from = from or 1
581+
to = to or #t
582+
random = random or math.random
583+
local n = to - from + 1
584+
while n > 1 do
585+
local r = from + n-1
586+
local l = from + random(0, n-1)
587+
t[l], t[r] = t[r], t[l]
588+
n = n-1
589+
end
590+
end
591+
592+
579593
--------------------------------------------------------------------------------
580594
-- mainmenu only functions
581595
--------------------------------------------------------------------------------

Diff for: ‎doc/lua_api.txt

+7
Original file line numberDiff line numberDiff line change
@@ -2925,6 +2925,13 @@ Helper functions
29252925
find new indices.
29262926
* `table.key_value_swap(t)`: returns a table with keys and values swapped
29272927
* If multiple keys in `t` map to the same value, the result is undefined.
2928+
* `table.shuffle(table, [from], [to], [random_func])`:
2929+
* Shuffles elements `from` to `to` in `table` in place
2930+
* `from` defaults to `1`
2931+
* `to` defaults to `#table`
2932+
* `random_func` defaults to `math.random`. This function receives two
2933+
integers as arguments and should return a random integer inclusively
2934+
between them.
29282935
* `minetest.pointed_thing_to_face_pos(placer, pointed_thing)`: returns a
29292936
position.
29302937
* returns the exact position on the surface of a pointed node

0 commit comments

Comments
 (0)
Please sign in to comment.