Difference between revisions of "LuaAPI/mathx"
(Document the mathx module) |
m (Fix an incorrect header) |
||
Line 45: | Line 45: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | ==== | + | ==== mathx.shuffle ==== |
* '''mathx.shuffle'''(''array'', [''random function'']) | * '''mathx.shuffle'''(''array'', [''random function'']) |
Revision as of 03:39, 6 February 2023
mathx.random
- mathx.random([m, [n]]) → random number
This function returns a random number generated by the synced random generator, which is also used by [set_variable]rand=. This function has the same interface as math.random so it can take 0, 1 or 2 arguments.
In map generation scripts, the values returned by this function depend on the seed the map author has input (if any).
Be careful as random is not safe in certain events, see Multiplayer_safety.
mathx.random_choice
- mathx.random_choice(spec) → choice
Chooses a random element from its input. The input can be a string (as set_variable's rand=), in which case it will be split on commas and consider integer ranges; or it can be a Lua array, in which case the elements can be either simple values or a table of two integers, representing a range.
-- create a random unit at (1, 1) on side=1 :
wesnoth.units.to_map{
type = mathx.random_choice{"Dwarvish Fighter", "Dwarvish Thunderer", "Dwarvish Scout"}
x = 1, y = 1
}
Note that random_choice is only safe in certain events, see Multiplayer Safety.
mathx.round
- mathx.round(n) → number
Rounds a number to the nearest integer, using the "round half away from zero" method (see here for a more detailed explanation).
-- this number will be rounded up
mathx.round(345.67) -- returns 346
-- this one will be rounded down
mathx.round(543.21) -- returns 543
-- an integer stays integer
mathx.round(123) -- returns 123
-- works also for negative numbers
mathx.round(-369.84) -- returns -370
mathx.round(-246.42) -- returns -246
mathx.shuffle
- mathx.shuffle(array, [random function])
This function randomly sorts in place the elements of the table passed as argument, following the Fisher-Yates algorithm. It returns no value.
local locs = wesnoth.map.find{ terrain="G*" }
mathx.shuffle(locs)
This function uses the synced RNG (mathx.random) by default and should not cause out-of-sync errors. It is also possible to pass a different random generator as a second argument; a random generator is a function that takes two integers a and b and returns a random integer in the range [a,b]. For example, math.random can be passed if you need unsynced random calls (for example because it's used for user interface code):
local locs = wesnoth.map.find{ terrain="G*" }
mathx.shuffle(locs, math.random)