Stats

This is a simple utility package for tracking stats on an entity. This is a scripting package, it contains no UI.

Installation

  • Install the “Stats” package
  • Drop the Stats template on whatever you want to have stats

There’s a “Level” stat already added to the Stats template to give you an idea how to set it up.

Usage

There are 2 scripts in the package statsScript and statScript. statsScript is primarily used for managing multiple stats when an entity has multiple statScript.

API

statsScript

StatName(id)

Return the stat name for the given ID

GetStat(id)

Returns the statScript for the given ID

GetStats()

This method will return a table such that each key is the ID of a stat on the entity, and the value is the statScript

Sum()

Returns the sum of all levels of the stats. Useful for giving entities a “meta-level”. For example, your level in Runescape is the sum of all skill levels.

AddXp(id, amt)

Add the specified amount of xp to the specified stat. If the XP can be added, calls the onStatChange event.

Returns true or false depending on if the call was successful or not. A call can fail if the XP would put the stat over the level limit.

statScript

Name()

Returns the name of the stat

XpForLevel(level)

Called with a level returns the amount of XP required to reach that level.

Level()

Returns the current level of the stat, based on its current XP

CurrentXp()

Returns the current XP for the stat

PercentToNextLevel()

Returns a float between 0 and 1 representing the progress towards the next level

RequiredXp()

Returns the amount of XP required for the next level

AddXp(amt)

If the stat is below max level, adds the specified amount of XP to the stat

Load(table)

When passed a table, uses the xp key to set the xp property.

ToTable()

Returns the stat in table format, containing the keys xp, name, and id.

Additional Info

Integrating with Save Data

This package intentionally doesn’t integrate with save data because of the frequency you might use this on a world entity.

If you want to integrate it with save data, it’s fairly simple.

Create a new script on your user saveStatsScript, and enter the following methods. Assign the HandleStatChange method to the onStatChange event on the statsScript and use AddXp on statsScript to handle adding xp.

-- On Init, load any saved stats
function SaveStatsScript:Init()
  local statsScript = self:GetEntity().statsScript

  local data = self:GetSaveData()
  data.stats = data.stats or {}

  for id, record in ipairs(data.stats) do 
    local stat = statsScript:GetStat(id)
    if stat then 
      stat:Load(record)  
    end
  end
end 

-- When a stat changes, save it to save data
function SaveStatsScript:HandleStatChange(entity, statId, xp, stat)
  local data = self:GetSaveData()

  data.stats = data.stats or {}
  data.stats[statId] = stat:ToTable()

  self:SetSaveData(data)
end