Skip to content

Commit

Permalink
Add table.shuffle (#8299)
Browse files Browse the repository at this point in the history
  • Loading branch information
HybridDog authored Feb 1, 2020
1 parent 2b3490d commit ea5e231
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
14 changes: 14 additions & 0 deletions builtin/common/misc_helpers.lua
Original file line number Diff line number Diff line change
Expand Up @@ -576,6 +576,20 @@ function table.key_value_swap(t)
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


--------------------------------------------------------------------------------
-- mainmenu only functions
--------------------------------------------------------------------------------
Expand Down
7 changes: 7 additions & 0 deletions doc/lua_api.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2925,6 +2925,13 @@ Helper functions
find new indices.
* `table.key_value_swap(t)`: returns a table with keys and values swapped
* If multiple keys in `t` map to the same value, the result is undefined.
* `table.shuffle(table, [from], [to], [random_func])`:
* Shuffles elements `from` to `to` in `table` in place
* `from` defaults to `1`
* `to` defaults to `#table`
* `random_func` defaults to `math.random`. This function receives two
integers as arguments and should return a random integer inclusively
between them.
* `minetest.pointed_thing_to_face_pos(placer, pointed_thing)`: returns a
position.
* returns the exact position on the surface of a pointed node
Expand Down

0 comments on commit ea5e231

Please sign in to comment.