Skip to content

tes3⚓︎

The tes3 library provides the majority of the functions for interacting with the game system.

Properties⚓︎

tes3.bsaLoader⚓︎

One of the core game objects, responsible for loaded BSA files.

Returns:


tes3.dataHandler⚓︎

One of the core game objects.

Returns:


tes3.game⚓︎

One of the core game objects.

Returns:


tes3.installDirectory⚓︎

The currently executed root Morrowind installation path (The folder containing Morrowind.exe).

Returns:

  • result (string)

tes3.magicSchoolSkill⚓︎

This table is used to convert numerical magic school IDs to their respective skill IDs. These constants will return their respective tes3.skill constants.

Returns:

Example: Convert magic school from event data to a respective skill

The example below gives the player 100 experience for failing to cast a spell. Here we can see how tes3.magicSchoolSkill is used.

local function OnSpellFailed(e)

    local skill = tes3.magicSchoolSkill[e.expGainSchool] -- Note: e.expGainSchool is a value in tes3.magicSchool constants table

    tes3.mobilePlayer:exerciseSkill(skill, 100)
end

event.register(tes3.event.spellCastedFailure, OnSpellFailed)

tes3.mobilePlayer⚓︎

The player's mobile actor.

Returns:


tes3.player⚓︎

A reference to the player.

Returns:


tes3.player1stPerson⚓︎

A reference used for the player's first person hands.

Returns:


tes3.worldController⚓︎

One of the core game objects.

Returns:


Functions⚓︎

tes3.addArmorSlot⚓︎

Registers a new armor slot. Adds a new place for armor pieces with a matching slot number to equip to.

local wasAdded = tes3.addArmorSlot({ slot = ..., name = ..., key = ..., weight = ..., scalar = ... })

Parameters:

  • params (table)
    • slot (number): Armor slot number. A number greater than 10 to configure a slot for.
    • name (string): The human-readable name for the armor slot.
    • key (string): Optional. The key placed in the tes3.armorSlot table. If no key is provided, the name will be used.
    • weight (number): Default: 0. A stand-in for the armor base weight value, typically controlled by a GMST (e.g. iHelmWeight).
    • scalar (number): Default: 0.1. A multiplier with range 0.0-1.0 that controls how much of an item's armor value applies to a character's overall armor rating. For comparison, standard chest armor uses 0.3, helmets, greaves and pauldrons use 0.1, and gauntlets use 0.05.

Returns:

  • wasAdded (boolean)

tes3.addClothingSlot⚓︎

Registers a new clothing slot. Adds a new place for clothing pieces with a matching slot number to equip to.

tes3.addClothingSlot({ slot = ..., name = ..., key = ... })

Parameters:

  • params (table)
    • slot (number): Clothing slot number. A number greater than 9 to configure a slot for.
    • name (string): The human-readable name for the clothing slot.
    • key (string): Optional. The key placed in the tes3.clothingSlot table. If no key is provided, the name will be used.

tes3.addItem⚓︎

Adds an item to a given reference's inventory or mobile's inventory. The reference will be cloned if needed.

local addedCount = tes3.addItem({ reference = ..., item = ..., itemData = ..., soul = ..., count = ..., playSound = ..., showMessage = ..., limit = ..., reevaluateEquipment = ..., equipProjectiles = ..., updateGUI = ... })

Parameters:

  • params (table)
    • reference (tes3reference, tes3mobileActor, string): Who to give items to.
    • item (tes3item, tes3leveledItem, string): The item to add. If a leveled item is passed, it will be resolved and added.
    • itemData (tes3itemData): Optional. The item data for the item.
    • soul (tes3creature, tes3npc): Optional. For creating filled soul gems.
    • count (number): Default: 1. The maximum number of items to add.
    • playSound (boolean): Default: true. If false, the up/down sound for the item won't be played. This only applies if reference is the player.
    • showMessage (boolean): Default: false. If true, a message box notifying the player will be shown. This only applies if reference is the player.
    • limit (boolean): Default: false. If false, items can be placed into containers that shouldn't normally be allowed. This includes organic containers, and containers that are full.
    • reevaluateEquipment (boolean): Default: true. If true, and the item added is armor, clothing, or a weapon, the actor will reevaluate its equipment choices to see if the new item is worth equipping. This does not affect the player.
    • equipProjectiles (boolean): Default: true. If true, and the reference has the same projectile already equipped, the stacks will be merged. This will only work if the GUI is updated.
    • updateGUI (boolean): Default: true. If false, the function won't manually resync the player's GUI state. This can result in some optimizations, though tes3ui.forcePlayerInventoryUpdate() must manually be called after all inventory updates are finished.

Returns:

  • addedCount (number)

tes3.addItemData⚓︎

Creates an item data if there is room for a new stack in a given inventory. This can be then used to add custom user data or adjust an item's condition. This will return nil if no item data could be allocated for the item -- for example if the reference doesn't have the item in their inventory or each item of that type already has item data. Calling this function will mark the to reference as modified.

local createdData = tes3.addItemData({ to = ..., item = ..., updateGUI = ... })

Parameters:

  • params (table)
    • to (tes3reference, tes3mobileActor, string): The reference or mobile whose inventory will be modified.
    • item (tes3item, string): The item to create item data for.
    • updateGUI (boolean): Default: true. If false, the player or contents menu won't be updated.

Returns:


tes3.addJournalEntry⚓︎

This function creates a new journal entry. It can be called once the world controller is loaded.

The text uses the same HTML-style formatting as books, which has different layout to regular dialogue. Use <BR> for line breaks that can span pages instead of \\n.

tes3.addJournalEntry({ text = ..., showMessage = ... })

Parameters:

  • params (table)
    • text (string): The text of the new Journal entry.
    • showMessage (boolean): Default: true. If this parameter is true, a "Your journal has been updated" message will be displayed.

tes3.addMagicEffect⚓︎

This function creates a new custom magic effect. The effect can be scripted through lua. This function should be used inside magicEffectsResolved event callback.

local effect = tes3.addMagicEffect({ id = ..., name = ..., baseCost = ..., school = ..., size = ..., sizeCap = ..., speed = ..., description = ..., lighting = ..., icon = ..., particleTexture = ..., castSound = ..., boltSound = ..., hitSound = ..., areaSound = ..., castVFX = ..., boltVFX = ..., hitVFX = ..., areaVFX = ..., allowEnchanting = ..., allowSpellmaking = ..., appliesOnce = ..., canCastSelf = ..., canCastTarget = ..., canCastTouch = ..., casterLinked = ..., hasContinuousVFX = ..., hasNoDuration = ..., hasNoMagnitude = ..., illegalDaedra = ..., isHarmful = ..., nonRecastable = ..., targetsAttributes = ..., targetsSkills = ..., unreflectable = ..., usesNegativeLighting = ..., onTick = ..., onCollision = ... })

Parameters:

  • params (table)
    • id (tes3.effect, integer): Id of the new effect. Maps to newly claimed tes3.effect constants with tes3.claimSpellEffectId(). If the effect of this id already exists, an error will be thrown.
    • name (string): Default: Unnamed Effect. Name of the effect.
    • baseCost (number): Default: 1. Base magicka cost for the effect.
    • school (tes3.magicSchool, integer): Default: tes3.magicSchool.alteration. The magic school the new effect will be assigned to. Maps to tes3.magicSchool constants.
    • size (number): Default: 1. Controls how much the visual effect scales with its magnitude.
    • sizeCap (number): Default: 1. The maximum possible size of the projectile.
    • speed (number): Default: 1.
    • description (string): Default: No description available.. Description for the effect.
    • lighting (table): Optional.
      • x (number): Default: 1. Value of red color channel. In range of 0 - 1.
      • y (number): Default: 1. Value of green color channel. In range of 0 - 1.
      • z (number): Default: 1. Value of blue color channel. In range of 0 - 1.
    • icon (string): Path to the effect icon. Must be a string no longer than 31 characters long. Use double as path separator.
    • particleTexture (string): Path to the particle texture to use for the effect. Must be a string no longer than 31 characters long.
    • castSound (string): The sound ID which will be played on casting a spell with this effect. Must be a string no longer than 31 characters long. If not specified, the default sound for the spell school will be used.
    • boltSound (string): The sound ID which will be played when a spell with this effect is in flight. Must be a string no longer than 31 characters long. If not specified, the default sound for the spell school will be used.
    • hitSound (string): The sound ID which will be played when a spell with this effect hits something. Must be a string no longer than 31 characters long. If not specified, the default sound for the spell school will be used.
    • areaSound (string): The sound ID which will be played on area of effect impact. Must be a string no longer than 31 characters long. If not specified, the default sound for the spell school will be used.
    • castVFX (tes3physicalObject, string): Optional. The visual played when a spell with this effect is cast.
    • boltVFX (tes3physicalObject, string): Optional. The visual played when a spell with this effect is in flight.
    • hitVFX (tes3physicalObject, string): Optional. The visual played when a spell with this effect hits something.
    • areaVFX (tes3physicalObject, string): Optional. The visual played when a spell with this effect, with area of effect hits something.
    • allowEnchanting (boolean): Default: true. A flag which controls whether this effect can be used in a custom enchantment.
    • allowSpellmaking (boolean): Default: true. A flag which controls whether this effect can be used in a custom spell.
    • appliesOnce (boolean): Default: true. A flag which controls whether this effect applies once or is a ticking effect.
    • canCastSelf (boolean): Default: true. A flag which controls whether this effect can be used with cast on self range.
    • canCastTarget (boolean): Default: true. A flag which controls whether this effect can be used with cast on target range.
    • canCastTouch (boolean): Default: true. A flag which controls whether this effect can be used with cast on touch range.
    • casterLinked (boolean): Default: true. Access to the base flag that determines if this effect must end if caster is dead, or not an NPC/creature. Not allowed in container or door trap spells. Note that this property is hidden in the Construction Set.
    • hasContinuousVFX (boolean): Default: true. A flag which controls whether the effect's visual is continuously played during the whole duration of the effect.
    • hasNoDuration (boolean): Default: true. A flag which controls whether this effect doesn't have duration.
    • hasNoMagnitude (boolean): Default: true. A flag which controls whether this effect doesn't have magnitude.
    • illegalDaedra (boolean): Default: true. A flag which controls whether this effect is illegal to use in public, because it summons Daedra. Note: this mechanic is not implemented in the game. Some mods might rely on this parameter.
    • isHarmful (boolean): Default: true. A flag which controls whether this effect is considered harmful and casting it can be considered as an attack.
    • nonRecastable (boolean): Default: true. A flag which controls whether this effect can be recast while it already is in duration.
    • targetsAttributes (boolean): Default: true. A flag which controls whether this effect targets a certain attribute or attributes.
    • targetsSkills (boolean): Default: true. A flag which controls whether this effect targets a certain skill or skills.
    • unreflectable (boolean): Default: true. A flag which controls whether this effect can be reflected.
    • usesNegativeLighting (boolean): Default: true. A flag which controls whether this effect uses negative lighting.
    • onTick (fun(e: tes3magicEffectTickEventData)): Optional. A function which will be called on each tick of a spell containing this effect. Note: dt (frame time) scaling is handled automatically. This function typically calls e:trigger() to run the effect through the normal spell event system.
    • onCollision (fun(e: tes3magicEffectCollisionEventData)): Optional. A function which will be called when a spell containing this spell effect collides with something.

Returns:

Example: Fire Damage effect

An implementation of the vanilla Fire Damage effect. Also, three spells are constructed with newly created magic effect, which are added to the player. You can test this in-game.

-- Claiming an ID is needed before actually
-- creating an effect with that ID
tes3.claimSpellEffectId("customFireDmg", 220)

---@param tickParams tes3magicEffectTickEventData
local function onFireDmgTick(tickParams)
    local target = tickParams.effectInstance.target
    local targetHealth = target.mobile.health
    -- This will print current health for any actor our spell hit,
    -- so we can see if it works as expected
    tes3.messageBox(
        "%s, health: %s",
        target.object.id,
        targetHealth.current
    )

    tickParams:trigger({
        type = tes3.effectEventType.modStatistic,
        -- The resistance attribute against Fire Damage should be Resist Fire
        attribute = tes3.effectAttribute.resistFire,

        -- The variable this effect affects
        value = targetHealth,
        negateOnExpiry = false,
        isUncapped = true,
    })
end

event.register(tes3.event.magicEffectsResolved, function()
    tes3.addMagicEffect({
        -- The ID we claimed before is now available in tes3.effect namespace
        id = tes3.effect.customFireDmg,

        -- This information is copied from the Construction Set
        name = "Fire Damage",
        description = ("This spell effect produces a manifestation of elemental fire. Upon " ..
        "contact with an object, this manifestation explodes, causing damage."),
        baseCost = 5,
        school = tes3.magicSchool.destruction,
        size = 1.25,
        sizeCap = 50,
        speed = 1,
        lighting = { x = 0.99, y = 0.26, z = 0.53 },
        usesNegativeLighting = false,

        icon = "s\\Tx_S_fire_damage.tga",
        particleTexture = "vfx_firealpha00A.tga",
        castSound = "destruction cast",
        castVFX = "VFX_DestructCast",
        boltSound = "destruction bolt",
        boltVFX = "VFX_DestructBolt",
        hitSound = "destruction hit",
        hitVFX = "VFX_DestructHit",
        areaSound = "destruction area",
        areaVFX = "VFX_DestructArea",

        appliesOnce = false,
        hasNoDuration = false,
        hasNoMagnitude = false,
        illegalDaedra = false,
        unreflectable = false,
        casterLinked = false,
        nonRecastable = false,
        targetsAttributes = false,
        targetsSkills = false,

        onTick = onFireDmgTick,
    })
end)

event.register(tes3.event.loaded, function()

    -- Now let's create some custom spells to test the new effect.

    local spell1 = tes3.createObject({ objectType = tes3.objectType.spell }) --[[@as tes3spell]]
    tes3.setSourceless(spell1)
    spell1.name = "TEST SPELL - self"
    spell1.magickaCost = 1

    local effect = spell1.effects[1]
    effect.id = tes3.effect.customFireDmg
    effect.rangeType = tes3.effectRange.self
    effect.min = 10
    effect.max = 10
    effect.duration = 10
    effect.radius = 0
    effect.skill = -1
    effect.attribute = -1

    local spell2 = tes3.createObject({ objectType = tes3.objectType.spell }) --[[@as tes3spell]]
    tes3.setSourceless(spell2)
    spell2.name = "TEST SPELL - target"
    spell2.magickaCost = 1

    local effect = spell2.effects[1]
    effect.id = tes3.effect.customFireDmg
    effect.rangeType = tes3.effectRange.target
    effect.min = 3
    effect.max = 3
    effect.duration = 10
    effect.radius = 15
    effect.skill = -1
    effect.attribute = -1

    local spell3 = tes3.createObject({ objectType = tes3.objectType.spell }) --[[@as tes3spell]]
    tes3.setSourceless(spell3)
    spell3.name = "TEST SPELL - touch"
    spell3.magickaCost = 1

    local effect = spell3.effects[1]
    effect.id = tes3.effect.customFireDmg
    effect.rangeType = tes3.effectRange.touch
    effect.min = 3
    effect.max = 3
    effect.duration = 10
    effect.radius = 0
    effect.skill = -1
    effect.attribute = -1

    tes3.addSpell({ reference = tes3.mobilePlayer, spell = spell1 })
    tes3.addSpell({ reference = tes3.mobilePlayer, spell = spell2 })
    tes3.addSpell({ reference = tes3.mobilePlayer, spell = spell3 })
end)

tes3.addSoulGem⚓︎

Causes a misc item to be recognized as a soul gem, so that it can be used for soul trapping.

local wasAdded = tes3.addSoulGem({ item = ... })

Parameters:

  • params (table)
    • item (tes3misc, string): The item to recognize as a soul gem.

Returns:

  • wasAdded (boolean)
Example: Make Dwemer Tubes be treated as Soul gems. Also, make sure Fargoth's soul always ends up in one if the player has one avilable.
local function onInitialized()
    tes3.addSoulGem({ item = "misc_dwrv_artifact60" })
end
event.register(tes3.event.initialized, onInitialized)

local function onFilterSoulGemTarget(e)
    if (e.reference.baseObject.id:lower() == "fargoth") then
        return e.soulGem.id == "misc_dwrv_artifact60"
    end
end
event.register(tes3.event.filterSoulGemTarget, onFilterSoulGemTarget)

