Skip to content

Community Lua Functions

King Pendragon edited this page Jul 20, 2024 · 43 revisions

Hey! If you're reading this you're probably looking for a place that a lot of commonly used functions that we all steal borrow of each other. (All in good fun). Note you don't HAVE to use these, and if you have some way to improve them, please feel free to add to it!

Functions

MoveTo

This function makes the player fly or walk to a specified location, ensuring the navmesh is ready before proceeding. takes an X, Y, Z, Stop Distance, and Boolean (True/False)

-- needs vnavmesh
  function MoveTo(valuex, valuey, valuez, stopdistance, FlyOrWalk)
      function MeshCheck()
          function Truncate1Dp(num)
              return truncate and ("%.1f"):format(num) or num
          end
          local was_ready = NavIsReady()
          if not NavIsReady() then
              while not NavIsReady() do
                  LogInfo("[Debug]Building navmesh, currently at " .. Truncate1Dp(NavBuildProgress() * 100) .. "%")
                  yield("/wait 1")
                  local was_ready = NavIsReady()
                  if was_ready then
                      LogInfo("[Debug]Navmesh ready!")
                  end
              end
          else
              LogInfo("[Debug]Navmesh ready!")
          end
      end
      MeshCheck()
      if FlyOrWalk then
          while GetCharacterCondition(4, false) do
              yield("/wait 0.1")
              if GetCharacterCondition(27) then
                  yield("/wait 2")
              else
                  yield('/gaction "mount roulette"')
              end
          end
          if HasFlightUnlocked(GetZoneID()) then
              PathfindAndMoveTo(valuex, valuey, valuez, true) -- flying
          else
              LogInfo("[MoveTo] Can't fly trying to walk.")
              PathfindAndMoveTo(valuex, valuey, valuez, false) -- walking
          end
      else
          PathfindAndMoveTo(valuex, valuey, valuez, false) -- walking
      end
      while ((PathIsRunning() or PathfindInProgress()) and GetDistanceToPoint(valuex, valuey, valuez) > stopdistance) do
          yield("/wait 0.3")
      end
      PathStop()
      LogInfo("[MoveTo] Completed")
  end

Example usage:

MoveTo(-242.07663, -43.815063, 665.1687, 1, true) --Flies to Coordinates
MoveTo(-162.892, 0.922, -30.488, 3, false) --Walks to coordinates
setSNDProperty

Use these Functions to Set or Unset SND Properties.

--[[
All the settings you can edit with SetSNDProperty()

CraftLoopFromRecipeNote -- bool
CraftLoopMaxWait -- int
CraftLoopEcho -- bool
MaxTimeoutRetries -- int
NoisyErrors -- bool
BeepFrequency -- int
BeepDuration -- int
BeepCount -- int
UseSNDTargeting -- bool
UseItemStructsVersion -- bool
StopMacroIfActionTimeout -- bool
StopMacroIfItemNotFound -- bool
StopMacroIfCantUseItem -- bool
StopMacroIfTargetNotFound -- bool
StopMacroIfAddonNotFound -- bool
StopMacroIfAddonNotVisible -- bool

--]]

-- Function to set or unset the property
function setSNDProperty(propertyName, value)
  local currentValue = GetSNDProperty(propertyName)
  if currentValue ~= value then
      SetSNDProperty(propertyName, tostring(value))
      LogInfo("[SetSNDProperty] " .. propertyName .. " set to " .. tostring(value))
  end
end

Example usage:

setSNDProperty("UseItemStructsVersion", true)
setSNDProperty("UseSNDTargeting", true)
setSNDProperty("StopMacroIfTargetNotFound", false)
setSNDProperty("StopMacroIfCantUseItem", false)
setSNDProperty("StopMacroIfItemNotFound", false)
setSNDProperty("StopMacroIfAddonNotFound", false)
PlayerTest

Waits Until Player is Ready.

  -- This function will wait until player is ready can be used in map changes, menu exit waits ex.
  function PlayerTest()
      repeat
          yield("/wait 0.5")
      until IsPlayerAvailable()
  end

Example usage:

PlayerTest()
EatFood

Eats Food if you don't have any.

function EatFood(FoodKind, StopIfNoFood)
  -- Check if the food effect is not active and if using food is enabled
  if not HasStatusId(48) and UseFood then
      while not HasStatusId(48) and UseFood do
          yield("/item " .. FoodKind)
          yield("/wait 2")
          
          -- Check if there was an error indicating no food remaining
          if GetNodeText("_TextError", 1) == "You do not have that item." and IsAddonVisible("_TextError") then
              UseFood = false
              LogInfo("[FoodCheck] No food remaining, setting UseFood to false")
              
              -- Stop the script if the flag is set
              if StopIfNoFood then
                  LogInfo("[FoodCheck] StopIfNoFood is true, stopping the script")
                  yield("/snd stop")
              end
              
              break
          end
      end
      LogInfo("[FoodCheck] Completed")
  else
      LogInfo("[FoodCheck] Already has food status or UseFood is false")
  end
end

Example usage:

EatFood("Vegetable Soup <HQ>", false) --make sure to have the name of the food IN the "" and <HQ> for HQ food,  if set to True will stop script when food runs out.
RandomSpot

Returns a Random X Y Z coordinate from a Variable List. Variable Lists should include 4 pieces of information in them. X value, Y value, Z value, Spot value. The Spot value allows you to use the same List Variable for multiple slots. Included in the code below are three coordinates sets for 3 different spots. When Calling the Function it looks for the value for the spot to pick from.

