2
votes

I'm trying to build a script for a MUD I play that will create a table to keep track of average xp for each mob. I'm having trouble with the syntax of checking whether an element in a table exists and if not creating it. I tried something like this but keep getting: attempt to index field '?' (a nil value)

mobz_buried = {
{mob = "troll", quantity = 2}
{mob = "warrior", quantity = 1}
{mob = "wizard", quantity = 1}} -- sample data

number_of_mobz_buried = 4 

xp_from_bury = 2000 -- another script generates these values, these are all just examples

xp_per_corpse = xp_from_bury / number_of_mobz_buried

for _, v in ipairs(mobz_buried) do
    if type(mobz[v].kc) == "variable" then -- kc for 'kill count', number of times killed 
            mobz[v].kc = mobz[v].kc + 1 -- if it exists increment kc
    else
        mobz[v].kc = 1 -- if it doesn't exist create a key value that matches the mobs name and make the kc 1
    end
    if type(mobz[v].xp) == "variable" then -- xp for average experience points
        mobz[v].xp = (((mobz[v].kc - 1) * mobz[v].xp + xp_per_corpse)/mobz[v].kc) -- just my formula to find the average xp over a range of differant buries
    else
            mobz[v].xp = xp_per_corpse -- if it doesn't exist create the table just like before
    end
end

I'm trying to end up with mobz.troll = {kc, xp}, mobz.warrior = {kc, xp}, mobz.wizard = {kc, xp} and the ability to add more key values based off of the names mobz_buried gives me.

1
Provide a simple example of the table mobz_buried and mobz. - Yu Hao
See How to create a Minimal, Complete, and Verifiable example. Your current example isn't complete. - Yu Hao
Your mobz_buried table has a value that doesn't have a corresponding element in mobz so when you try to use mobz[v] and then index into that value there isn't a value and you get this error. See eval.in/private/88f083da483307 - Etan Reisner
Okay, I edited my question so the example and objective should be much more clear now! - Eli Bell
Please post the full stacktrace error and include the surrounding code of the line it refers to. - greatwolf

1 Answers

0
votes

Based on extra info from your comments, it sounds like you didn't construct a table for mobz. Try this:

local mobz = {}
for _, v in ipairs(mobz_buried) do
    mobz[v.mob] = mobz[v.mob] or {}
    mobz[v.mob].kc = (mobz[v.mob].kc or 0) + 1

    -- etc...
end