-- calcSoulValue event allows assigning a new soul value to creatures
-- If the event was triggered for an NPC, it allows assigning a value
-- thus allowing soul-trapping the actor.
local function calcSoulValueCallback(e)
    if (e.actor.id:lower() == "fargoth") then
        e.value = 69
        mwse.log("Getting Fargoth's value.")
        return
    end
end
event.register(tes3.event.calcSoulValue, calcSoulValueCallback)

tes3.addSpell⚓︎

Adds a spell to an actor's spell list. If the spell is passive, the effects will be applied. At least one of the actor, mobile or reference arguments needs to be passed.

local wasAdded = tes3.addSpell({ reference = ..., actor = ..., mobile = ..., spell = ..., updateGUI = ..., bypassResistances = ... })

Parameters:

  • params (table)
    • reference (tes3reference, tes3mobileActor, string): Optional. Who to give the spell to. To manipulate an actor without specifying any particular reference, use actor instead.
    • actor (tes3actor, string): Optional. Who to give the spell to. Providing a base actor can be done before a save has been loaded, but may not correctly update effects for instanced versions of that actor in an active save.
    • mobile (tes3reference, tes3mobileActor, string): Optional. Who to give the spell to. To manipulate an actor without specifying any particular reference, use actor instead.
    • spell (tes3spell, string): The spell to add.
    • updateGUI (boolean): Default: true. If true, the GUI will be updated respecting the adding of the spell. This can be useful to disable when batch-adding many spells. The batch should be ended with tes3.updateMagicGUI to reflect the changes.
    • bypassResistances (boolean): Default: true. Should the resistances be bypassed when applying the spell?

Returns:

  • wasAdded (boolean): True if the spell was successfully added. This can be false if the actor's race or birthsign already contains the spell.

tes3.addTopic⚓︎

Adds a topic to the valid topic list for the player. This doesn't create a dynamic new topic.

local wasAdded = tes3.addTopic({ topic = ..., updateGUI = ... })

Parameters:

  • params (table)
    • topic (tes3dialogue, string): The topic to add
    • updateGUI (boolean): Default: true. If true, the GUI will be updated respecting the adding of the topic.

Returns:

  • wasAdded (boolean): True if the topic was successfully added. This can be false if the topic already existed in the player's list.

tes3.adjustSoundVolume⚓︎

Changes the volume of a sound that is playing on a given reference.

tes3.adjustSoundVolume({ sound = ..., reference = ..., mixChannel = ..., volume = ... })

Parameters:

  • params (table)
    • sound (tes3sound, string): The sound object, or id of the sound to look for.
    • reference (tes3reference, tes3mobileActor, string): The reference to attach the sound to.
    • mixChannel (tes3.soundMix, integer): Default: tes3.soundMix.effects. The channel to base volume off of. Maps to tes3.soundMix constants.
    • volume (number): Default: 1.0. A value between 0.0 and 1.0 to scale the volume off of.

tes3.advanceTime⚓︎

Advances the game time. Can be used to simulate player resting.

local hoursPassed = tes3.advanceTime({ hours = ..., resting = ..., updateEnvironment = ... })

Parameters:

  • params (table)
    • hours (number): How many hours to progress.
    • resting (boolean): Default: false. Should advancing time count as resting? If set to true invokes usual sleeping mechanics: health, fatigue and magicka restoration, and possible rest interruption. The length of the rest will be equal to hours parameter, rounded down to nearest natural number.
    • updateEnvironment (boolean): Default: true. Controls if the weather system is updated for each hour passed.

Returns:

  • hoursPassed (number)

tes3.applyMagicSource⚓︎

Applies magic effects from a spell, potion, or enchantment on the given actor instantly. You can also apply any custom set of effects, by passing an effects table.

Usage:

  • To apply a potion pass a reference.
  • When applying a spell, the reference will be the spell's caster, and the target will be the spell's target.
  • When using enchantment, you need to pass the reference, target, and fromStack. The charge of the item in the fromStack will be used. If that item is out of charge no enchantment will be applied.
local instance = tes3.applyMagicSource({ reference = ..., source = ..., name = ..., effects = ..., createCopy = ..., fromStack = ..., target = ..., bypassResistances = ... })

Parameters:

  • params (table)
    • reference (tes3reference, tes3mobileActor, string): A reference on which the magic source will be applied.
    • source (tes3object): Optional. A magic source to apply.
    • name (string): Optional. While optional for other uses, if applying alchemy as a source, you must specify a name for the magic source.
    • effects (table): Optional. A table of custom effects to apply as a potion. Maximal number of effects is 8.
      • id (tes3.effect, integer): Default: -1. ID of the effect. Maps to values in tes3.effect table.
      • skill (tes3.skill, integer): Default: -1. If effect parameter specified is: Absorb, Damage, Drain, Fortify or Restore Skill, a skill should be provided. This also applies to any custom spell effect which operates on a certain skill. This value maps to tes3.skill constants.
      • attribute (tes3.attribute, integer): Default: -1. If effect parameter specified is: Absorb, Damage, Drain, Fortify or Restore Attribute, an attribute should be provided. This also applies to any custom spell effect which operates on a certain attribute. This value maps to tes3.attribute constants.
      • rangeType (tes3.effectRange, integer): Default: tes3.effectRange.self. The range of the effect. This maps to tes3.effectRange constants.
      • radius (number): Default: 0. The radius of the effect.
      • duration (number): Default: 0. Number of seconds the effect is going to be active.
      • min (number): Default: 0. The minimal magintude of the effect per tick.
      • max (number): Default: 0. The maximal magnitude of the effect per tick.
    • createCopy (boolean): Default: true. This parameter controls whether the function will return the original magic source or a copy of the magic source. This parameter is only used if source is alchemy.
    • fromStack (tes3equipmentStack): Optional. The piece of equipment this magic source is coming from. This item's charge will be used. The fromStack has to be an already equipped item from tes3actor.equipment. This will probably change in the future.
    • target (tes3reference, tes3mobileActor, string): Optional. The target of the magic.
    • bypassResistances (boolean): Default: false. Is this effect going to bypass magic resistance?

Returns:


tes3.applyTextDefines⚓︎

Returns a string with all the text defines replaced in the input string. This can be used to replicate the behavior of book and dialogue text.

local result = tes3.applyTextDefines({ text = ..., actor = ... })

Parameters:

  • params (table)
    • text (string): The input string to do text replacements for.
    • actor (tes3actor): The actor to use for replacements like %Name and %Faction.

Returns:

  • result (string)

tes3.calculateChargeUse⚓︎

Calculates the actual charge use of an enchantment by a mobile actor, after skills are applied. Invokes the enchantChargeUse event to account for modded charge usage. Takes into account the MCP charge use rebalance patch, if activated.

local chargeUse = tes3.calculateChargeUse({ mobile = ..., enchantment = ... })

Parameters:

  • params (table)

Returns:

  • chargeUse (number): Actual charge use.
Example: How to check the charge use of the player's currently selected enchantment
local ench = tes3.mobilePlayer.currentSpell
local charge = tes3.calculateChargeUse{ mobile = tes3.mobilePlayer, enchantment = ench }
tes3.messageBox{ message = string.format("%s uses %d charge", ench.id, charge) }

tes3.calculatePrice⚓︎

Calculates a price, given a merchant and associated trading data. This is useful beyond accessing the object's .value field in that it raises the appropriate events to let other mods modify the values.

local price = tes3.calculatePrice({ object = ..., basePrice = ..., buying = ..., selling = ..., merchant = ..., bartering = ..., repairing = ..., training = ..., count = ..., itemData = ..., skill = ... })

Parameters:

  • params (table)
    • object (tes3object): Optional. The object to calculate the price for. If not provided, basePrice is required.
    • basePrice (number): Optional. The base price to calculate the end price for. This defaults to the object param's value, if provided. This parameter is required if object is not provided.
    • buying (boolean): Default: true. If true, uses the logic for buying a service/item. This is exclusive with selling.
    • selling (boolean): Default: false. If true, uses the logic for selling an item. This is exclusive with buying.
    • merchant (tes3mobileActor): The merchant to use for calculating the price.
    • bartering (boolean): Default: false. If true, a calcBarterPrice or calcRepairPrice event will be triggered.
    • repairing (boolean): Default: false. If true, a calcRepairPrice event will be triggered.
    • training (boolean): Default: false. If true, a calcTrainingPrice event will be triggered, passing the given skill ID.
    • count (number): Default: 1. If bartering, the count passed to the calcBarterPrice event.
    • itemData (tes3itemData): Optional. If bartering or repairing, the item data passed to the calcBarterPrice or calcRepairPrice event.
    • skill (tes3.skill, integer): Optional. If training, the skill ID passed to the calcTrainingPrice event. Maps to values in tes3.skill table.

Returns:

  • price (number): The calculated price, filtered by events.

tes3.canCastSpells⚓︎

Returns true if the target actor can cast spells, otherwise returns false.

local result = tes3.canCastSpells({ target = ... })

Parameters:

Returns:

  • result (boolean)

tes3.cancelAnimationLoop⚓︎

Signals looping animations on the actor to stop looping and play to the end. The animation will continue, playing past the loop point until the end frame. Useful for exiting looping animations cleanly.

tes3.cancelAnimationLoop({ reference = ... })

Parameters:


tes3.canRest⚓︎

This function returns true if player can rest.

local canRest = tes3.canRest({ checkForEnemies = ..., checkForSolidGround = ..., showMessage = ... })

Parameters:

  • params (table): Optional.
    • checkForEnemies (boolean): Default: true. Perform a check whether there are enemies nearby before opening rest menu. If there are, false is returned.
    • checkForSolidGround (boolean): Default: true. Perform a check if the player is underwater. If underwater, false is returned.
    • showMessage (boolean): Default: false. If true, a messagebox will be shown if the player can't rest because some condition isn't met.

Returns:

  • canRest (boolean)

tes3.cast⚓︎

Casts a spell from a given reference to a target reference. Touch effects will hit the target at any range, while target effects will create a projectile. By default, the spell always casts successfully and does not consume magicka. By default, an actor casting will stop and perform its cast animation, but the 'instant' flag can start the cast instantly and allows more control over the spell for NPCs.

If the caster is the player, the target parameter is optional; without a target, the player's touch effects will only hit targets in front of them, and target effects will create a projectile in the direction the player is facing.

local success = tes3.cast({ reference = ..., target = ..., spell = ..., instant = ..., alwaysSucceeds = ..., bypassResistances = ... })

Parameters:

  • params (table)
    • reference (tes3reference, tes3mobileActor, string): The caster reference.
    • target (tes3reference, tes3mobileActor, string): The target reference. Optional only if the caster is the player.
    • spell (tes3spell, string): The spell the caster uses.
    • instant (boolean): Default: false. If true, the spell is cast instantly. No animation is performed.
    • alwaysSucceeds (boolean): Default: true. If true, the spell cannot fail and does not consume magicka. If false, it is cast using the actor's spell skill, and requires and takes enough magicka to cast. For NPCs, this only applies if instant is true.
    • bypassResistances (boolean): Default: false. If true, the spell will bypass the target's resistances. For NPCs, this only applies if instant is true.

Returns:

  • success (boolean): Returns true if the spell was cast successfully. Returns false if instant is false and the player is trying to cast the spell, while being unable to cast spells under normal circumstances.
Example: This is an example of how to use tes3.cast instead of mwscript.explodeSpell
-- The following code can be tested in-game by pressing Alt + l or Alt + k

event.register(tes3.event.keyDown, function(e)
    if e.isAltDown then
        tes3.messageBox("mwscript.explodeSpell")
        ---@diagnostic disable-next-line: deprecated
        mwscript.explodeSpell({
            reference = tes3.game.playerTarget,
            spell = "proj_trap_spell"
        })
    end
end, { filter = tes3.scanCode.l })

event.register(tes3.event.keyDown, function(e)
    if e.isAltDown then
        tes3.messageBox("tes3.cast")
        -- This will behave the same as mwscript.explodeSpell()
        tes3.cast({
            target = tes3.game.playerTarget,
            reference = tes3.game.playerTarget,
            spell = "proj_trap_spell",
        })
    end
end, { filter = tes3.scanCode.k })
Example: Applying the spell of a trapped door or container on an actor
--- Filter only the objects that can have a trap.
---@param object tes3object
---@return boolean canHaveTrap
local function canHaveTrap(object)
    local type = object.objectType
    return (type == tes3.objectType.container or
            type == tes3.objectType.door)
end

---@param trappedReference tes3reference
---@param targetReference tes3reference? *Default:* tes3.player
---@return boolean trapApplied
local function triggerTrapSpell(trappedReference, targetReference)

    -- Set the player as default targetReference.
    targetReference = targetReference or tes3.player

    local object = trappedReference.object
    if not canHaveTrap(object) then
        return false
    end

    local lockNode = trappedReference.lockNode
    if not lockNode then
        return false
    end

    local trap = lockNode.trap
    if not trap then
        return false
    end

    tes3.cast({
        reference = trappedReference,
        target = targetReference,
        spell = trap,
    })
    lockNode.trap = nil
    trappedReference.modified = true

    -- Let the game update the activation tooltip otherwise,
    -- the tooltip would still say "Trapped" if the activation
    -- tooltip was active when the triggerTrapSpell() was called.
    tes3.game:clearTarget()
    return true
end

-- To test aim at a trapped door or container and press "u" key.
local function onKeyDown()
    local result = tes3.getPlayerTarget()
    if not result then return end

    triggerTrapSpell(result)
end
event.register(tes3.event.keyDown, onKeyDown, { filter = tes3.scanCode.u })

tes3.checkMerchantOffersService⚓︎

Checks if a merchant will offer a service to you, including dialogue checks like disposition and faction membership. A specific service can be checked, or if no service is given, a generic dialogue check is made. If the service is refused, the dialogue reply for the refusal may also be returned (it may be nil, as there may not always be a reply available).

local offersService, refusalReply = tes3.checkMerchantOffersService({ reference = ..., service = ..., context = ... })

Parameters:

Returns:


tes3.checkMerchantTradesItem⚓︎

Determines if a merchant trades in a given item.

local trades = tes3.checkMerchantTradesItem({ item = ..., reference = ... })

Parameters:

Returns:

  • trades (boolean)

tes3.claimSpellEffectId⚓︎

This function is used to claim a unique spell effect name and id. This is needed before actually creating a new effect by calling tes3.addMagicEffect(). A claimed effect id is then available as: tes3.effect.effectName (just like any other spell effect). For examples of this function in practice see tes3.addMagicEffect() example.

You can read a list of already claimed magic effects here. The new magic effect's id should be higher than 142 (the last vanilla magic effect) and not already claimed.

tes3.claimSpellEffectId(name, id)

Parameters:

  • name (string): The name of the new spell effect. Must be unique. An error will be thrown if it's non-unique.
  • id (number): A unique number representing the new spell effect. An error will be thrown if it's non-unique.

tes3.clearMarkLocation⚓︎

This function deletes the player's mark location.

tes3.clearMarkLocation()

tes3.closeAlchemyMenu⚓︎

This function closes the alchemy menu.

tes3.closeAlchemyMenu()

tes3.closeContentsMenu⚓︎

This function closes the contents menu.

local wasClosed = tes3.closeContentsMenu()

Returns:

  • wasClosed (boolean): If true, the menu was previously open, and is now closed.

tes3.closeDialogueMenu⚓︎

This function closes the dialogue menu.

local wasClosed = tes3.closeDialogueMenu({ force = ... })

Parameters:

  • params (table)
    • force (boolean): Default: true. Normally, the menu can't be closed in certain circumstances, such as when the player is making a dialogue choice. If true, these usual restrictions will be ignored.

Returns:

  • wasClosed (boolean): If true, the menu was previously open, and is now closed.

tes3.closeRepairServiceMenu⚓︎

This function closes the repair service menu.

tes3.closeRepairServiceMenu()

tes3.closeRestMenu⚓︎

This function closes the resting menu.

tes3.closeRestMenu()

tes3.closeSpellmakingMenu⚓︎

This function closes the spellmaking menu.

tes3.closeSpellmakingMenu()

tes3.createObject⚓︎

Creates an object and returns it. The created object will be part of the saved game.

local createdObject = tes3.createObject({ id = ..., objectType = ..., getIfExists = ... })

