YellowButShort
YellowButShort

Reputation: 13

Getting "table index is nil" with string index

So I'm currently working on creating blocks of codes which can be called simultaneously by a name id. I've decided to do that with a main table, which contains table with id and with functions. To do that, I wrote 3 functions

function hook.add(name, hookname, func)
    hooks[hookname[name]] = func
end
function hook.create(name)
    hooks[name] = {}
end
function hook.run(name)
    for _, func in pairs(hooks[name]) do
        func()
    end
end


hook.create("MainHook")
    local function func()
        print("working")
    end
    hook.add("todo", "MainHook", func)

However it doesnt work and crashes with

bin/hooks.lua:27: table index is nil

Error contains in

hooks[hookname[name]] = func

line but I have no idea why because even if i print hookname and name there is no nil at all.

I would really appreciate if you help me

Upvotes: 0

Views: 2054

Answers (1)

Darius
Darius

Reputation: 1180

Your function hook.create creates empty table for name, so function hook.add should look like this:

function hook.add(name, hookname, func)
    -- create hooks[hookname] table if not exists
    hooks[hookname] = hooks[hookname] or {}
    -- add function to hooks[hookname] table
    hooks[hookname][name] = func
end

Upvotes: 1

Related Questions