Updating/referencing a hierarchial table

Post Reply
duckman
Posts: 3
Joined: Sun Sep 06, 2020 10:47 pm

Updating/referencing a hierarchial table

Post by duckman »

Hello. I'm trying to capture group status, and put the results in a table, where the key is the character name and each character has in turn attribute values (hp, mana, etc).

I wasn't able to get this to work with table.insert, because that requires a numerical index, so I did this:
Code: [show] | [select all] lua

function GroupAdd(name, xhp, xmaxhp)
  if table.contains(grouplist, name) ~= true then
    local temptable = ({[name] = { ["hp"] = xhp, ["maxhp"] = xmaxhp}})
    table.insert(grouplist, temptable)
    return true
  end
end
That gets an entry in there. However I can't figure out how to reference the data in other commands - in particular to update it if the current HP changes, or to get the HP of a character by name.

I think it's just a rookie programming mistake, where I don't know the syntax for referencing the table correctly. Can someone lend a hand, or is there a better way to accomplish this? Thanks!

User avatar
demonnic
Posts: 686
Joined: Sat Dec 05, 2009 3:19 pm

Re: Updating/referencing a hierarchial table

Post by demonnic »

To add an element to a table at a specific key, you just reference the key directly. So...
Code: [show] | [select all] lua
grouplist = grouplist or {}
function GroupAdd(name, hp, maxhp)
  grouplist[name] = {hp = hp, maxhp = maxhp }
end

duckman
Posts: 3
Joined: Sun Sep 06, 2020 10:47 pm

Re: Updating/referencing a hierarchial table

Post by duckman »

Thanks so much, I really appreciate it. I figured the answer was simple. I think I've got it now!

duckman
Posts: 3
Joined: Sun Sep 06, 2020 10:47 pm

Re: Updating/referencing a hierarchial table

Post by duckman »

So, my next challenge is sorting the key/value table based on an arbitrary field. For example lets narrow it down to the character name (as a key) and their current HP, which is what I want to sort by. I've gotten the below simplified example but it doesn't seem to actually sort - I'm sure it's something simple I'm missing?
Code: [show] | [select all] lua
charlist = {["Meatbag"] = 50, ["Tom"] = 90, ["Joe"] = 70}

table.sort(charlist, function(a, b)
  if charlist[a] > charlist[b] then
    return true
  else
    return false
  end
end
)

display(charlist)


After I run the command the output is still the unordered list. What am I doing wrong?

User avatar
demonnic
Posts: 686
Joined: Sat Dec 05, 2009 3:19 pm

Re: Updating/referencing a hierarchial table

Post by demonnic »

table.sort doesn't work with keyed tables, just ones with sequential numerical indices. Lua does not guarantee the order of keyed tables, so there's some extra work required to get that sort of thing working.

If you wanna join us on discord we can maybe help get you setup a little better. There are a few directions you could go but it depends in part on what your end goal is.

Post Reply