Parameters:

  • params (table)

    • id (string): Optional. The id of the new object.
    • objectType (tes3.objectType, integer): The type of object to create. Maps to values in the tes3.objectType table. Supported object types are:

      • tes3.objectType.activator
      • tes3.objectType.alchemy
      • tes3.objectType.armor
      • tes3.objectType.book
      • tes3.objectType.clothing
      • tes3.objectType.container
      • tes3.objectType.enchantment
      • tes3.objectType.misc
      • tes3.objectType.sound
      • tes3.objectType.spell
      • tes3.objectType.static
      • tes3.objectType.weapon
    • getIfExists (boolean): Default: true. If true, an existing object of the same objectType and id will be returned instead of creating a new one.

Returns:

Example: Creates a tes3misc object

The example below create a misc item object that could be used to create a placeable reference later on.

local miscItemId = "create_misc_item_id"
local miscItemName = "create_misc_item_name"

mwse.log( "creating a misc item of id %s", miscItemId )

local miscItem = tes3.createObject({
    objectType = tes3.objectType.miscItem,
    id = miscItemId,
    name = miscItemName,
    mesh = [[m\misc_dwrv_gear00.nif]]
})
--- @cast miscItem tes3misc

if( miscItem ~= nil ) then
    mwse.log( "misc item created : id is %s", miscItemId )
else
    mwse.log( "failed to create a misc item of id %s", miscItemId )
    return
end

tes3.createReference({
    object = miscItem,
    position = tes3.getPlayerEyePosition(),
    orientation = { 0, 0, 0 },
    cell = tes3.getPlayerCell()
})

mwse.log( "created a reference of a misc item of id %s", miscItem.id )
Example: Creates a tes3static object

The example below create a static object that could be used to create a placeable reference later on.

local staticId = "create_static_id"

mwse.log( "creating a static of id %s", staticId )

local static = tes3.createObject({
    objectType = tes3.objectType.static,
    id = staticId,
    mesh = [[d\door_dwrv_main00.nif]]
})
--- @cast static tes3static

if( static ~= nil ) then
    mwse.log( "static created : id is %s", staticId )
else
    mwse.log( "failed to create a static of id %s", staticId )
    return
end

tes3.createReference( {
    object = static,
    position = tes3.getPlayerEyePosition(),
    orientation = { 0, 0, 0 },
    cell = tes3.getPlayerCell()
} )

mwse.log( "created a reference of static of id %s", static.id )

tes3.createReference⚓︎

Similar to mwscript's PlaceAtPC or PlaceAtMe, this creates a new reference in the game world.

local newReference = tes3.createReference({ object = ..., position = ..., orientation = ..., cell = ..., scale = ... })

Parameters:

  • params (table)
    • object (tes3physicalObject, string): The object to create a reference of.
    • position (tes3vector3, number[]): The location to create the reference at.
    • orientation (tes3vector3, number[]): The new orientation for the created reference.
    • cell (tes3cell, string, table): Optional. The cell to create the reference in. This is only needed for interior cells.
    • scale (number): Default: 1. A scale for the reference.

Returns:


tes3.createVisualEffect⚓︎

Creates an arbitrary and automatically tracked visual effect. Most VFX assignments are persistent, and only expire when their lifespan ends, an associated reference is destroyed, or a given spell serial is retired.

local vfx = tes3.createVisualEffect({ object = ..., serial = ..., repeatCount = ..., lifespan = ..., scale = ..., verticalOffset = ..., position = ..., avObject = ..., magicEffectId = ... })

Parameters:

  • params (table)
    • object (tes3physicalObject, string): Optional. The physical object to use as the VFX. To use an enchantment-style VFX, supply the magicEffectId parameter instead.
    • serial (number): Optional. An associated tes3magicSourceInstance serial. If a serial is assigned to the VFX, the effect expiring will also remove the VFX. This is not used when creating an enchantment-style VFX.
    • repeatCount (number): Optional. A repeat count for the VFX. If provided, the key timing for the associated effect will be used, multiplied by this value, to determine the total lifespan of the VFX. This is not used when creating an enchantment-style VFX.
    • lifespan (number): Optional. The desired lifespan for the VFX. If not provided, the VFX will never die of old age.
    • scale (number): Default: 1. The scale used to resize the given VFX. The default value will match the size used by most magical effect logic. This is not used when creating an enchantment-style VFX.
    • verticalOffset (number): Default: 0. This offset will be used to position it above its anchor reference. This is not used when creating an enchantment-style VFX.
    • position (tes3vector3, number[]): Optional. If provided the VFX will be attached relative to a position, and not follow a reference.
    • avObject (niAVObject): Optional.
    • magicEffectId (number): Optional. The magic effect ID to use to create an enchantment-style VFX. This will use most of the same VFX logic, but cannot be applied to a position or specific niAVObject.

Returns:

  • vfx (tes3vfx): A handle to the VFX that was created. This can be passed to tes3.removeVisualEffect to remove it from the reference.

tes3.decrementKillCount⚓︎

Decreases player's kill count of a certain type of actor by one.

tes3.decrementKillCount({ actor = ... })

Parameters:

  • params (table)
    • actor (tes3actor, string): The actor (or their ID).

tes3.deleteObject⚓︎

Deletes a game object from the system. This can be dangerous, use with caution.

tes3.deleteObject(object)

Parameters:


tes3.disableKey⚓︎

Disables the use of a keyboard key.

tes3.disableKey(keyCode)

Parameters:


tes3.dropItem⚓︎

Drops one or more items from a reference's inventory onto the ground at their feet. It will unequip the item if it is equipped. The return value will be nil if no matching item was found.

local createdReference = tes3.dropItem({ reference = ..., item = ..., itemData = ..., matchNoItemData = ..., count = ..., updateGUI = ... })

Parameters:

  • params (table)
    • reference (tes3mobileActor, tes3reference, string): The reference whose inventory will be modified.
    • item (tes3item, string): The item to drop.
    • itemData (tes3itemData): Optional. The item data of the specific item to drop. Without this, the first matching item in the inventory will drop.
    • matchNoItemData (boolean): Default: false. If true, matches an item without item data. This can be used when you want to drop an item that isn't equipped (equipped items always have item data).
    • count (number): Default: 1. The number of items to drop.
    • updateGUI (boolean): Default: true. If false, the player or contents menu won't be updated.

Returns:


tes3.enableKey⚓︎

Enables the use of a keyboard key.

tes3.enableKey(keyCode)

Parameters:


tes3.fadeIn⚓︎

Similar to the vanilla FadeIn mwscript command.

tes3.fadeIn({ fader = ..., duration = ... })

Parameters:

  • params (table): Optional.
    • fader (tes3fader): Default: tes3.worldController.transitionFader. Defaults to the transition fader.
    • duration (number): Default: 1.0. Time, in seconds, for the fade.

tes3.fadeOut⚓︎

Similar to the vanilla FadeOut mwscript command.

tes3.fadeOut({ fader = ..., duration = ... })

Parameters:

  • params (table): Optional.
    • fader (tes3fader): Optional. Defaults to the transition fader.
    • duration (number): Default: 1.0. Time, in seconds, for the fade.

tes3.fadeTo⚓︎

Similar to the vanilla FadeTo mwscript command.

tes3.fadeTo({ fader = ..., duration = ..., value = ... })

Parameters:

  • params (table): Optional.
    • fader (tes3fader): Optional. Defaults to the transition fader.
    • duration (number): Default: 1.0. Time, in seconds, for the fade.
    • value (number): Default: 1.0.

tes3.findActorsInProximity⚓︎

Searches for active mobile actors which are within range distance from the reference or position argument. It only finds mobiles which have active AI, and can include the player. This function is used by the game for area-of-effect hits. It has a small amount of overhead, so try not to use it too much.

local mobileList = tes3.findActorsInProximity({ reference = ..., position = ..., range = ... })

Parameters:

  • params (table)
    • reference (tes3reference, tes3mobileActor, string): Optional. The position to search from, taken from a reference. Uses the position of the centre of the body if the reference is an actor.
    • position (tes3vector3): Optional. The position to search from.
    • range (number): The distance around the position to search. An actor is included if the centre of their body is in range.

Returns:


tes3.findBirthsign⚓︎

Fetches the core game birthsign object for a given birthsign ID. If the birthsign with a given ID doesn't exist, nil is returned.

local birthsign = tes3.findBirthsign(id)

Parameters:

  • id (string): ID of the birthsign to search for.

Returns:


tes3.findClass⚓︎

Fetches the core game character class object for a given class ID. If the class with a given ID doesn't exist, nil is returned.

local class = tes3.findClass(id)

Parameters:

  • id (string): ID of the class to search for.

Returns:


tes3.findClosestExteriorReferenceOfObject⚓︎

Using the same engine function used by the vanilla intervention spells, locations the first reference of a given object in the exterior world.

local reference = tes3.findClosestExteriorReferenceOfObject({ object = ..., position = ... })

Parameters:

  • params (table)
    • object (tes3physicalObject, string): The object to search for.
    • position (tes3vector3): Optional. The position to search from. Must be an exterior position. Defaults to the last exterior position of the player if no position is provided.

Returns:


tes3.findDialogue⚓︎

Locates a root dialogue topic that can then be filtered down for a specific actor to return a specific dialogue info. Specify either topic, or both type and page for other types of dialogue.

For example, tes3.findDialogue({type = tes3.dialogueType.greeting, page = tes3.dialoguePage.greeting.greeting0}) will return the "Greeting 0" topic, which is not available using a topic ID.

local dialogue = tes3.findDialogue({ topic = ..., type = ..., page = ... })

Parameters:

  • params (table)
    • topic (string): Optional. The dialogue topic to look for.
    • type (tes3.dialogueType, integer): Optional. The type of dialogue to look for. Uses tes3.dialogueType constants.
    • page (tes3.dialoguePage.voice, tes3.dialoguePage.greeting, tes3.dialoguePage.service, integer): Optional. The page of dialogue to fetch. Uses tes3.dialoguePage constants.

Returns:


tes3.findGlobal⚓︎

Fetches the core game object that represents a global variable.

local globalVariable = tes3.findGlobal(id)

Parameters:

  • id (string)

Returns:


tes3.findGMST⚓︎

Fetches the core game object that represents a game setting. While this function accepts a name, it is recommended to use the tes3.GMST constants.

local gameSetting = tes3.findGMST(id)

Parameters:

Returns:

Example: Document all GMST Default Values

This example reads the default values of all GMSTs, and writes them to a markdown file for users to read.

-- Converter table for a GMST's type to something more user-friendly.
local typeNames = {
    s = "string",
    i = "integer",
    f = "float",
}

-- Write our markdown header.
local f = assert(io.open("Data Files\\MWSE\\tmp\\GMSTs.md", "w"))
f:write("# GMSTs\n\n")
f:write("Index | Type   | Identifier                       | Default Value\n")
f:write("----- | ------- | -------------------------------- | --------------------------------------------\n")

-- Go through all our GMSTs...
for id = 0, 1520 do
    -- Write out most of the info.
    local gmst = tes3.findGMST(id)
    f:write(string.format("%-5d | %-7s | %-32s | ", gmst.index, typeNames[gmst.type], gmst.id))

    -- Customize how the value is written based on its type.
    if (gmst.type == "s") then
        -- Remove linebreaks and escape them.
        local value = gmst.defaultValue
        value = string.gsub(value, "\r", "\\r")
        value = string.gsub(value, "\n", "\\n")
        f:write(string.format("`\"%s\"`", value))
    elseif (gmst.type == "f") then
        f:write(string.format("`%.4f`", gmst.defaultValue))
    else
        f:write(string.format("`%d`", gmst.defaultValue))
    end

    f:write("\n")
end

-- Close up our file.
f:close()
Example: Retrieve value of a GMST

This example shows how to read a value of a GMST and how to change it.

local oldGMST = tes3.findGMST("sServiceTrainingTitle").value

-- oldGMST is now "Training"

-- Now let's change the message to something more appropriate.
tes3.findGMST("sServiceTrainingTitle").value = "Cheat"

tes3.findRegion⚓︎

Fetches the core game region object for a given region ID. If the region with a given ID doesn't exist, nil is returned.

local region = tes3.findRegion({ id = ... })

Parameters:

  • params (table)
    • id (string): ID of the region to search for.

Returns:


tes3.force1stPerson⚓︎

Forces the player's POV to first person the next simulation frame, and returns true if the POV has been changed.

local changedPOV = tes3.force1stPerson()

Returns:

  • changedPOV (boolean)

tes3.force3rdPerson⚓︎

Forces the player's POV to third person the next simulation frame, and returns true if the POV has been changed.

local changedPOV = tes3.force3rdPerson()

Returns:

  • changedPOV (boolean)

tes3.get3rdPersonCameraOffset⚓︎

Returns the camera offset from the player's head while in 3rd person view.

Tip

If used before initialized event, this function returns empty table.

local cameraOffset = tes3.get3rdPersonCameraOffset()

Returns:


tes3.getActiveCells⚓︎

Returns a table of active cells. If indoors, the table will have only one entry. If outdoors, the 9 surrounding cells will be provided.

local cells = tes3.getActiveCells()

Returns:


tes3.getAnimationActionTiming⚓︎

This function fetches a dictionary of the timings of the action keys for a specific animation group on an actor. The actor is required, as different actors can use different animations. The result is a table with action names as keys, and timings as values. The function will return nil if the actor does not have that animation group, or if the actor's animations are not active.

local result = tes3.getAnimationActionTiming({ reference = ..., group = ... })

Parameters:

Returns:

  • result (table<string, number>, nil)

tes3.getAnimationGroups⚓︎

This function fetches a reference's attached animation groups. The animation groups match the values from tes3.animationGroup table.

local lowerBodyGroup, upperBodyGroup, leftArmGroup = tes3.getAnimationGroups({ reference = ... })

Parameters:

  • params (table)
    • reference (tes3reference): A reference whose animation groups to fetch.

Returns:

Example: Getting animation timings for bow animations
local function onSimulate()
    local reference = tes3.is3rdPerson() and tes3.player or tes3.player1stPerson

    local _, upperGroup, _ = tes3.getAnimationGroups({ reference = reference })
    if upperGroup ~= tes3.animationGroup.bowAndArrow then return end

    local _, upperTiming, _ = unpack(
        tes3.getAnimationTiming({ reference = reference })
    )
    tes3.messageBox(upperTiming)
end
event.register(tes3.event.simulate, onSimulate)

tes3.getAnimationTiming⚓︎

This function fetches a reference's attached animation groups' timings.

local result = tes3.getAnimationTiming({ reference = ... })

Parameters:

Returns:

  • result (number[])
Example: Getting animation timings for bow animations
local function onSimulate()
    local reference = tes3.is3rdPerson() and tes3.player or tes3.player1stPerson

    local _, upperGroup, _ = tes3.getAnimationGroups({ reference = reference })
    if upperGroup ~= tes3.animationGroup.bowAndArrow then return end

    local _, upperTiming, _ = unpack(
        tes3.getAnimationTiming({ reference = reference })
    )
    tes3.messageBox(upperTiming)
end
event.register(tes3.event.simulate, onSimulate)
Example: An elegent usage example

The function returns animation timings for three body segments. This array can be nicely broken down into three variables using Lua's unpack() function.

local reference = tes3.is3rdPerson() and tes3.player or tes3.player1stPerson
local lowerTiming, upperTiming, leftArmTiming = unpack(
    tes3.getAnimationTiming({ reference = reference })
)

tes3.getArchiveList⚓︎

Returns a 1-indexed table of active archives. The paths are relative to Morrowind folder. For example: "Data Files\Tribunal.bsa".

local archives = tes3.getArchiveList()

Returns:

  • archives (string[])

tes3.getAttachment⚓︎

Fetches an attachment with a given type from a reference. Will return nil if no attachment of that type has been found.

local result = tes3.getAttachment(reference, attachment)

Parameters:

  • reference (tes3reference): The reference to get the attachment from.
  • attachment (string): The type of attachment to get. Possible values are:
    • "bodyPartManager": Returns tes3bodyPartManager
    • "light": Returns tes3lightNode
    • "lock": Returns tes3lockNode
    • "leveledBase": Returns tes3reference
    • "travelDestination": Returns tes3travelDestinationNode
    • "variables": Returns tes3itemData
    • "actor": Returns tes3mobileActor
    • "animation": Returns tes3animationData

Returns:


tes3.getAttributeName⚓︎

Returns the lowercase identifying name of an attribute for a given numerical, 0-based index. E.g. "strength", by using GMSTs. Uses tes3.attributeName enumeration as a fallback.

local name = tes3.getAttributeName(attributeId)

Parameters:

Returns:

  • name (string)

tes3.getCamera⚓︎

Returns the world camera.

local camera = tes3.getCamera()

Returns:


tes3.getCameraPosition⚓︎

Returns the camera's position.

