Following Chris's example (http://www.shatters.net/forum/viewtopic.php?f=9&t=9813&start=0&st=0&sk=t&sd=a&hilit=key+handler), let's say you have a collection of key assignments contained in a table called "keyhandlers":
Code: Select all
keyhandlers =
{
G = fast_goto,
["1"] = toggle_ecliptic_grid,
etc,
etc
}
and a function that handles the key input:
Code: Select all
function handlekey(k)
handler = keyhandlers[k.char]
if (handler ~= nil) then
handler()
return true
else
return false
end
end
and a command that ties the "key" event to the "handlekey" function:
Code: Select all
celestia:registereventhandler("key", handlekey)
Now if you've already run this script (in start.celx, say), is there a way to add another key assignment to the table, or add another table to the function, by running another script?
Adding another key assignment is pretty simple - just run a script with this command:
Code: Select all
rawset(keyhandlers, "A", toggle_plates)
(Of course, if "A" was assigned to a different function originally, this command will reassign it.)
You can also have the script look for the existence of the "keyhandlers" table, and if it doesn't find it, create it:
Code: Select all
if (keyhandlers == nil) then
keyhandlers = { ["A"] = toggle_plates }
celestia:registereventhandler("key", handlekey)
else
rawset(keyhandlers, "A", toggle_plates)
end
But to make it work, you will have to add the "handlekey" function to the script as well:
Code: Select all
function handlekey(k)
handler = keyhandlers[k.char]
if (handler ~= nil) then
handler()
return true
else
return false
end
end
This will overwrite any previous declaration of "handlekey", which won't be a problem if it's identical.
Now let's say your script creates a new table called "keyhandlers2". Can you include this table in the "handlekey" function along with the original key handling table?
Use this variation of the key handling function:
Code: Select all
function handlekey(k)
handler = keyhandlers[k.char]
handler2 = keyhandlers2[k.char]
if (handler ~= nil) then
handler()
return true
elseif (handler2 ~= nil) then
handler2()
return true
else
return false
end
end
When you run your script, the old function "handlekey" will be overwritten with this version, but the original "keyhandlers" table will still work.