View Single Post
03-22-24, 10:33 AM   #6
Codger
An Aku'mai Servant
AddOn Author - Click to view addons
Join Date: Mar 2021
Posts: 30
Here is updated code for the Saved Variables example

Thank you Fizzlemizz. Those are both very good points and I appreciate your thoughtful replies.
This code has been modified to use a unique database name and a more generic form of the date function.
I might have overdone the db name a little bit, but it makes a good point.

Here is the saved variables toc file:
Lua Code:
  1. ## Title: MyAddon
  2. ## Interface: 100206
  3. ## Version: 1.0
  4. ## Author:
  5. ## Notes: A simple WoW addon using a database
  6. ## SavedVariablesPerCharacter: MyAddonDBExampleMarch2024 --must be unique
  7. MyAddon.lua

Here is the saved variables lua file:
Lua Code:
  1. -- Create a saved variable to store last time
  2. local lastLogoffTime = nil
  3.  
  4. -- Create a new frame
  5. local frame = CreateFrame("Frame")
  6.  
  7. -- Load last logoff time from saved variable
  8. local function LoadLastLogoffTime()
  9.     if MyAddonDBExampleMarch2024 then
  10.         lastLogoffTime = MyAddonDBExampleMarch2024.lastLogoffTime
  11.         print("Last logoff time loaded:", lastLogoffTime)
  12.     else
  13.         print("Trying to load logoff time but MyAddonDBExampleMarch2024 is nil.")
  14.     end
  15. end
  16.  
  17. -- Save last time to saved variable
  18. local function SaveLastLogoffTime()
  19.     if not MyAddonDBExampleMarch2024 then
  20.         print("Trying to save logoff time but MyAddonDBExampleMarch2024 is nil")
  21.     else
  22.         MyAddonDBExampleMarch2024.lastLogoffTime = date()
  23.     end
  24. end
  25.  
  26. -- Hook the Logout event to update last logoff time
  27. frame:RegisterEvent("PLAYER_LOGIN")
  28. frame:RegisterEvent("PLAYER_LOGOUT")
  29. frame:SetScript("OnEvent", function(self, event)
  30.     if event == "PLAYER_LOGIN" then
  31.         if not MyAddonDBExampleMarch2024 then
  32.             MyAddonDBExampleMarch2024 = {}
  33.             print ("MyAddonDBExampleMarch2024 was nil")
  34.         end
  35.         LoadLastLogoffTime()
  36.     elseif event == "PLAYER_LOGOUT" then
  37.         SaveLastLogoffTime()
  38.     end
  39. end)
  40.  
  41. -- Slash command handler function
  42. local function SlashCommandHandler(msg)
  43.     LoadLastLogoffTime()
  44. end
  45.  
  46. -- Register slash command
  47. SLASH_MYADDON1 = "/myaddon"
  48. SlashCmdList["MYADDON"] = SlashCommandHandler

One more question, if I had an extremely unique database name that was 50 or 60 characters long, how could I set up an alias?
Something like a local variable defined at the top and set in event PLAYER_LOGIN?
  Reply With Quote