local vector3 = tes3.getCameraPosition()

Returns:


tes3.getCameraVector⚓︎

Returns the camera look vector.

local vector3 = tes3.getCameraVector()

Returns:


tes3.getCell⚓︎

Finds a cell, either by an id, by an object position (finds an exterior cell), or by an X/Y grid position. Returns nil if the cell id cannot be found or the cell does not exist at a position.

local cell = tes3.getCell({ id = ..., position = ..., x = ..., y = ... })

Parameters:

  • params (table)
    • id (string): Optional. The cell's ID. If not provided, position or x and y must be.
    • position (tes3vector3, number[]): Optional. A point in an exterior cell.
    • x (number): Optional. The X grid-position.
    • y (number): Optional. The Y grid-position.

Returns:


tes3.getCumulativeDaysForMonth⚓︎

Gets the number of days that have passed leading up to the start of a given month.

local days = tes3.getCumulativeDaysForMonth(month)

Parameters:

  • month (number): The 0-based month index.

Returns:

  • days (number)

tes3.getCurrentAIPackageId⚓︎

Returns an actor's current AI package ID, just as the mwscript function GetCurrentAIPackage would.

local packageID = tes3.getCurrentAIPackageId({ reference = ... })

Parameters:

Returns:


tes3.getCurrentWeather⚓︎

Gets the currently active weather, from the player's current region.

local weather = tes3.getCurrentWeather()

Returns:


tes3.getCursorPosition⚓︎

Returns a table with values x and y that contain the current cursor position.

local position = tes3.getCursorPosition()

Returns:


tes3.getDaysInMonth⚓︎

Returns the number of days in a given month. This may be altered if a Morrowind Code Patch feature was installed.

local dayCount = tes3.getDaysInMonth(month)

Parameters:

  • month (number)

Returns:

  • dayCount (number)

tes3.getDialogueInfo⚓︎

Locates and returns a Dialogue Info by a given id. This involves file IO and is an expensive call. Results should be cached.

local dialogueInfo = tes3.getDialogueInfo({ dialogue = ..., id = ... })

Parameters:

  • params (table)
    • dialogue (tes3dialogue, string): The dialogue that the info belongs to.
    • id (string): The numerical, unique id for the info object.

Returns:


tes3.getEffectMagnitude⚓︎

This function returns the total effective magnitude and total base magnitude of a certain magic effect affecting a reference. It returns a pair of numbers, the first being the effective magnitude after all the actor's resistances are applied (see examples). The second number is the magnitude before any of the actor's resistances are applied. This function respects hasNoMagnitude flag, returning 0 for both magnitude and effectiveMagnitude for such effects.

local effectiveMagnitude, magnitude = tes3.getEffectMagnitude({ reference = ..., effect = ..., skill = ..., attribute = ... })

Parameters:

  • params (table)
    • reference (tes3reference, tes3mobileActor, string): An associated mobile should exist for this function to be able to work.
    • effect (tes3.effect, integer): Effect ID. Can be any of the predefined spell effects, or one added by tes3.claimSpellEffectId(). Maps to values of tes3.effect constants
    • skill (tes3.skill, integer): Default: -1. If effect parameter specified is: Absorb, Damage, Drain, Fortify or Restore Skill, a skill should be provided. This also applies to any custom spell effect which operates on a certain skill. This value maps to tes3.skill constants.
    • attribute (tes3.attribute, integer): Default: -1. If effect parameter specified is: Absorb, Damage, Drain, Fortify or Restore Attribute, an attribute should be provided. This also applies to any custom spell effect which operates on a certain attribute. This value maps to tes3.attribute constants.

Returns:

  • effectiveMagnitude (number): The effective magnitude after all the actor's resistances are applied.
  • magnitude (integer): The magnitude before any of the actor's resistances are applied.
Example: Get both magnitudes.
local effectiveMagnitude, magnitude = tes3.getEffectMagnitude{reference = tes3.player, effect = tes3.effect.fireDamage}
tes3.messageBox(string.format("fortify speed: %f (%f)", effectiveMagnitude, magnitude))
Example: Get magnitude after resistances are applied.

You can treat the function as if it returns a single value.

local effectiveMagnitude = tes3.getEffectMagnitude{reference = tes3.player, effect = tes3.effect.fortifyAttribute, attribute = tes3.attribute.speed}
tes3.messageBox(string.format("fortify speed: %f", effectiveMagnitude))

tes3.getEquippedItem⚓︎

Returns an actor's equipped item stack, provided a given filter

local stack = tes3.getEquippedItem({ actor = ..., enchanted = ..., objectType = ..., slot = ..., type = ... })

Parameters:

Returns:

  • stack (tes3equipmentStack, nil): The equipped stack, or nil if the queried stack was not found.
Example: Get Player’s Equipped Light

In this example, we print the object ID of the player’s equipped light source.

local equippedLightStack = tes3.getEquippedItem({ actor = tes3.player, objectType = tes3.objectType.light })
if (equippedLightStack) then
    mwse.log("Equipped light: %s", equippedLightStack.object.id)
else
    mwse.log("No light equipped.")
end
Example: Get Player’s Shield

This example shows the player’s shield.

local equippedShieldStack = tes3.getEquippedItem({ actor = tes3.player, objectType = tes3.objectType.armor, slot = tes3.armorSlot.shield })
if (equippedShieldStack) then
    mwse.log("Equipped shield: %s", equippedShieldStack.object.id)
else
    mwse.log("No shield equipped.")
end

tes3.getFaction⚓︎

Fetches the core game faction object for a given faction ID.

local faction = tes3.getFaction(id)

Parameters:

  • id (string)

Returns:


tes3.getFileExists⚓︎

Determines if a file exists in the user's Data Files.

local exists = tes3.getFileExists(path)

Parameters:

  • path (string)

Returns:

  • exists (boolean)

tes3.getFileSource⚓︎

Determines if a file exists on the filesystem or inside of a bsa. The returned string will be "file" or "bsa".

local exists, path = tes3.getFileSource(path)

Parameters:

  • path (string)

Returns:

  • exists (string?): A string representing the file source. This can be either file or bsa.
  • path (string?): If the file exists, this is a path to the file. If the file is from a BSA, it is a path inside the BSA.

tes3.getGlobal⚓︎

Retrieves the value of a global value, or nil if the global could not be found.

local value = tes3.getGlobal(id)

Parameters:

  • id (string)

Returns:

  • value (integer)

tes3.getInputBinding⚓︎

Gets the input configuration for a given keybind.

local inputConfig = tes3.getInputBinding(keybind)

Parameters:

Returns:


tes3.getItemCount⚓︎

Returns the amount of a certain item that can be found in a reference's inventory.

local count = tes3.getItemCount({ reference = ..., item = ... })

Parameters:

  • params (table)
    • reference (tes3reference, tes3mobileActor, string): The reference to get the item count for. Must be a reference that has an inventory.
    • item (tes3item, string): The item to get the count of.

Returns:

  • count (number): The absolute value of the stack count in the reference's inventory.

tes3.getItemIsStolen⚓︎

This function checks item's stolen flag.

local isStolen, stolenFrom = tes3.getItemIsStolen({ item = ..., from = ... })

Parameters:

  • params (table)
    • item (tes3item): The item to check.
    • from (tes3creature, tes3npc, tes3faction, nil): Optional. Where the item was stolen from. If not provided, the function will return true if the item was stolen from anyone.

Returns:

  • isStolen (boolean): If true the item is stolen.
  • stolenFrom (tes3creature[], tes3npc[], tes3faction[]): A list of who and what the item has been stolen from.

tes3.getJournalIndex⚓︎

Gets the index of a given journal, or nil if no valid journal could be found.

local index = tes3.getJournalIndex({ id = ... })

Parameters:

Returns:

  • index (number)

tes3.getKeyName⚓︎

Gets the name of a corresponding tes3.scanCode, using the appropriate GMSTs. The keyName returned by this function is the same keyName that would be used in the in-game Controls menu.

For example, tes3.getKeyName(tes3.scanCode.b) will return "B", and tes3.getKeyName(tes3.scanCode.rshift) will return "Right Shift".

local keyName = tes3.getKeyName(keyCode)

Parameters:

Returns:

  • keyName (string, nil): A string representation of the given keyCode.

tes3.getKillCount⚓︎

Returns how many times the player killed an actor. If no actor is specified, total number of kills player commited will be returned.

local count = tes3.getKillCount({ actor = ... })

Parameters:

  • params (table): Optional.
    • actor (tes3actor, string): Optional. The actor (or their ID) for whom to retrieve player's kill count.

Returns:

  • count (number)

tes3.getKillCounts⚓︎

Returns a table with complete player kill counts. The table returned is formated so actor IDs are table keys and kill count of that type of actor is value.

local killMap = tes3.getKillCounts()

Returns:


tes3.getLanguage⚓︎

Gets the language as an ISO string (e.g. "eng"), determined by the language entry in Morrowind.ini and the detected executable. Maps to values in the tes3.language table.

local result = tes3.getLanguage()

Returns:

  • result (string)

tes3.getLanguageCode⚓︎

Gets the language code, determined by the language entry in Morrowind.ini and the detected executable. Maps to values in the tes3.languageCode table.

local result = tes3.getLanguageCode()

Returns:


tes3.getLastExteriorPosition⚓︎

Returns the last exterior position of the player.

local vector3 = tes3.getLastExteriorPosition()

Returns:


tes3.getLegacyScriptRunning⚓︎

This function returns true if a mwscript is currently running. Only checks global scripts.

local isRunning = tes3.getLegacyScriptRunning({ script = ... })

Parameters:

  • params (table)
    • script (tes3script, string): The script to check for.

Returns:

  • isRunning (boolean)

tes3.getLocked⚓︎

Determines if a given reference is a locked door or container.

local isLocked = tes3.getLocked({ reference = ... })

Parameters:

Returns:

  • isLocked (boolean)

tes3.getLockLevel⚓︎

Gets an locked reference's lock level. If no lock data is available, it will return nil.

local level = tes3.getLockLevel({ reference = ... })

Parameters:

Returns:

  • level (number)

tes3.getLuaModMetadata⚓︎

Fetches the contents of the metadata file associated with a given lua mod key. The mod key should match the value of lua-mod specified in the [tools.mwse] section of the relevant metadata file.

local metadata = tes3.getLuaModMetadata(modKey)

Parameters:

  • modKey (string): The key for the lua mod, which must match the file location and the metadata file's [tools.mwse] contents.

Returns:

  • metadata (MWSE.Metadata, nil)

tes3.getMagicEffect⚓︎

Fetches the core game Magic Effect object for a given ID. Can return custom magic effects added with tes3.addMagicEffect.

local magicEffect = tes3.getMagicEffect(id)

Parameters:

Returns:


tes3.getMagicEffectName⚓︎

Returns the complex name of a magic effect, taking into account attribute or skill values.

local complexName = tes3.getMagicEffectName({ effect = ..., attribute = ..., skill = ... })

Parameters:

  • params (table)

Returns:

  • complexName (string)

tes3.getMagicSourceInstanceBySerial⚓︎

Fetches an instance of the magic source of a given serial number.

local magicSourceInstance = tes3.getMagicSourceInstanceBySerial({ serialNumber = ... })

Parameters:

  • params (table)
    • serialNumber (number)

Returns:


tes3.getModList⚓︎

Fetches the list of the active ESM and ESP files.

local modList = tes3.getModList()

Returns:

  • modList (string[])

tes3.getObject⚓︎

Fetches the core game object for a given object ID.

local object = tes3.getObject(id)

Parameters:

  • id (string)

Returns:


tes3.getOwner⚓︎

Returns the object's owner, or nil if the object is unowned.

local owner, requirement = tes3.getOwner({ reference = ... })

Parameters:

Returns:

  • owner (tes3faction, tes3npc, nil)
  • requirement (number, tes3globalVariable, nil): The faction rank required if the owner is a faction, or the global variable needing to be set if the owner is an NPC.

tes3.getPlayerActivationDistance⚓︎

This function returns the distance that the player can activate objects with. This is a sum of the iMaxActivateDist GMST value and the player's telekinesis strength.

local result = tes3.getPlayerActivationDistance()

Returns:

  • result (number)

tes3.getPlayerCell⚓︎

Fetches the cell that the player is currently in.

local result = tes3.getPlayerCell()

Returns:


tes3.getPlayerEyePosition⚓︎

Returns the position of the player's eyes.

local position = tes3.getPlayerEyePosition()

Returns:


tes3.getPlayerEyeVector⚓︎

Returns the look direction of the player's eyes.

local lookDirection = tes3.getPlayerEyeVector()

Returns:


tes3.getPlayerGold⚓︎

Gets the gold count carried by the player.

local goldCount = tes3.getPlayerGold()

Returns:

  • goldCount (number)

tes3.getPlayerTarget⚓︎

This function is used to see what the player is looking at. Unlike a real raycast, this does not work in all circumstances. For instance, combat targets aren't returned by this function. You can access the last hit combat target using mobileActor.actionData.hitTarget. Other option is to use tes3.rayTest.

As a general rule, it will return the reference if the information box is shown when it is looked at.

local result = tes3.getPlayerTarget()

Returns:


tes3.getQuickKey⚓︎

This function retrieves data for a quick key.

local result = tes3.getQuickKey({ slot = ... })

Parameters:

  • params (table)
    • slot (number): The key to retrieve data for. This is a value between 1 and 9.

Returns:


tes3.getReference⚓︎

Fetches the first reference for a given base object ID.

local reference = tes3.getReference(id)

Parameters:

  • id (string): Optional. Passing "player" or "playersavegame" will return the player reference.

Returns:


tes3.getRegion⚓︎

Gets the current region the player is in. This checks the player's current cell first, but will fall back to the last exterior cell.

local region = tes3.getRegion({ useDoors = ... })

Parameters:

  • params (table): Optional.
    • useDoors (boolean): Default: false.

Returns:


tes3.getScript⚓︎

Locates and returns a script by a given id.

local script = tes3.getScript(id)

Parameters:

  • id (string)

Returns:


tes3.getSimulationTimestamp⚓︎

Returns a UNIX-style timestamp based on in-world simulation time since the start of the era, in hours.

local timestamp = tes3.getSimulationTimestamp(highPrecision)

Parameters:

  • highPrecision (boolean): Default: true. If false is passed returns the value of the simulation time variable used by the game engine. Calculates the timestamp from the current year, month and game hour global variables otherwise.

Returns:

  • timestamp (number)

tes3.getSkill⚓︎

Fetches the core game object for a given skill ID.

local skill = tes3.getSkill(id)

Parameters:

Returns:


tes3.getSkillName⚓︎

Returns the identifying name of a skill for a given numerical, 0-based index. E.g. "Enchant".

local name = tes3.getSkillName(skillId)

Parameters:

Returns:

  • name (string)

tes3.getSound⚓︎

Locates and returns a sound by a given id.

local sound = tes3.getSound(id)

Parameters:

  • id (string)

Returns:


tes3.getSoundGenerator⚓︎

Returns a sound generator by a given creature id and type.

local soundGenerator = tes3.getSoundGenerator(creatureId, soundType)

Parameters:

Returns:


tes3.getSoundPlaying⚓︎

Without a reference, this function returns true if the sound is playing unattached or on any reference. With a reference, it returns true if the sound is playing on that specific reference.

local soundIsPlaying = tes3.getSoundPlaying({ sound = ..., reference = ... })

Parameters:

Returns:

  • soundIsPlaying (boolean)

tes3.getSpecializationName⚓︎

Returns the lowercase identifying name of a specialization type for a given numerical, 0-based index. E.g. "magic", by using GMSTs. Uses tes3.specializationName enumeration as a fallback.

local name = tes3.getSpecializationName(specializationId)

Parameters:

Returns:

  • name (string)

tes3.getSpells⚓︎

Gets the spells of an actor. This can be filtered by spellType and set to include or exclude actor, racial and birthsign spells.

local result = tes3.getSpells({ target = ..., spellType = ..., getActorSpells = ..., getRaceSpells = ..., getBirthsignSpells = ... })

Parameters:

  • params (table)
    • target (tes3reference, tes3mobileActor, tes3actor): The actor to get the spells of. Must be able to cast spells.
    • spellType (tes3.spellType): Default: -1. The spell type to filter for. Only spells with this spell type will be returned. A value of -1 will return spells of all types. Maps to values in the tes3.spellType table.
    • getActorSpells (boolean): Default: true. If true, the spells of the actor itself will be included in the result. This includes every spell except racial and birthsign spells.
    • getRaceSpells (boolean): Default: true. If true, the spells of the actor's race will be included in the result.
    • getBirthsignSpells (boolean): Default: true. If true, the spells of the actor's birthsign will be included in the result.

