Reputation: 149
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
Upvotes: 1
Views: 149
Reputation: 72412
Use
q = { scancode = 16, bind = "q", action = Menu.ToggleMenu }
and
v:action()
Upvotes: 2