are you allowed to have a numeric key in a lua table?
dictionary, lua, lua-table
Solution
You need to put the numeric indices in brackets:
dyeColor = {
[0]="black" , black = 0,
[1]="red" , red = 1,
[2]="green" , green = 2,
[3]="brown" , brown = 3,
[4]="blue" , blue = 4,
[5]="purple" , purple = 5,
[6]="cyan" , cyan = 6,
[7]="lightGray" , lightGray = 7,
[8]="gray" , gray = 8,
[9]="pink" , pink = 9,
[10]="lime" , lime =10,
[11]="yellow" , yellow =11,
[12]="lightBlue", lightBlue =12,
[13]="magenta" , magenta =13,
[14]="orange" , orange =14,
[15]="white" , white =15}
You can save yourself some typing with:
dyeColor = {
[0]="black" ,
[1]="red" ,
[2]="green" ,
[3]="brown" ,
[4]="blue" ,
[5]="purple" ,
[6]="cyan" ,
[7]="lightGray" ,
[8]="gray" ,
[9]="pink" ,
[10]="lime" ,
[11]="yellow" ,
[12]="lightBlue",
[13]="magenta" ,
[14]="orange" ,
[15]="white" }
for i = 0, #dyeColor do dyeColor[dyeColor[i]] = i end
Lua permits `Name`s as `fieldspec`s in the form `Name = exp` but not numbers. Numbers must be in brackets. The same is true of field references. You may say
dyeColor.black
but not
dyeColor.0 -- you may say dyeColor[0] of course
Problem
The following example is supposed to make a table, that can convert between a number and a string and back again, but fails to run. Is it because I'm using a numeric key in a dictionary type way? Or is it because lua starts table indices from 1? Is there a better way to accomplish this? ``` dyeColor = { 0="black" , black = 0, 1="red" , red = 1, 2="green" , green = 2, 3="brown" , brown = 3, 4="blue" , blue = 4, 5="purple" , purple = 5, 6="cyan" , cyan = 6, 7="lightGray", lightGray = 7, 8="gray" , gray = 8, 9="pink" , pink = 9, 10="lime" , lime =10, 11="yellow" , yellow =11, 12="lightBlue", lightBlue =12, 13="magenta" , magenta =13, 14="orange" , orange =14, 15="white" , white =15} ``` using this online interpreter (http://repl.it/languages/Lua) it gives the error `[string "stdin"]:2: '}' expected (to close '{' at line 1) near '='attempt to call a nil value`