Returns:


tes3.getTopMenu⚓︎

Gets the top-level UI menu.

local menu = tes3.getTopMenu()

Returns:


tes3.getTrap⚓︎

Gets the trap on a given reference.

local spell = tes3.getTrap({ reference = ... })

Parameters:

Returns:


tes3.getValue⚓︎

Gets the value of an item and, optionally, an associated itemData. This can be useful if you wish to take durability and soul value into account. It will also take into account any installed Morrowind Code Patch rebalances. It can also be used to get the value of a reference.

local value = tes3.getValue({ item = ..., itemData = ..., reference = ..., useDurability = ..., useSoulValue = ... })

Parameters:

  • params (table)
    • item (tes3item, string): Optional. The item to get the value of. Not needed if a reference is given.
    • itemData (tes3itemData): Optional. The item data to use to modify the value. Not needed if a reference is given.
    • reference (tes3reference, tes3mobileActor, string): Optional. The reference to get the value of. Not used if an item is given.
    • useDurability (boolean): Default: true. If set to false, condition and uses will be ignored.
    • useSoulValue (boolean): Default: true. If set to false, the soul value will be ignored, effectively giving you the base soul gem value.

Returns:

  • value (number): The calculated value of the item.

tes3.getVanityMode⚓︎

The function returns true if the player is in the vanity mode. Vanity mode is triggered by a period of inactivity from the player or by a tes3.setVanityMode() function. The view is switched to third person (if not already), and the camera is orbiting slowly around the player character.

local result = tes3.getVanityMode()

Returns:

  • result (boolean): Is the vanity mode currently active?

tes3.getViewportSize⚓︎

Returns both the viewport width and the viewport height. Note that this is the real resolution of the screen. For a value scaled by MGE's menu scaling, see the same-named function in the tes3ui namespace. To get the scale used, check getViewportScale in the tes3ui namespace.

local width, height = tes3.getViewportSize()

Returns:

  • width (number): The width of the viewport.
  • height (number): The height of the viewport.

tes3.getWerewolfKillCount⚓︎

Returns the number of kills player commited as a Werewolf.

local werewolfKills = tes3.getWerewolfKillCount()

Returns:

  • werewolfKills (number)

tes3.getWorldController⚓︎

Gets the worldController.

local worldController = tes3.getWorldController()

Returns:


tes3.hammerKey⚓︎

Simulates hammering a key.

tes3.hammerKey(keyCode)

Parameters:


tes3.hasCodePatchFeature⚓︎

Attempts to determine if a given Morrowind Code Patch feature is enabled. This may not be possible, in which case nil will be returned.

local state = tes3.hasCodePatchFeature(id)

Parameters:

Returns:

  • state (boolean, nil)

tes3.hasOwnershipAccess⚓︎

Determines if a reference has access to another object, including its inventory. References have access to their own things, and the player has access to dead NPC's items.

local hasAccess = tes3.hasOwnershipAccess({ reference = ..., target = ... })

Parameters:

Returns:

  • hasAccess (boolean)

tes3.hasSpell⚓︎

Determines if the player has access to a given spell. At least one of the actor, mobile or reference arguments needs to be passed.

local hasSpell = tes3.hasSpell({ reference = ..., actor = ..., mobile = ..., spell = ... })

Parameters:

  • params (table)
    • reference (tes3reference, tes3mobileActor, string): Optional. Who to check the spell list of. To check an actor without specifying any particular reference, use actor instead.
    • actor (tes3actor, string): Optional. Who to check the spell list of. Providing a base actor can be done before a save has been loaded, but may not correctly update effects for instanced versions of that actor in an active save.
    • mobile (tes3reference, tes3mobileActor, string): Optional. Who to check the spell list of. To check an actor without specifying any particular reference, use actor instead.
    • spell (tes3spell, string): The spell to check.

Returns:

  • hasSpell (boolean): True if the spell exists in the actor's spell list, race spell list, or birthsign spell list.

tes3.incrementKillCount⚓︎

Increases player's kill count of a certain type of actor by one.

tes3.incrementKillCount({ actor = ... })

Parameters:

  • params (table)
    • actor (tes3actor, string): The actor (or their ID) for whom to increase player's kill count.

tes3.is3rdPerson⚓︎

Returns true if the game is in 3rd person.

local state = tes3.is3rdPerson()

Returns:

  • state (boolean)

tes3.isAffectedBy⚓︎

This function performs a check whether the provided reference is affected by a certain object or magic effect.

Note reference.object.spells:contains(spellID) will give the same output as this function for abilities, diseases, and curses, because having them in your spell list also makes them affect you.

local isAffectedBy = tes3.isAffectedBy({ reference = ..., effect = ..., object = ... })

Parameters:

Returns:

  • isAffectedBy (boolean)

tes3.isCharGenFinished⚓︎

Returns true if the character generation process has been finished for the current player character.

local result = tes3.isCharGenFinished()

Returns:

  • result (boolean)

tes3.isCharGenRunning⚓︎

Returns true if the character generation process is still in progress for the current player character.

local result = tes3.isCharGenRunning()

Returns:

  • result (boolean)

tes3.isCharGenStarted⚓︎

Returns true if the character generation process has been started (this is only false on the main menu).

local result = tes3.isCharGenStarted()

Returns:

  • result (boolean)

tes3.isInitialized⚓︎

Returns true if the game has initialized.

local isInitialized = tes3.isInitialized()

Returns:

  • isInitialized (boolean)

tes3.isKeyEqual⚓︎

Compares two key objects and returns their equality. Returns true if the objects are equal, false otherwise.

local equal = tes3.isKeyEqual({ actual = ..., expected = ... })

Parameters:

  • params (table)
    • actual (table, mwseKeyCombo, mwseKeyMouseCombo, keyDownEventData, keyUpEventData, keyEventData, mouseButtonDownEventData, mouseButtonUpEventData, mouseWheelEventData): The key object that is being compared.
      • keyCode (tes3.scanCode): Default: false. Value of the actual key scan code, such as the letter p. Maps to tes3.scanCode.*.
      • isShiftDown (boolean): Default: false. Value of whether the shift key is pressed.
      • isControlDown (boolean): Default: false. Value of whether the control key is pressed.
      • isAltDown (boolean): Default: false. Value of whether the alt key is pressed.
      • isSuperDown (boolean): Default: false. Value of whether the super (Windows key) key is pressed.
      • mouseButton (number): Default: false. The mouse button index.
      • mouseWheel (integer): Default: false. The mouse wheel direction. -1 is down, 1 is up.
    • expected (table, mwseKeyCombo, mwseKeyMouseCombo, keyDownEventData, keyUpEventData, keyEventData, mouseButtonDownEventData, mouseButtonUpEventData, mouseWheelEventData): The key object that is being compared against.
      • keyCode (tes3.scanCode): Default: false. Value of the expected key scan code, such as the letter p. Maps to tes3.scanCode.*.
      • isShiftDown (boolean): Default: false. Value of whether the shift key is expected to be pressed.
      • isControlDown (boolean): Default: false. Value of whether the control key is expected to be pressed.
      • isAltDown (boolean): Default: false. Value of whether the alt key is expected to be pressed.
      • isSuperDown (boolean): Default: false. Value of whether the super (Windows key) key is pressed.
      • mouseButton (number): Default: false. The mouse button index.
      • mouseWheel (integer): Default: false. The mouse wheel direction. -1 is down, 1 is up.

Returns:

  • equal
Example: Filtering out key presses that aren't equal to the bound key combination
-- An example of a simple configuration setup
local defaultConfig = {
    ---@type mwseKeyMouseCombo
    combo = {
        -- Alt + Left mouse button
        mouseButton = 0,
        isAltDown = true,
        isControlDown = false,
        isShiftDown = false,
    },
}
local config = mwse.loadConfig("myModConfig", defaultConfig)

local function registerModConfig()
    local template = mwse.mcm.createTemplate({ name = "Test Mod" })
    template:register()

    local page = template:createSideBarPage({ label = "Settings" })

    page:createKeyBinder({
        label = "My combo",
        description = "This combo does...",
        allowMouse = true,
        variable = mwse.mcm.createTableVariable({
            id = "combo",
            table = config
        }),
    })
end
event.register(tes3.event.modConfigReady, registerModConfig)


--- @param e keyDownEventData|mouseButtonDownEventData|mouseWheelEventData
local function sayHi(e)
    if not tes3.isKeyEqual({ expected = config.combo, actual = e }) then
        -- Nothing to do if the pressed combination isn't equal to our expected combination.
        return
    end

    -- Now do our logic
    tes3.messageBox("Hi!")
end

event.register(tes3.event.keyDown, sayHi)
event.register(tes3.event.mouseButtonDown, sayHi)
event.register(tes3.event.mouseWheel, sayHi)

tes3.isLuaModActive⚓︎

Determines if the player has a given lua mod active. The key passed to this function is the path to where its main.lua file is, relative to the MWSE\mods folder. Slashes are automatically replaced with periods, and the key is case-insensitive.

local isActive = tes3.isLuaModActive(key)

Parameters:

  • key (string): The key to check.

Returns:

  • isActive (boolean): True if the mod is active, otherwise false.
Example: Determine if a Specific Lua Mod is Active

In this example, we determine if Chameleon is active. The mod provides no interop files to try to include, and is a simple main.lua file. This makes it hard to otherwise detect.

if (tes3.isLuaModActive("Danae.Chameleon")) then
    -- Perform some compatibility actions here.
end

tes3.isModActive⚓︎

Determines if the player has a given ESP or ESM file active.

local result = tes3.isModActive(filename)

Parameters:

  • filename (string): The filename of the mod to find, including the extension.

Returns:

  • result (boolean)

tes3.iterate⚓︎

This function returns a function that iterates over a tes3iterator object. This is useful for for loops.

Note that tes3iterator objects support iteration with pairs() function.

local iterator = tes3.iterate(iterator)

Parameters:

Returns:


tes3.iterateObjects⚓︎

Iteration function used for looping over game objects.

local objectIterator = tes3.iterateObjects(filter)

Parameters:

  • filter (integer, integer[]): Optional. Maps to tes3.objectType constants.

Returns:


tes3.loadAnimation⚓︎

Loads an animation and uses it to override existing animations on an actor. Animation groups present in the file will replace the actor's animation groups. The actor's model must be already loaded into memory to have its animations modified. The overridden animations only persist until the actor is unloaded.

Calling this more than once will remove the previous animation override before loading the new animation. Therefore, if applying animations to the player, you should call this before every playAnimation so that different animation mods can co-exist. For NPCs under your mod's control, you only need to do it when the player enters the cell containing the NPC.

Calling this without a file argument will reset the reference's animations to default.

tes3.loadAnimation({ reference = ..., file = ... })

Parameters:

  • params (table)
    • reference (tes3mobileActor, tes3reference, string): The reference to the actor that is having its animations modified.
    • file (string): Optional. The specified animation base file that will be loaded. e.g. For an animation composed of files anim.nif, xanim.nif and xanim.kf, you should pass file="anim.nif". The animation target skeleton must match the skeleton of the actor to work. i.e. 3rd person anims for NPCs and tes3.player, 1st person anims for firstPersonReference.

tes3.loadGame⚓︎

Loads a game.

tes3.loadGame(filename)

Parameters:

  • filename (string): The full filename of the save that we want to load, including extension.

tes3.loadMesh⚓︎

Loads a mesh file and provides a scene graph object.

local model = tes3.loadMesh(path, useCache)

Parameters:

  • path (string): Path, relative to Data Files/Meshes.
  • useCache (boolean): Default: true. If false, a new object will be created even if it had been previously loaded.

Returns:


tes3.loadSourceTexture⚓︎

Loads a source texture file and provides the niSourceTexture object.

local texture = tes3.loadSourceTexture(path, useCache)

Parameters:

  • path (string): Path, relative to Data Files/Textures.
  • useCache (boolean): Default: true. If false, a new object will be created even if it had been previously loaded.

Returns:


tes3.lock⚓︎

Locks an object, and optionally sets a locked reference's lock level. Returns true if the object can be and wasn't already locked.

local locked = tes3.lock({ reference = ..., level = ... })

Parameters:

Returns:

  • locked (boolean)

tes3.loopTArray⚓︎

This function returns a function that iterates over a tes3tarray object. This is useful for for loops.

local iterationFunction = tes3.loopTArray(tarray)

Parameters:

Returns:


tes3.makeSafeObjectHandle⚓︎

Returns a safe handle for the object. To get the object use :getObject(). To check if it still exists use :valid().

local safeObjectHandle = tes3.makeSafeObjectHandle(object)

Parameters:

Returns:

Example: Example
local function doMyRayTest()
    -- the result can get invalidated
    local result = tes3.rayTest({
        position = tes3.getPlayerEyePosition(),
        direction = tes3.getPlayerEyeVector(),
        ignore = { tes3.player }
    })

    if not result then
        return
    end

    local refHandle = tes3.makeSafeObjectHandle(result.reference)
    timer.start({
        type = timer.simulate,
        duration = 20,
        iterations = 1,
        callback = function()
            -- Before using the reference, we need to check that it's still valid.
            -- References get unloaded on cell changes etc.
            if not refHandle:valid() then
                return
            end
            local reference = refHandle:getObject()
            -- Now we can use the `reference` variable safely
            -- ...
        end
    })
end

tes3.menuMode⚓︎

Returns true if the player is currently in menu mode.

local inMenuMode = tes3.menuMode()

Returns:

  • inMenuMode (boolean)

tes3.messageBox⚓︎

Displays a message box. This may be a simple toast-style message, or a box with choice buttons.

local element = tes3.messageBox({ message = ..., buttons = ..., callback = ..., showInDialog = ..., duration = ... }, ...)

Parameters:

  • messageOrParams (boolean, number, string, table)
    • message (string)
    • buttons (string[]): Optional. An array of strings to use for buttons. Maximal text length on each button is 32 characters.
    • callback (fun(e: tes3messageBoxCallbackData)): Optional. The callback function will be executed after a button was pressed. The callback function will be passed a table with button field corresponding to 0-based index of the button from passed buttons array.
    • showInDialog (boolean): Default: true. Specifying showInDialog = false forces the toast-style message, which is not shown in the dialog menu.
    • duration (number): Optional. Overrides how long the toast-style message remains visible.
  • ... (any): Optional. Formatting arguments. These are passed to string.format, provided messageOrParams is a string.

Returns:

  • element (tes3uiElement, nil): The UI menu created for the notification, if any.
Example: A message box with a callback function

This demonstrates how to determine which button was pressed inside callback function.

-- This variable is used to store a function that will be
-- registered as a callback when a button is pressed inside
-- our messageBox. The function's body is declared later.
local onButtonPressed


-- This function is registered to execute when U key is pressed.
local function onKeyPressed()
    tes3.messageBox({
        message = "Do you want a muffin?",
        buttons = { "Yes", "No" },
        showInDialog = false,
        callback = onButtonPressed,
    })
end
event.register(tes3.event.keyDown, onKeyPressed, { filter = tes3.scanCode.u })

-- Here we define the body of our function.
onButtonPressed = function(e)
    -- This corresponds to the first button
    --  of our message, which is "Yes"
    if e.button == 0 then
        tes3.addItem({
            reference = tes3.player,
            item = "ingred_bread_01_UNI3",
        })
    else
        -- Do nothing
    end
end

tes3.modStatistic⚓︎

Modifies a statistic on a given actor. This should be used instead of manually setting values on the game structures, to ensure that events and GUI elements are properly handled. Either skill, attribute, or the statistic's property name must be provided.

tes3.modStatistic({ reference = ..., attribute = ..., skill = ..., name = ..., base = ..., current = ..., value = ..., limit = ..., limitToBase = ... })

Parameters:

  • params (table)
    • reference (tes3mobileActor, tes3reference, string)
    • attribute (tes3.attribute): Optional. The attribute to set. Uses a value from tes3.attribute
    • skill (tes3.skill): Optional. The skill to set. Uses a value from tes3.skill
    • name (string): Optional. The property name of the statistic to set. The names can be taken from the properties of tes3mobileNPC or tes3mobileCreature. Useful for specifying health, magicka, fatigue or encumbrance.
    • base (number): Optional. If set, the base value will be modified.
    • current (number): Optional. If set, the current value will be modified.
    • value (number): Optional. If set, both the base and current value will be modified.
    • limit (boolean): Default: false. If set, the attribute won't rise above 100 or fall below 0.
    • limitToBase (boolean): Default: false. If set, the attribute's current value won't rise above its base value. Useful for health, magicka, and fatigue.
