2
votes

I was using a function in the world of warcraft lua API to make an addon.

My goal was simply to get a list of all tracked achievements the player currently had. The documentation seemed to suggest it should return a list, yet I am getting a number. My code is as follows:

I tracked 6 achievements, 4 of which were in the zone I was testing in.

Addon = LibStub("AceAddon-3.0"):NewAddon("LocationAchievements", "AceConsole-3.0", "AceEvent-3.0")
function Addon:OnInitialize()
  Addon:Print(ChatFrame1, "Successfully initialized")
end
function Addon:DisplayAchievements()
  Addon:Print(ChatFrame1, UnitName("Player").." has changed to zone "..GetZoneText())
  local achievements = GetTrackedAchievements()
  Addon:Print(ChatFrame1, "Type of achievements variable: "..type(achievements))
  Addon:Print(ChatFrame1, "Number of tracked achievements: "..GetNumTrackedAchievements())
end
Addon:RegisterEvent("ZONE_CHANGED_NEW_AREA", "DisplayAchievements")

When I enter a new area, I receive the following output to my chat box

Crowmonk has changed to zone Shadowmoon Valley

Type of achievement variable: number

Number of tracked achievements: 6

How can this be fixed? What am I doing wrong here?

2

2 Answers

1
votes

found the error:

local achievements = {GetTrackedAchievements()}
1
votes

Lua supports multiple return values. These come as a list, rather than an array or table/object (arrays and tables are actually the same thing in Lua)

If you want a certain index:

value = select( index, GetTrackedAchievements() )

To iterate over these values of unknown length:

for val in pairs( GetTrackedAchievements() ) do
    print(val)
end

pairs/ipairs can be called with lists as well as tables.

They can be fed back to another function as X parameters, in fact, print( GetTrackedAchievements() ) will output all values, or converted to a table by creating a pseudo-literal: { GetTrackedAchievements() } as you already found out, analogous to { 1, 2, 3, ["foo"] = "bar" }

The reverse of that, forming a list out of the values in a table, is unpack:

x,y,z = unpack(tbl)

If the table tbl has more than three values, additional ones are discarded.