FishingSpot =
{
{520.7,193.7,-518.1,0}, -- First spot
{521.4,193.3,-522.2,0},
{526.3,192.6,-527.2,0},

{544.6,192.4,-507.8, 1}, -- Second spot
{536.9,192.2,-503.2, 1},
{570.3,189.4,-502.7, 1},

{422.9,-191.2,-300.2, 500} --bailout
}

function RandomSpot(Value)
  local availableSpots = {} -- Table to store available spot indices

  for i, spot in ipairs(FishingSpot) do
      if spot[4] == Value then
          table.insert(availableSpots, i)
      end
  end
  if #availableSpots > 0 then
      local randomIndex = math.random(1, #availableSpots)
      local spotIndex = availableSpots[randomIndex]

      local spot = FishingSpot[spotIndex]
      local x, y, z = spot[1], spot[2], spot[3]
      return x, y, z

  else
      LogInfo("[Debug]No available spots")
      return nil, nil, nil
  end
end

Example usage:

X, Y, Z = RandomSpot(1) -- Calls a random X, Y, Z Value from the coordinates in the above code from the (2nd spots which is marked with a 1)
NpcRepair

Selects the Named NPC to repair.

function NpcRepair(Name)
    while true do
        if not NeedsRepair(RepairAmount) then
            break
        elseif GetTargetName() ~= Name then
            yield("/target " .. Name)
            yield("/wait 0.1")
        elseif IsAddonVisible("SelectIconString") then
            yield("/callback SelectIconString true 1")
        elseif IsAddonVisible("SelectYesno") then
            yield("/callback SelectYesno true 0")
            yield("/wait 0.1")
        elseif IsAddonVisible("Repair") then
            yield("/callback Repair true 0")
        else
            yield("/interact")
        end
        yield("/wait 0.3")
    end
    while IsAddonVisible("Repair") do
        yield("/callback Repair true -1")
        yield("/wait 0.1")
    end
    LogInfo("[RepairNpc]Got Repaired by " .. Name .. " .")
end

Example usage:

NpcRepair("Mender")
SelfRepair

Self repairs gear.

function SelfRepair(RepairAmount, StopIfNoDarkMatter)
  if NeedsRepair(RepairAmount)then
      while not IsAddonVisible("Repair") do
          yield("/generalaction repair")
          yield("/wait 0.5")
      end
      yield("/callback Repair true 0")
      yield("/wait 0.1")
      if GetNodeText("_TextError", 1) == "You do not have the dark matter required to repair that item." and
          IsAddonVisible("_TextError") then
                      LogInfo("[Repair] Set to False not enough dark matter")
          if StopIfNoDarkMatter then
              yield("/snd stop")
          end
      end
      if IsAddonVisible("SelectYesno") then
          yield("/callback SelectYesno true 0")
      end
      while GetCharacterCondition(39) do
          yield("/wait 1")
      end
      yield("/wait 1")
      if IsAddonVisible("Repair") then
          yield("/callback Repair true -1")
      end
  end
  LogInfo("[Repair] Completed")
  
end

Example usage:

SelfRepair(50, false) --does a Self Repair when gear score is below 50 but does not stop the script if you have no dark matter. (set to true to stop script if you have no dark matter.)
TeleportTo

Checks if you are all ready in the area before teleporting to location. Requires the Teleporter Plugin.

function TeleportTo(town, targetZoneID)
  local currentZone = GetZoneID()
  
  if currentZone ~= targetZoneID then
      -- Teleport to the specified location
      local teleportCommand = "/tp " .. town
      yield(teleportCommand)
      yield("/wait 10")  -- Wait for the teleport to complete
      
      -- Check if the teleport was successful
      currentZone = GetZoneID()
      if currentZone == targetZoneID then
          yield("/echo Teleport successful. Now at Zone ID " .. targetZoneID .. ".")
      else
          yield("/echo Teleport failed. Still at Zone ID " .. currentZone .. ".")
      end
  end
end

Example usage:

TeleportTo("Solution Nine", 1186)
MateriaExtract

Extracts Materia from current Gear at 100% soulbond.

function MateriaExtract()
  if CanExtractMateria(100) then
      yield("/generalaction \"Materia Extraction\"")
      yield("/waitaddon Materialize")

      while CanExtractMateria(100) == true do
          yield("/callback Materialize true 2 0")
          yield("/wait 0.5")
if IsAddonVisible("MaterializeDialog") then
yield("/callback MaterializeDialog true 0")
end
          while GetCharacterCondition(39) do
              yield("/wait 3")
          end
          yield("/wait 2")
      end

      yield("/wait 1")
      yield("/callback Materialize true -1")
  end
end

Example usage

MateriaExtract()

Useful Code

Get Target name

Gets Target's name and returns it to chat.

yield("Target Name: "..tostring(GetTargetName()))
Current Zone ID

Gets the Current Zone ID and returns it to chat.

yield("InZone: " .. tostring(GetZoneID()))
Target Position

Gets the Current Targets X Y Z and returns it to chat.

yield("/e ------------------------------------------------------")
x = ("%.1f"):format(GetTargetRawXPos())
y = ("%.1f"):format(GetTargetRawYPos())
z = ("%.1f"):format(GetTargetRawZPos())
yield("/e Target Position: {"..x..","..y..","..z.."}")
yield("/e ------------------------------------------------------")
Players Position

Gets the Players X Y Z and returns it to chat.

yield("/e ------------------------------------------------------")
x = ("%.1f"):format(GetPlayerRawXPos())
y = ("%.1f"):format(GetPlayerRawYPos())
z = ("%.1f"):format(GetPlayerRawZPos())
yield("/e Current Position: {"..x..","..y..","..z.."}")
yield("/e ------------------------------------------------------")