Weighted List

A weighted list is an expanded table object allowing for semi-random selection of items from the table based on their preset weighting set when adding the item

Loaded in Campaign loaded in campaign
Back to top

Example Usage

Example - Creating, Inserting and Extracting:

The following creates a new weighted list, adds some items to it, and then retrieves a semi-random item from the list taking into account the weighting of the objects
local new_list = weighted_list:new();
new_list:add_item("Bob", 5);
new_list:add_item("John", 5);
new_list:add_item("Steve", 10);

local result = new_list:weighted_select();

-- Effective chance of each item being selected: Bob 25%, John 25%, Steve 50%
Back to top

Creation

weighted_list:new([table o])

Creates a new weighted list object

Parameters:

1

table

optional, default value=nil

Pass an object to the new function to use that instance of the object as this new one

Returns:

  1. weighted_list the new weighted list object

defined in ../working_data/script/_lib/lib_weighted_list.lua, line 35

Back to top

Adding & Removing

weighted_list:add_item(object item, number weight)

Allows adding of new items to the weighted list with a set weighting

Parameters:

1

object

The item to add to the list

2

number

The weight of this item

Returns:

  1. nil

defined in ../working_data/script/_lib/lib_weighted_list.lua, line 49

weighted_list:remove_item(number i)

Allows removal of an item from the weighted list

Parameters:

1

number

The index of the item to remove

Returns:

  1. nil

defined in ../working_data/script/_lib/lib_weighted_list.lua, line 63

Back to top

Selection

weighted_list:weighted_select()

Selects an item from the weighted list with the chance of each item
being selected being their weight relative to all other items

Returns:

  1. object the selected item

defined in ../working_data/script/_lib/lib_weighted_list.lua, line 72

weighted_list:random_select()

Randomly selects an item from the weighted list disregarding any weighting

Returns:

  1. object the selected item

defined in ../working_data/script/_lib/lib_weighted_list.lua, line 88

Last updated 07/02/21 06:39:14