Example: Decrease Health of an Actor

In this simple example, the current health of an actor, the player, is decreased by 10. To simulate actual combat damage, you should use tes3mobileActor.applyDamage.

tes3.modStatistic({
    reference = tes3.mobilePlayer,
    name = "health",
    current = -10
})
Example: Restore Magicka without Overflowing

Magicka is restored without exceeding the magicka pool using the limitToBase flag.

tes3.modStatistic({
    reference = tes3.mobilePlayer,
    name = "magicka",
    current = 20,
    limitToBase = true
})

tes3.newGame⚓︎

Starts a new game.

tes3.newGame()

tes3.onMainMenu⚓︎

Returns true if the player is on the main menu, and hasn't loaded a game yet.

local onMainMenu = tes3.onMainMenu()

Returns:

  • onMainMenu (boolean)

tes3.payMerchant⚓︎

Pays a merchant a specified amount of gold and updates the merchant's "last barter timer". This should be used to simulate paying for services. You may also want to play a trade-related sound of your choice upon successful completion.

If cost is positive, then that amount of gold will be removed from the player's inventory and added to the merchant's available barter gold.

If cost is negative, then that amount of gold will be added to the player's inventory and removed from the merchant's available barter gold.

local success = tes3.payMerchant({ merchant = ..., cost = ... })

Parameters:

  • params (table)
    • merchant (tes3mobileActor): The merchant to pay.
    • cost (number): The amount of gold to pay the merchant. If negative, the merchant will pay the player.

Returns:

  • success (boolean): true if the transaction completed. false if there was not enough gold.

tes3.persuade⚓︎

Attempts a persuasion attempt on an actor, potentially adjusting their disposition. Returns true if the attempt was a success.

local success = tes3.persuade({ actor = ..., index = ..., modifier = ... })

Parameters:

  • params (table)
    • actor (tes3mobileActor, tes3reference, string): The actor to try to persuade.
    • index (number): Optional. If an index is provided, 0-indexed with the following results: admire, intimidate, taunt, bribe (10), bribe (100), bribe (1000).
    • modifier (number): Optional. If no index is provided, this is the direct modifier to try. The higher the modifer the higher the chance of a successful persuation, and higher disposition change.

Returns:

  • success (boolean)

tes3.playAnimation⚓︎

Plays a given animation group. Optional flags can be used to define how the group starts.

When 'group' is specified, the actor AI is paused while playing the animation, as if in an idle state. When one or more of 'lower', 'upper', or 'shield' are specified without 'group', the actor AI retains control, and the animations are layered. e.g. tes3.playAnimation{reference = ..., upper = tes3.animationGroup.idle3, loopCount = 0} will play the idle3 animation once (without looping) on the upper body, while the player or NPC is still able to walk around. Using 'upper' defers combat actions until the animation is done. Using 'shield' still allows combat actions.

As a special case, tes3.playAnimation{reference = ..., group = 0} returns control to the AI, as the AI knows that is the actor's neutral idle state.

tes3.playAnimation({ reference = ..., group = ..., lower = ..., upper = ..., shield = ..., startFlag = ..., loopCount = ..., mesh = ... })

Parameters:

  • params (table)
    • reference (tes3mobileActor, tes3reference, string): The reference that will play the animation.
    • group (tes3.animationGroup): Optional. The animation group id to start playing -- a value from 0 to 149. Applies the animation to the whole body. Maps to tes3.animationGroup constants.
    • lower (tes3.animationGroup): Optional. Sets the animation group id for the lower body. This is used to combine different animations for each body section. Maps to tes3.animationGroup constants.
    • upper (tes3.animationGroup): Optional. Sets the animation group id for the upper body. This is used to combine different animations for each body section. Maps to tes3.animationGroup constants.
    • shield (tes3.animationGroup): Optional. Sets the animation group id for the shield arm. This is used to combine different animations for each body section. Maps to tes3.animationGroup constants.
    • startFlag (tes3.animationStartFlag): Default: tes3.animationStartFlag.immediate. A flag for starting the group with, using tes3.animationStartFlag constants.
    • loopCount (number): Default: -1. If provided, the animation will repeat its loop section a given number of times. To make an animation play through once, set loopCount = 0. Defaults to infinite looping.
    • mesh (string): Optional. Deprecated. Please use tes3.loadAnimation (check its documentation) before calling playAnimation. You can also use loadAnimation to reset loaded animations to default.

tes3.playItemPickupSound⚓︎

Plays the sound responsible for picking up or putting down an item.

local executed = tes3.playItemPickupSound({ reference = ..., item = ..., pickup = ... })

Parameters:

  • params (table)
    • reference (tes3reference, tes3mobileActor, string): Optional. The reference to attach the sound to.
    • item (tes3item, string): The appropriate item up/down sound will be played for item of this type.
    • pickup (boolean): Default: true. If false, the place down item will be used.

Returns:

  • executed (boolean)

tes3.playSound⚓︎

Plays a sound on a given reference. Provides control over volume (including volume channel), pitch, and loop control. Triggers addTempSound event if soundPath argument is passed, triggers playSound or soundObjectPlay otherwise.

Note: MP3 sound files can only be played if they are inside \Vo\ folder. The files must conform to the MPEG Layer-3, 64 Kbps 44100 kHz, 16-bit mono specification.

local executed = tes3.playSound({ sound = ..., reference = ..., loop = ..., mixChannel = ..., volume = ..., pitch = ..., soundPath = ... })

Parameters:

  • params (table)
    • sound (tes3sound, string): Optional. The sound object, or id of the sound to look for.
    • reference (tes3reference, tes3mobileActor, string): Optional. The reference to attach the sound to. If no reference is provided, the sound will be played directly and soundObjectPlay will be triggered instead of playSound.
    • loop (boolean): Default: false. If true, the sound will loop.
    • mixChannel (tes3.soundMix): Default: tes3.soundMix.effects. The channel to base volume off of. Maps to tes3.soundMix constants.
    • volume (number): Default: 1.0. A value between 0.0 and 1.0 to scale the volume off of.
    • pitch (number): Default: 1.0. The pitch-shift multiplier. For 22kHz audio (most typical) it can have the range [0.005, 4.5]; for 44kHz audio it can have the range [0.0025, 2.25].
    • soundPath (string): Optional. The path to a custom soundfile (useful for playing sounds that are not registered in the Construction Set). Starts in Data Files\Sound.

Returns:

  • executed (boolean)

tes3.playVoiceover⚓︎

Causes a target actor to play a voiceover. To stop a currently playing voiceover see tes3.removeSound().

local played = tes3.playVoiceover({ actor = ..., voiceover = ... })

Parameters:

Returns:

  • played (boolean)

tes3.positionCell⚓︎

Positions a reference to another place.

local executed = tes3.positionCell({ reference = ..., cell = ..., position = ..., orientation = ..., forceCellChange = ..., suppressFader = ..., teleportCompanions = ... })

Parameters:

  • params (table)
    • reference (tes3reference, tes3mobileActor, string): Default: tes3.mobilePlayer. The reference to reposition.
    • cell (tes3cell, string, table, nil): Optional. The cell to move the reference to. Can be a tes3cell, cell name, or a table with two values that correspond to the exterior cell's grid coordinates. If not provided, the reference will be moved to a cell in the exterior worldspace at the position provided.
    • position (tes3vector3, number[]): The position to move the reference to.
    • orientation (tes3vector3, number[]): Optional. The new orientation of the reference.
    • forceCellChange (boolean): Default: false. When true, forces the game to update a reference that has moved within a single cell, as if it was moved into a new cell.
    • suppressFader (boolean): Default: false. When moving the player, can be used to prevent the fade in and out visual effect.
    • teleportCompanions (boolean): Default: true. If used on the player, determines if companions should also be teleported.

Returns:

  • executed (boolean)

tes3.pushKey⚓︎

Simulates pushing a keyboard key.

tes3.pushKey(keyCode)

Parameters:


tes3.random⚓︎

Returns a value from Morrowind's random number generator. This is not preferrable to lua's math.random function, but may be necessary for reproducing Morrowind's generation.

tes3.random(seed)

Parameters:

  • seed (number): Optional. If provided, it the number generator is seeded with this value. Pointers to objects may be used, such as a reference's sceneNode, to create a consistent if less than random seed.

tes3.rayTest⚓︎

Performs a ray test and returns various information related to the result(s). The ray test works by effectively shooting out a line, starting at position and pointing towards direction, and then checking to see which objects intersect that line.

Here is an overview of how some commonly used parameters will alter how tes3.rayTest checks for collisions:

  1. root: Things that aren't a child of the specified root will be skipped. If root is not provided, then nothing will be skipped by this process.
  2. ignore: Objects in this array will be skipped.
  3. maxDistance: If specified, only objects within the specified distance will be checked.
  4. findAll: If true, then all intersections will be returned. Otherwise, only the first intersection will be returned.

Tip

The performance of tes3.rayTest depends quite a bit on the parameters the function is called with. The following suggestions will help to minimize the performance impact of calls to tes3.rayTest.

  1. Set a maxDistance.
  2. Filter objects by using the root parameter. This will make the algorithm much faster, and can make it behave more predictably as well. If you're only checking for interactable objects (containers/actors/plants/etc), use worldPickRoot. If you're looing for static, non-interable objects, use worldObjectRoot. You could even pass a smaller subset of the scene graph with a different NiNode you aquired yourself.
  3. Try to keep a cached copy of the array used for the ignore parameter (if possible).
  4. Keep maximum size of objects reasonable, and try to limit triangle counts.
local result = tes3.rayTest({ position = ..., direction = ..., findAll = ..., maxDistance = ..., ignore = ..., root = ..., useModelBounds = ..., useModelCoordinates = ..., useBackTriangles = ..., observeAppCullFlag = ..., accurateSkinned = ..., sort = ..., returnColor = ..., returnNormal = ..., returnSmoothNormal = ..., returnTexture = ... })

Parameters:

  • params (table)
    • position (tes3vector3, number[]): Position of the ray origin.
    • direction (tes3vector3, number[]): Direction of the ray. Does not have to be unit length.
    • findAll (boolean): Default: false. If true, the ray test won't stop after the first result.
    • maxDistance (number): Default: 0. The maximum distance that the test will run. If set to 0, no maximum distance will be used.
    • ignore (table<integer, niNode|tes3reference>): Optional. An array of references and/or scene graph nodes to cull from the result(s).
    • root (niNode): Default: tes3.game.worldRoot. Node pointer to node scene. Only nodes that are a child of this root will be checked by this function. This option can considerably increase performance if used properly. Common choices for the root node are: tes3.game.worldLandscapeRoot, worldObjectRoot (for most static objects), and worldPickRoot (for containers, NPCs, plants, doors, etc).
    • useModelBounds (boolean): Default: false. If true, model bounds will be tested for intersection. Otherwise triangles will be used. This will result in more accurate collision testing, but will be more computationally expensive. This is rarely needed.
    • useModelCoordinates (boolean): Default: false. If true, model coordinates will be used instead of world coordinates. Typically not needed.
    • useBackTriangles (boolean): Default: false. Include intersections with back-facing triangles. This essentially makes it possible to intersect with the "back-side" of an object, which could make it possible to return a hit on an object if the position parameter is "inside" the object in question.This will result in more accurate collision testing, but will be more computationally expensive. This is rarely needed.
    • observeAppCullFlag (boolean): Default: true. Ignore intersections with culled (hidden) models.
    • accurateSkinned (boolean): Default: false. If true, skinned objects will be deformed, allowing for more accurate collision checking. This significantly slows down the operation, and is rarely needed.
    • sort (boolean): Default: true. Sort results by distance from the specified position? Only applicable if findAll == true.
    • returnColor (boolean): Default: false. Calculate and return the vertex color at intersections?
    • returnNormal (boolean): Default: false. Calculate and return the vertex normal at intersections?
    • returnSmoothNormal (boolean): Default: false. Use normal interpolation for calculating vertex normals?
    • returnTexture (boolean): Default: false. Calculate and return the texture coordinate at intersections?

Returns:

Example: Get Activation Target

This example performs a tes3.rayTest to match the normal activation target test. Unlike tes3.getPlayerTarget() this will return objects not normally available for activation.

local hitResult = tes3.rayTest({ position = tes3.getPlayerEyePosition(), direction = tes3.getPlayerEyeVector() })
local hitReference = hitResult and hitResult.reference
if (hitReference == nil) then
    return
end

tes3.messageBox("The player is looking at a '%s'", hitReference.object.name or hitReference.object.id)
Example: Get Camera Target

See what the player's camera is looking at.

local hitResult = tes3.rayTest({ position = tes3.getCameraPosition(), direction = tes3.getCameraVector() })
local hitReference = hitResult and hitResult.reference
if (hitReference == nil) then
    return
end

tes3.messageBox("The camera is looking at a '%s'", hitReference.object.name or hitReference.object.id)
Example: Multiple Results

This example performs a tes3.rayTest and displays all results in the entire ray test, rather than ending at the first object hit.

local results = tes3.rayTest{ position = tes3.getCameraPosition(), direction = tes3.getCameraVector(), findAll = true }
if results then
    for i, hit in pairs(results) do
        mwse.log("Ray hit #%d: %s", i, hit.reference or "<non-reference>");
    end
end
Example: Save tes3.rayTest result for use at a later point

If you plan to use the results of rayTest, you should make sure it still exists. For example, an object which was in a list of results of rayTest can get unloaded when the player changes cells and become invalid, so it shouldn't be accessed.

local function doMyRayTest()
    -- the result can get invalidated
    local result = tes3.rayTest({
        position = tes3.getPlayerEyePosition(),
        direction = tes3.getPlayerEyeVector(),
        ignore = { tes3.player }
    })

    if not result then
        return
    end

    local refHandle = tes3.makeSafeObjectHandle(result.reference)
    timer.start({
        type = timer.simulate,
        duration = 20,
        iterations = 1,
        callback = function()
            -- Before using the reference, we need to check that it's still valid.
            -- References get unloaded on cell changes etc.
            if not refHandle:valid() then
                return
            end
            local reference = refHandle:getObject()
            -- Now we can use the `reference` variable safely
            -- ...
        end
    })
end

tes3.releaseKey⚓︎

Simulates releasing a keyboard key.

tes3.releaseKey(keyCode)

Parameters:


tes3.removeEffects⚓︎

Removes magic effects from a given reference. Requires that either the effect or castType parameter be provided.

tes3.removeEffects({ reference = ..., effect = ..., castType = ..., chance = ..., removeSpell = ... })

Parameters:

  • params (table)
    • reference (tes3reference): Target reference to remove effects from.
    • effect (tes3.effect, integer): Optional. Maps to tes3.effect constants.
    • castType (tes3.spellType): Optional. Maps to tes3.spellType constants.
    • chance (number): Default: 100. The chance for the effect to be removed.
    • removeSpell (boolean): Optional. If removing by cast type, determines if the spell should be removed from the target's spell list. Defaults to true if castType is not tes3.spellType.spell. This causes diseases and curses to be removed when dispelled.
Example: Simulating a Dispel

In this example there is a 50 % chance that any Water Breathing magic effects will be removed from the player when he/she is underwater.

local function example(e)
        -- We only care about the player
    if (e.mobile.objectType ~= tes3.objectType.mobilePlayer) then
        return
    end

    local cell = tes3.mobilePlayer.cell

    if (cell.isInterior and not cell.hasWater) then
        return
    end

    local waterLevel = cell.waterLevel
    local headPosition = tes3.mobilePlayer.position.z + tes3.mobilePlayer.height

    local underwater = headPosition < waterLevel

    if underwater then
        -- There is a 50 % chance that any Water Breathing effect will be removed from the player
        tes3.removeEffects({
            reference = tes3.player,
            chance = 50,
            effect = tes3.effect.waterBreathing,
        })
    end
end

event.register(tes3.event.initialized, function ()
    event.register(tes3.event.calcMoveSpeed, example)
end)

tes3.removeItem⚓︎

Removes an item from a given reference's inventory. Items without itemData will be removed first. The reference will be cloned if needed.

local removedCount = tes3.removeItem({ reference = ..., item = ..., itemData = ..., deleteItemData = ..., count = ..., playSound = ..., reevaluateEquipment = ..., updateGUI = ... })

