Names of keys in tables
Defining a keyed table or "dictionary" is quite straightforward in lua and not really diffferent from other programming languages. It is for instance done like this:
functions = {}
functions["j"] = printLower
functions["J"]
= printUpper
functions["C-j"] = printControl
* printUpper, -Lower and -Control are names of functions
The same result can be achieved with this syntax.
functions = {
j = printLower,
J = printUpper,
C-j = printControl
}
This alternative can come in quite handy when a table is part of a larger table/object structure, like this one.
menu = {
state = nil,
display = {
keys = {"M"},
functions = {
M = displayMenu
}
},
choice = {
keys = {"j", "J", "C-j"},
functions = {
j = printLower,
J = printUpper,
C-j = printControl
}
}
}
Still there is a problem with this perticular example and it wil produce a syntax error. The reason is in the third key/value pair:
- C-j = printControl
where the "-" character is not interpreted as part of the key value but as a minus sign. All key values that are not syntactic valid Lua identifiers will result in this same problem.
But we can't be daunted by such a small problem and will simply put the offending key value in qoutes right? Wrong! A syntax like this:
functions = {
"j" = printLower,
"J" = printUpper,
"C-j" = printControl
}
unfortunately is not allowed in lua and will yield an error. So in situations with problematic key values you will have to revert to a syntax like in the first example. That cóuld however get you into trouble with the way lua resolves field and/or function adresses; see also Function names in table fields.
I ran into problems with this phenomenon when I wanted to change the menu script in such a way that it would also correctly process [Control]+[Key] combinations. But the Celestia designers decided to specify [Control] combinations as a "C-x" string where the x represents the character pressed. A very unfortunate choice; the underscore character "_" would have been a better choice, since it is a valid part of a lua identifier.