Question

I have a table such as the following:

mafiadb:{"Etzli":{"alive":50,"mafia":60,"vigilante":3,"doctor":4,"citizen":78,"police":40},"Charneus":{"alive":29,"mafia":42,"vigilante":6,"doctor":14,"citizen":53,"police":33}}

There are more nested tables, but I'm just trying to keep it simple for now.

I run the following code to extract certain values (I'm making an ordered list based on those values):

sortmaf={}
for k,v in pairs(mafiadb) do
sortmaf[k]=v["mafia"]
end

That's one of the codes I run. The problem I'm running into is that it doesn't appear you can do arithmetic in a table loop. I tried:

sortpct={}
for k,v in pairs(mafiadb) do
sortpct[k]=(v["alive"]*100)/(v["mafia"]+v["vigilante"]+v["doctor"]+v["citizen"]+v["police"])
end

It returns that I'm attempting to do arithmetic on field "alive." What am I missing here? As usual, I appreciate any consideration in answering this question!

Editing: Instead of commenting on the comment, I'm going to add additional information here.

The mafiadb database I've posted IS the real database. It's just stripped down to two players instead of the current 150+ players I have listed in it. It's simply structured as such:

mafiadb = {
            Playername = {
                           alive = 0
                           mafia = 0
                           vigilante = 0
                           doctor = 0
                           police = 0
                           citizen = 0
                          }
           }

Add a few hundred more playernames, and there you have it.

As for the error message, the exact message is:

attempt to perform arithmetic on field 'alive' (nil value)

So... I'm not sure what the problem is. In my first code, the one with sortmaf, it works perfectly, but suddenly, it can't find v["alive"] as a value when I'm trying to do arithmetic? If I just put v["alive"] by itself, it's suddenly found and isn't nil any longer. I hope this clarifies a bit more.

Was it helpful?

Solution

This looks like a simple typo to me.

Some of your 150 characters is not well written - probably they don't have an "alive" property, or it's written incorrectly, or it's not a number. Try this:

for k,v in pairs(mafiadb) do
  if type(v.alive) ~= 'number' then
    print(k, "doesn't have a correct alive property")
  end
end

This should print the names of the "bad" characters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top