Parameters:

  • params (table)
    • reference (tes3reference, tes3mobileActor, string): Who to remove items from.
    • item (tes3item, string): The item to remove.
    • itemData (tes3itemData): Optional. The item data for the exact item to remove.
    • deleteItemData (tes3itemData): Optional. Whether to delete the item data after remove succeeds. Automatically set if itemData is used. Does not need to be specified for normal usage.
    • count (number): Default: 1. The maximum number of items to remove.
    • playSound (boolean): Default: true. If false, the up/down sound for the item won't be played.
    • reevaluateEquipment (boolean): Default: true. If true, and the item removed is armor, clothing, or a weapon, the actor will reevaluate its equipment choices to see if it needs to equip a new item. This does not affect the player.
    • updateGUI (boolean): Default: true. If false, the function won't manually resync the player's GUI state. This can result in some optimizations, though tes3ui.forcePlayerInventoryUpdate() must manually be called after all inventory updates are finished.

Returns:

  • removedCount (number)

tes3.removeItemData⚓︎

Removes and deletes item data from a given reference, or from their inventory. If no itemData is provided, it will be removed from the reference itself.

local wasRemoved = tes3.removeItemData({ from = ..., item = ..., itemData = ..., force = ..., ignoreOwnership = ..., updateGUI = ... })

Parameters:

  • params (table)
    • from (tes3reference, tes3mobileActor, string): The reference or mobile whose inventory will be modified.
    • item (tes3item, string): The item to remove item data for.
    • itemData (tes3itemData): Optional. The exact item data to remove. If no itemData is provided, the itemData from the reference itself will be removed.
    • force (boolean): Default: false. If true, no checks are made to see if the item data should be deleted. It will always be purged.
    • ignoreOwnership (boolean): Default: true. If force is false, a check will be made to see if the item data is empty and can be deleted. By default this ignores any ownership data. Setting this to false will override that behavior.
    • updateGUI (boolean): Default: true. If false, the player or contents menu won't be updated.

Returns:

  • wasRemoved (boolean)

tes3.removeSound⚓︎

Stops a sound playing. Without a reference, it will match unattached sounds. With a reference, it will only match a sound playing on that specific reference. To stop a voiceover, pass the wanted actor as the reference parameter and sound = nil.

tes3.removeSound({ sound = ..., reference = ... })

Parameters:

  • params (table)
    • sound (tes3sound, string, nil): The sound object, or id of the sound to look for. If no sound is passed, removes every sound on the reference.
    • reference (tes3reference, tes3mobileActor, string): Optional. The reference the sound is attached to.

tes3.removeSpell⚓︎

Removes a spell from an actor's spell list. If the spell is passive, any active effects from that spell are retired. At least one of the actor, mobile or reference arguments needs to be passed.

local wasRemoved = tes3.removeSpell({ reference = ..., actor = ..., mobile = ..., spell = ..., updateGUI = ... })

Parameters:

  • params (table)
    • reference (tes3reference, tes3mobileActor, string): Optional. Who to remove the spell from. To manipulate an actor without specifying any particular reference, use actor instead.
    • actor (tes3actor, string): Optional. Who to remove the spell from. Providing a base actor can be done before a save has been loaded, but may not correctly update effects for instanced versions of that actor in an active save.
    • mobile (tes3reference, tes3mobileActor, string): Optional. Who to remove the spell from. To manipulate an actor without specifying any particular reference, use actor instead.
    • spell (tes3spell, string): The spell to remove.
    • updateGUI (boolean): Default: true. If true, the GUI will be updated respecting the removal of the spell. This can be useful to disable when batch-removing many spells. The batch should be ended with tes3.updateMagicGUI to reflect the changes.

Returns:

  • wasRemoved (boolean): True if the spell was successfully removed. This can be false if the spell comes from a race or birthsign.

tes3.removeVisualEffect⚓︎

Removes one or more visual effects created either through magical effects or tes3.createVisualEffect().

local removedCount = tes3.removeVisualEffect({ vfx = ..., avObject = ..., serial = ..., reference = ... })

Parameters:

  • params (table)
    • vfx (tes3vfx): Optional. If provided, the specific VFX handle will be deleted.
    • avObject (niAVObject): Optional. If provided, any VFXs associated with the given niAVObject will be deleted.
    • serial (number): Optional. The magic source instance serial number to remove effects for. This must be paired with a reference as well.
    • reference (tes3reference, string): Optional. The reference to remove all visual effects from. A serial may also be provided.

Returns:

  • removedCount (number): The amount of VFX removed by this function call.

tes3.runLegacyScript⚓︎

This function will compile and run a mwscript chunk of code. This is not ideal to use, but can be used for features not yet exposed to lua.

local executed = tes3.runLegacyScript({ script = ..., source = ..., command = ..., variables = ..., reference = ..., dialogue = ..., info = ... })

Parameters:

  • params (table)
    • script (tes3script, string): Default: tes3.worldController.scriptCompileAndRun. The base script to base the execution from.
    • source (tes3.compilerSource): Default: tes3.compilerSource.default. The compilation source to use.
    • command (string): Optional. The script text to compile and run.
    • variables (tes3scriptVariables): Optional. If a reference is provided, the reference's variables will be used.
    • reference (tes3reference, tes3mobileActor, string): Optional. The reference to target for execution.
    • dialogue (tes3dialogue, string): Optional. If compiling for dialogue context, the dialogue associated with the script.
    • info (tes3dialogueInfo): Optional. The info associated with the dialogue.

Returns:

  • executed (boolean)

tes3.saveGame⚓︎

Saves the game.

local saved = tes3.saveGame({ file = ..., name = ... })

Parameters:

  • params (table)
    • file (string): Default: "quiksave". The filename of the save that will be created, without extension.
    • name (string): Default: "Quicksave". The display name of the save.

Returns:

  • saved (boolean)

tes3.say⚓︎

Plays a sound file, with an optional alteration and subtitle. Triggers addTempSound event.

Note: MP3 voice files must conform to the MPEG Layer-3, 64 Kbps 44100 kHz, 16-bit mono specification.

tes3.say({ reference = ..., soundPath = ..., pitch = ..., volume = ..., forceSubtitle = ..., subtitle = ... })

Parameters:

  • params (table)
    • reference (tes3reference, tes3mobileActor, string): The reference to make say something.
    • soundPath (string): A path to a valid sound file. Starts in Data Files\Sound.
    • pitch (number): Default: 1.0. A pitch shift to adjust the sound with.
    • volume (number): Default: 1.0. The volume to play the sound at, relative to the voice mix channel.
    • forceSubtitle (boolean): Default: false. If true a subtitle will be shown, even if subtitles are disabled.
    • subtitle (string): Optional. The subtitle to show if subtitles are enabled, or if forceSubtitle is set.

tes3.set3rdPersonCameraOffset⚓︎

Changes the 3rd person camera offset from the player's head.

Note

This function can be used once tes3worldController and tes3mobilePlayer have finished initializing.

tes3.set3rdPersonCameraOffset({ offset = ... })

Parameters:

  • params (table)

tes3.setAIActivate⚓︎

Configures a mobile actor to activate an object.

tes3.setAIActivate({ reference = ..., target = ..., reset = ... })

Parameters:


tes3.setAIEscort⚓︎

Configures a mobile actor to escort another actor to a destination. Escorting actor will protect and wait for the escortee to catch up. Its advisible to make the target actor follow the escorting actor with tes3.setAIFollow(), because the escorting actor will otherwise wait the escortee forever.

tes3.setAIEscort({ reference = ..., target = ..., destination = ..., duration = ..., cell = ..., reset = ... })

Parameters:


tes3.setAIFollow⚓︎

Configures a mobile actor to follow another actor to a destination.

tes3.setAIFollow({ reference = ..., target = ..., destination = ..., duration = ..., cell = ..., reset = ... })

Parameters:


tes3.setAITravel⚓︎

Configures a mobile actor to travel to a destination.

tes3.setAITravel({ reference = ..., destination = ..., reset = ... })

Parameters:


tes3.setAIWander⚓︎

Configures a mobile actor to wander around a cell.

tes3.setAIWander({ reference = ..., idles = ..., range = ..., duration = ..., time = ..., reset = ... })

Parameters:

  • params (table)
    • reference (tes3mobileActor, tes3reference): This actor will wander around.
    • idles (integer[]): An array with 8 values that corresponds to the chance of playing each idle animation. For more info see tes3aiPackageWander.idles.
    • range (integer): Default: 0.
    • duration (integer): Default: 0. How long the actor will be wandering around, in hours.
    • time (integer): Default: 0.
    • reset (boolean): Default: true.

tes3.setAnimationTiming⚓︎

This function sets a reference's animation groups' timings to a specified value.

tes3.setAnimationTiming({ reference = ..., timing = ... })

Parameters:

  • params (table)
    • reference (tes3reference, tes3mobileActor, string): A reference whose animation groups' timings to set.
    • timing (number, table): If one parameter is provided, all animation data timings will be set to the timing provided. If a table with 3 timings is provided, animation data timings will be set accordingly.

tes3.setDestination⚓︎

Sets or changes the destination of a door to a new location.

tes3.setDestination({ reference = ..., position = ..., orientation = ..., cell = ... })

Parameters:

  • params (table)
    • reference (tes3reference): The door reference that will be updated.
    • position (tes3vector3, number[]): The new coordinates of the transition.
    • orientation (tes3vector3, number[]): The new rotation to use after transition.
    • cell (tes3cell, string): Optional. The cell to transition to, if transitioning to an interior.

tes3.setEnabled⚓︎

Enables or disables a reference.

local success = tes3.setEnabled({ reference = ..., toggle = ..., enabled = ... })

Parameters:

  • params (table)
    • reference (tes3reference, tes3mobileActor, string): The reference to enable/disable.
    • toggle (boolean): Default: false. If true, the enabled state will be toggled.
    • enabled (boolean): Default: true. If not toggling, setting enabled to true will enable the reference or to false will disable the reference.

Returns:

  • success (boolean)

tes3.setExpelled⚓︎

This function can expel and undo expelled state for the player in the given faction.

tes3.setExpelled({ faction = ..., expelled = ... })

Parameters:

  • params (table)
    • faction (tes3faction): The faction the player will be expelled from.
    • expelled (boolean): Default: true. Passing false will make the player regain membership.

tes3.setGlobal⚓︎

Sets the value of a global value. If the global could not be found, the function returns false.

local value = tes3.setGlobal(id, value)

Parameters:

  • id (string)
  • value (number)

Returns:

  • value (boolean)

tes3.setItemIsStolen⚓︎

This function changes an item's stolen flag. Morrowind handles stealing by marking the base item (not the inventory stack) with NPCs that you have stolen that item from. The NPC will recognize an item as stolen if they are marked as stolen on the base item.

tes3.setItemIsStolen({ item = ..., from = ..., stolen = ... })

Parameters:

  • params (table)
    • item (tes3item): The item whose stolen flag to modify.
    • from (tes3creature, tes3npc, tes3faction, nil): Who or what to set/clear the stolen state for. If not provided, the stolen state can be cleared (but not set) for all objects.
    • stolen (boolean): Default: true. If this parameter is set to true, the item will be flagged as stolen. Otherwise, the item's stolen flag will be removed.

tes3.setJournalIndex⚓︎

Sets the index of a given journal in a way similar to the mwscript function SetJournalIndex.

local wasSet = tes3.setJournalIndex({ id = ..., index = ..., showMessage = ... })

Parameters:

  • params (table)
    • id (tes3dialogue, string)
    • index (integer)
    • showMessage (boolean): Default: false. If set, a message may be shown to the player.

Returns:

  • wasSet (boolean)

tes3.setKillCount⚓︎

Sets player's kill count of a certain type of actor.

tes3.setKillCount({ actor = ..., count = ... })

Parameters:

  • params (table)
    • actor (tes3actor, string): The actor (or their ID) for whom to set player's kill count.
    • count (number): Number of kills that will be set.

tes3.setLockLevel⚓︎

Sets a locked reference's lock level. This does not lock the object.

local set = tes3.setLockLevel({ reference = ..., level = ... })

Parameters:

Returns:

  • set (boolean)

tes3.setMarkLocation⚓︎

This function sets the player's mark location to the one specified.

tes3.setMarkLocation({ position = ..., rotation = ..., cell = ... })

Parameters:

  • params (table)
    • position (tes3vector3, number[]): Coordinates of the mark's position.
    • rotation (number): Default: tes3.player.orientation.z. This argument controls which direction the player's mark location will be facing.
    • cell (tes3cell): Optional. A cell in which the mark should be placed. This argument is unnecessary when setting the Mark's location to an exterior cell.

tes3.setOwner⚓︎

This function sets the owner of a reference.

tes3.setOwner({ reference = ..., remove = ..., owner = ..., requiredGlobal = ..., requiredRank = ... })

Parameters:

  • params (table)
    • reference (tes3reference, tes3mobileActor, string): A reference whose owner to set.
    • remove (boolean): Default: false. If this parameter is set to true, reference's owner field will be removed.
    • owner (tes3npc, tes3npcInstance, tes3mobileNPC, tes3mobileCreature, tes3reference, tes3faction, string): Optional. Assigns this NPC or a faction as the owner of the reference.
    • requiredGlobal (tes3globalVariable): Optional. If owner is set to NPC, requiredGlobal variable can be set.
    • requiredRank (number): Default: 0. If owner is set to faction, requitedRank variable controls minimal rank in faction the player has to have to be able to freely take the reference.

tes3.setPlayerControlState⚓︎

Enables or disables player's controls state.

local changedControlState = tes3.setPlayerControlState({ enabled = ..., attack = ..., jumping = ..., magic = ..., vanity = ..., viewSwitch = ... })

Parameters:

  • params (table): Optional.
    • enabled (boolean): Default: false. Setting this to false will disable any kind of control.
    • attack (boolean): Default: false. If this is false, it will block player from attacking.
    • jumping (boolean): Default: false. If this is false, it will block player from jumping.
    • magic (boolean): Default: false. If this is false, it will block player from using magic.
    • vanity (boolean): Default: false. If this is false, it will block player from going to vanity mode.
    • viewSwitch (boolean): Default: false. If this is false, it will block player changing view mod from 1st to 3rd person camera and vice versa.

Returns:

  • changedControlState (boolean)

tes3.setSourceless⚓︎

Sets an object (of any kind) to be sourceless, which are objects the game does not store in savegames. This can be useful for mod-created temporary objects which are not necessary to save.

tes3.setSourceless(object, sourceless)

Parameters:

  • object (tes3baseObject): The object whose sourceless flag to modify.
  • sourceless (boolean): Default: true. Allows flagging an object as sourceless or undoing that action.

tes3.setStatistic⚓︎

Sets a statistic on a given actor. This should be used instead of manually setting values on the game structures, to ensure that events and GUI elements are properly handled. Either skill, attribute, or the statistic's property name must be provided.

tes3.setStatistic({ reference = ..., attribute = ..., skill = ..., name = ..., base = ..., current = ..., value = ..., limit = ... })

Parameters:

  • params (table)
    • reference (tes3mobileActor, tes3reference, string)
    • attribute (tes3.attribute, integer): Optional. The attribute to set. Uses a value from tes3.attribute
    • skill (tes3.skill, integer): Optional. The skill to set. Uses a value from tes3.skill
    • name (string): Optional. The property name of the statistic to set. The names can be taken from the properties of tes3mobileNPC or tes3mobileCreature. Useful for specifying health, magicka, fatigue or encumbrance.
    • base (number): Optional. If set, the base value will be set.
    • current (number): Optional. If set, the current value will be set.
    • value (number): Optional. If set, both the base and current value will be set.
    • limit (boolean): Default: false. If set, the attribute won't rise above 100 or fall below 0.

tes3.setTrap⚓︎

Sets the trap on a given reference.

local trapped = tes3.setTrap({ reference = ..., spell = ... })

Parameters:

Returns:

  • trapped (boolean)
Example: Untrapping a door or container the player is looking at
---@param reference tes3reference
---@return boolean untrapped
local function untrap(reference)
    local object = reference.object

    -- Skip objects that can't be trapped.
    if object.objectType ~= tes3.objectType.door
    or object.objectType ~= tes3.objectType.container then
        return false
    end

    tes3.setTrap({
        reference = reference,
        spell = nil
    })
    -- Let the game update the activation tooltip otherwise,
    -- the tooltip would still say "Trapped".
    tes3.game:clearTarget()

    return true
end

-- To test aim at a trapped door or container and press "u" key.
local function onKeyDown()
    -- Get the player's target and apply it's spell
    -- on the player if it's trapped.

    local target = tes3.getPlayerTarget()
    if not target then return end

    untrap(target)
