0

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

1
  • 1
    You seems to be doing something odd. hookname[name] means your are trying to index the string "MainHook" with the string "todo" which will return a nil if not an out right error for attempting to index a string like that. Can't be sure what you intended to do, perhaps concat the to strings? hookname .. name? Commented May 1, 2020 at 22:15

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.