1

I have a main loop in my lua script, and i am including 2 objects like this:

local Menu = require("menu")
local InputHandler = require("inputhandler")

Here are the scripts for each object:

menu.lua

Menu = {
  Active = false,
  Initialise = function(self)
  end,
  ToggleMenu = function(self)
    self.Active = not self.Active
    print(self.Active)
  end
}
return Menu

and inputhandler.lua

InputHandler = {
  KeyBinds = {
    q = { scancode = 16, bind = "q", action = "Menu:ToggleMenu" }
  },
  RunKeyAction = function (self, key)
    for k, v in pairs(self.KeyBinds) do
      if (v.bind == key) then
        _G[v.action]()
      end
    end
  end
}
return InputHandler

Basically I am trying to map keyboard keys to various functions within my script, so when someone presses "Q", it will run the method associated with that key.

So if I do something like this:

InputHandler:RunKeyAction("q")

It will run this method:

Menu:ToggleMenu()

When I run this script as it is now, I get this error:

lua: ./classes//inputhandler.lua:8: attempt to call field '?' (a nil value)
stack traceback:
    ./classes//inputhandler.lua:8: in function 'RunKeyAction'
    [string "<eval>"]:20: in main chunk

Can anyone please tell me that correct way of doing this?

Thank you for reading

1 Answer 1

2

Use

q = { scancode = 16, bind = "q", action = Menu.ToggleMenu }

and

v:action()
Sign up to request clarification or add additional context in comments.

2 Comments

hello lhf, thanks a lot for your reply, i get this error when i try it that way: inputhandler.lua:4: attempt to index global 'Menu' (a nil value)
@Aaranihlus but you need to remember that state Active written in table q.Active instead Menu.Active ;-)

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.