end
event.register(tes3.event.keyDown, onKeyDown, { filter = tes3.scanCode.u })

tes3.setVanityMode⚓︎

Toggles the camera into vanity mode. In vanity mode the camera is in third person and it is orbiting slowly around the player character. Returns true if changed to vanity mode.

Note that unlike the vanity mode caused by not doing anything for a while, this vanity mode must be toggled to go off.

local changedVanityMode = tes3.setVanityMode({ enabled = ..., checkVanityDisabled = ..., toggle = ... })

Parameters:

  • params (table): Optional.
    • enabled (boolean): Default: true. This flag sets the vanity mode as enabled or disabled.
    • checkVanityDisabled (boolean): Default: true. This will prevent changing vanity mode according to vanityDisabled flag on tes3.mobilePlayer.
    • toggle (boolean): Default: false. When this flag is set to true. The vanity mode will be toggled. If the player was in vanity mode, this will make the player leave vanity mode. Conversly, if the player wasn't in the vanity mode, this will turn on the vanity mode.

Returns:

  • changedVanityMode (boolean)

tes3.setWerewolfKillCount⚓︎

Sets player's kill count as a werewolf.

tes3.setWerewolfKillCount({ count = ... })

Parameters:

  • params (table)
    • count (number): Number of kills.

tes3.showAlchemyMenu⚓︎

This function opens the alchemy menu.

tes3.showAlchemyMenu()

tes3.showContentsMenu⚓︎

This function opens the contents menu. This menu is used for containers, companion inventories, and pickpocket attempts.

local wasShown = tes3.showContentsMenu({ reference = ..., pickpocket = ... })

Parameters:

  • params (table)
    • reference (tes3mobileActor, tes3reference, string): The reference to open the contents of.
    • pickpocket (boolean): Default: false. If true, the contents menu will open in the context of an attempted pickpocketing.

Returns:

  • wasShown (boolean): If true, the contents menu was successfully shown.

tes3.showDialogueMenu⚓︎

This function opens the dialogue menu. This behaves similar to the ForceGreeting mwscript command.

local wasShown = tes3.showDialogueMenu({ reference = ..., checkAllowWerewolfForceGreeting = ... })

Parameters:

  • params (table)
    • reference (tes3mobileActor, tes3reference, string): The reference to open dialogue with.
    • checkAllowWerewolfForceGreeting (boolean): Default: true. If true, the AllowWerewolfForceGreeting variable must exist on the reference's script to allow opening a dialogue while the player is a werewolf. This can be set to false to override the vanilla behavior.

Returns:

  • wasShown (boolean): If true, the dialogue window was successfully shown.

tes3.showRepairServiceMenu⚓︎

This function opens the repair service menu.

tes3.showRepairServiceMenu({ serviceActor = ... })

Parameters:

  • params (table): Optional.

tes3.showRestMenu⚓︎

This function opens the resting menu and returns true on success. If the player can't rest currently, it returns false.

Various parameters can be used to allow resting in situations not normally possible.

local success = tes3.showRestMenu({ checkForEnemies = ..., checkForSolidGround = ..., checkSleepingIllegal = ..., checkIsWerewolf = ..., showMessage = ..., resting = ..., waiting = ... })

Parameters:

  • params (table): Optional.
    • checkForEnemies (boolean): Default: true. Perform a check whether there are enemies nearby before opening rest menu. If there are, false is returned.
    • checkForSolidGround (boolean): Default: true. Perform a check if the player is underwater. If underwater, false is returned.
    • checkSleepingIllegal (boolean): Default: true. Perform a check if the sleeping in the current cell is illegal. If illegal, then the player will be prompted to wait instead of rest.
    • checkIsWerewolf (boolean): Default: true. Perform a check if the player is Werewolf. If they are, then the player will be prompted to wait instead of rest.
    • showMessage (boolean): Default: true. Should a messagebox be shown if the player can't open resting menu because some condition isn't met.
    • resting (boolean): Default: true. Should this be a rest?
    • waiting (boolean): Default: false. Or, is this a wait?

Returns:

  • success (boolean)

tes3.showSpellmakingMenu⚓︎

This function opens the spellmaking menu and returns true on success.

local success = tes3.showSpellmakingMenu({ serviceActor = ..., useDialogActor = ... })

Parameters:

  • params (table)
    • serviceActor (tes3mobileActor, tes3reference, string): Optional. The actor to use for calculating the service price. If none is provided, an open dialog menu's service actor will be used instead.
    • useDialogActor (boolean): Default: true. If set to false, the dialog menu service actor will be ignored. If false, a serviceActor must be provided.

Returns:

  • success (boolean)

tes3.skipAnimationFrame⚓︎

Skips a given reference's animation for a single frame.

tes3.skipAnimationFrame({ reference = ... })

Parameters:


tes3.skipToNextMusicTrack⚓︎

This function interrupts the current music to play a random new combat or explore track, as appropriate. The selected music track can be read from the audio controller's .nextMusicFilePath field.

local musicTrackQueued = tes3.skipToNextMusicTrack({ situation = ..., crossfade = ..., volume = ..., force = ... })

Parameters:

  • params (table)
    • situation (tes3.musicSituation): Optional. Determines what kind of gameplay situation the music should activate for. By default, the function will determine the right solution based on the player's combat state. This value maps to tes3.musicSituation constants.
    • crossfade (number): Default: 1.0. The duration in seconds of the crossfade from the old to the new track. The default is 1.0.
    • volume (number): Optional. The volume at which the music will play. If no volume is provided, the user's volume setting will be used.
    • force (boolean): Default: false. If true, normally uninterruptible music will be overwritten to instead play the new track.

Returns:

  • musicTrackQueued (boolean)

tes3.stopLegacyScript⚓︎

This function stops a global mwscript.

tes3.stopLegacyScript({ script = ... })

Parameters:

  • params (table)
    • script (tes3script, string): The script to stop.

tes3.streamMusic⚓︎

This function interrupts the current music to play the specified music track.

local executed = tes3.streamMusic({ path = ..., situation = ..., crossfade = ..., volume = ... })

Parameters:

  • params (table)
    • path (string): Path to the music file, relative to Data Files/music/.
    • situation (tes3.musicSituation): Default: tes3.musicSituation.uninterruptible. Determines what kind of gameplay situation the music should stay active for. Explore music plays during non-combat, and ends when combat starts. Combat music starts during combat, and ends when combat ends. Uninterruptible music always plays, ending only when the track does. This value maps to tes3.musicSituation constants.
    • crossfade (number): Default: 1.0. The duration in seconds of the crossfade from the old to the new track. The default is 1.0.
    • volume (number): Optional. The volume at which the music will play. If no volume is provided, the user's volume setting will be used.

Returns:

  • executed (boolean)

tes3.tapKey⚓︎

Simulates tapping a keyboard key.

tes3.tapKey(keyCode)

Parameters:


tes3.testLineOfSight⚓︎

Checks if there is a clear line of sight between two references, or two points in space, in the same method that the game uses for actor vision. You should pass two references, or two positions and heights.

Only certain object types count as blocking for the purposes of the test: Statics, activators, containers, doors, and lights with non-zero weight.

The collision root node is used for testing, if present in the model.

local hasLineOfSight = tes3.testLineOfSight({ reference1 = ..., reference2 = ..., position1 = ..., height1 = ..., position2 = ..., height2 = ... })

Parameters:

  • params (table)
    • reference1 (tes3reference): Optional. Position of the starting point of the LoS check. For actors, this point is set to position of this reference's head. For other objects the starting point is at the top of its bounding box.
    • reference2 (tes3reference): Optional. Position of the ending point of the LoS check. For actors, this point is set to position of this reference's head. For other objects the ending point is at the top of its bounding box.
    • position1 (tes3vector3, number[]): Optional. Position of the starting point of the LoS check. Modified by height1.
    • height1 (number): Default: 0. Moves the starting point upwards (+Z direction) by this amount. Normally used to simulate head height from a position that is on the ground.
    • position2 (tes3vector3, number[]): Optional. Position of the ending point of the LoS check. Modified by height2.
    • height2 (number): Default: 0. Moves the starting point upwards (+Z direction) by this amount. Normally used to simulate head height from a position that is on the ground.

Returns:

  • hasLineOfSight (boolean)

tes3.togglePOV⚓︎

Forces a toggle of the player's POV the next simulation frame, and returns if the player was previously in 3rd person. Multiple calls in the same frame will not stack.

local was3rdPerson = tes3.togglePOV()

Returns:

  • was3rdPerson (boolean)

tes3.transferInventory⚓︎

Moves all the items in one reference's inventory to another. Both to and from objects will be cloned. The function will update the GUI for the to and from references. This function preserves the tes3itemData of the transferred items and handles leveled lists. The function can do either partial or complete transfer. Limiting transfer by capacity only works for containers, other actors can get over-encumbered after this operation.

local transferred = tes3.transferInventory({ from = ..., to = ..., filter = ..., playSound = ..., limitCapacity = ..., completeTransfer = ..., reevaluateEquipment = ..., equipProjectiles = ..., checkCrime = ... })

Parameters:

  • params (table)
    • from (tes3reference, tes3mobileActor, string): Who to take items from.
    • to (tes3reference, tes3mobileActor, string): Who to give items to.
    • filter (fun(item: tes3item, itemData: tes3itemData): boolean): Optional. You can pass a filter function to only transfer certain type of items. The filter function is called for each item in the from's inventory. Note that not all the items may have itemData.
    • playSound (boolean): Default: true. If false, the up/down sound won't be played.
    • limitCapacity (boolean): Default: true. If false, items can be placed into containers that shouldn't normally be allowed. This includes organic containers and containers that are full. If this argument is set to true the whole from's inventory might not fit into the destination inventory. In that case, partial transfer is made.
    • completeTransfer (boolean): Default: false. Use this to disable partial transfers. If limitCapacity is set to true, passing completeTransfer = true will only transfer the items from one inventory to the other if and only if all the items can fit inside the destination inventory. This argument only works if limitCapacity is true.
    • reevaluateEquipment (boolean): Default: true. If true, and the if in the transferred items are armor, clothing, or weapon items, the actors will reevaluate their equipment choices to see if the new items are worth equipping. This does not affect the player.
    • equipProjectiles (boolean): Default: true. If true, and the to reference has the same projectile already equipped, the stacks will be merged.
    • checkCrime (boolean): Default: false. If true, and the to reference is the player, the function will check if the player has access to the from reference's inventory. If not, appropriate crime reactions will be triggered.

Returns:

  • transferred (boolean): Returns true if at least one item was transferred. If both limitCapacity and completeTransfer were passed as true the function returns true if the whole inventory was successfully transferred.
Example: Transfering target's weapons to the player's inventory
-- Pressing i key while looking at a container, NPC or creature
-- will transfer the target's weapons to the player.

---@param e keyDownEventData
local function onKeyDown(e)
    local target = tes3.getPlayerTarget()
    if not target then
        tes3.messageBox("No target!")
        return
    end

    tes3.transferInventory({
        from = target,
        to = tes3.player,
        ---@param item tes3item
        ---@param itemData tes3itemData?
        ---@return boolean
        filter = function(item, itemData)
            -- You can use the itemData to filter more specifically
            if item.objectType == tes3.objectType.weapon then
                return true
            end
            return false
        end,
        limitCapacity = false,
    })
end
event.register(tes3.event.keyDown, onKeyDown, { filter = tes3.scanCode.i })

tes3.transferItem⚓︎

Moves one or more items from one reference to another. Returns the actual amount of items successfully transferred. If transfering more than one item, the items without itemData will be transferred first. Both the from and to references will be cloned if needed.

local transferredCount = tes3.transferItem({ from = ..., to = ..., item = ..., itemData = ..., count = ..., playSound = ..., limitCapacity = ..., reevaluateEquipment = ..., equipProjectiles = ..., updateGUI = ... })

Parameters:

  • params (table)
    • from (tes3reference, tes3mobileActor, string): Who to take items from.
    • to (tes3reference, tes3mobileActor, string): Who to give items to.
    • item (tes3item, string): The item to transfer.
    • itemData (tes3itemData): Optional. The specific item data to transfer if, for example, you want to transfer a specific player item. If itemData argument is provided, only one item will be transferred.
    • count (number): Default: 1. The maximum number of items to transfer.
    • playSound (boolean): Default: true. If false, the up/down sound for the item won't be played.
    • limitCapacity (boolean): Default: true. If false, items can be placed into containers that shouldn't normally be allowed. This includes organic containers, and containers that are full.
    • reevaluateEquipment (boolean): Default: true. If true, and the item transferred is armor, clothing, or a weapon, the actors will reevaluate their equipment choices to see if the new item is worth equipping. This does not affect the player.
    • equipProjectiles (boolean): Default: true. If true, and the to reference has the same projectile already equipped, the stacks will be merged. This will only work if the GUI is updated.
    • updateGUI (boolean): Default: true. If false, the function won't manually resync the player's GUI state. This can result in some optimizations, though tes3ui.forcePlayerInventoryUpdate or tes3.updateInventoryGUI and tes3.updateMagicGUI must manually be called after all inventory updates are finished.

Returns:

  • transferredCount (number)

tes3.triggerCrime⚓︎

Emulates the player committing a crime. Returns true if the crime was witnessed by an actor.

local result = tes3.triggerCrime({ type = ..., victim = ..., value = ..., forceDetection = ... })

Parameters:

  • params (table)
    • type (tes3.crimeType): Default: tes3.crimeType.theft. The type of crime to be committed. Maps to values in the tes3.crimeType table.
    • victim (tes3mobileNPC, tes3actor, tes3faction): Default: tes3.mobilePlayer. The victim of the crime. This can be an individual actor or a entire faction. Has no effect on crimes with a type of tes3.crimeType.trespass or tes3.crimeType.werewolf.
    • value (number): Default: 0. Only valid if type is tes3.crimeType.theft. The value of the stolen objects. There in no need to multiply the value by fCrimeStealing GMST - the engine will handle that.
    • forceDetection (boolean): Default: false. If true, bypasses regular detection logic and forces all nearby actors to detect the crime.

Returns:

  • result (boolean)

tes3.undoTransform⚓︎

Changes a reference back from werewolf form to human. This function works only on a reference infected with Lycanthropy, be it the player or any other reference. Returns true if successful.

local success = tes3.undoTransform({ reference = ... })

Parameters:

  • params (table)
    • reference (tes3reference): A reference to change back to human.

Returns:

  • success (boolean)

tes3.unhammerKey⚓︎

Stops simulating hammering a keyboard key.

tes3.unhammerKey(keyCode)

Parameters:


tes3.unlock⚓︎

Unlocks an object. Returns true if the object can be and wasn't already unlocked.

local unlocked = tes3.unlock({ reference = ... })

Parameters:

Returns:

  • unlocked (boolean)

tes3.updateInventoryGUI⚓︎

Forces the GUI to update inventory-relevant elements for a given reference. This can be used after many calls to inventory-manipulating functions while passing updateGUI as false to resync inventory tiles, container weights, and companion data.

tes3.updateInventoryGUI({ reference = ... })

Parameters:


tes3.updateJournal⚓︎

Updates the journal index in a way similar to the mwscript function Journal.

local wasUpdated = tes3.updateJournal({ id = ..., index = ..., speaker = ..., showMessage = ... })

Parameters:

  • params (table)
    • id (tes3dialogue, string)
    • index (integer)
    • speaker (tes3mobileActor, tes3reference, string): Default: tes3.mobilePlayer.
    • showMessage (boolean): Default: true. If set, a message may be shown to the player.

Returns:

  • wasUpdated (boolean)

tes3.updateMagicGUI⚓︎

Forces the GUI to update magic-relevant elements for a given reference. This can be used after many calls to magic- or magic item-manipulating functions while passing updateGUI as false to resync inventory tiles, container weights, and companion data.

tes3.updateMagicGUI({ reference = ..., updateSpells = ..., updateEnchantments = ... })

Parameters:

  • params (table)
    • reference (tes3reference, tes3mobileActor, string): The reference to update GUI elements for.
    • updateSpells (boolean): Default: true. Determines if the spell and power lists are refreshed.
    • updateEnchantments (boolean): Default: true. Determines if the enchanted items list is refreshed.

tes3.wakeUp⚓︎

This function wakes player up and returns true if successful.

Note this function returns false if WorldController or MobilePlayer aren't initialized, and if the player is not sleeping or waiting

local wokeUp = tes3.wakeUp()

Returns:

  • wokeUp (boolean)