0

Anyone tell me why this doesn't work?

GET_TABLE {1=ID}
key = string.format("%q", GET_TABLE[1])
RETURN_TABLE[key] = "ss"
print(RETURN_TABLE[ID])
print(GET_TABLE[1])

First print result: nil. Second print result: ID

I want the first print result to be: ss

GET_TABLE {1=ID}
key = "ID"
RETURN_TABLE[key] = "ss"
print(RETURN_TABLE[ID])
print(GET_TABLE[1])

The above works fine so I assume its due to the string.format not working right?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
  • Why don't you print the result of the string.format so you can see what you are getting, then fix it? – The Archetypal Paul Aug 16 '14 at 10:49
  • 1
    `GET_TABLE {1=ID}` <-- This calls the function `GET_TABLE()` with the given table literal as the only argument. Are you missing an equals sign, or are you really calling a function and then trying to index it? – cdhowie Aug 16 '14 at 11:00
  • By the way, in Lua a table key can be of *any* type except `nil`, so the `format` may not be necessary for what you want to do. – dualed Aug 18 '14 at 08:45

2 Answers2

1

The %q format token returns the input as an escaped and quoted Lua string. This means that given the input ID it will return "ID" (the double quotes being part of the string!) which is a different string. (Or, represented as Lua strings, the input is 'ID' and the return value is '"ID"'.)

You have therefore set the ID key while trying to retrieve the "ID" key (which presumably does not exist).

> x = 'ID'
> =x
ID
> =string.format('%q', x)
"ID"
> =#x
2
> =#string.format('%q', x)
4
cdhowie
  • 158,093
  • 24
  • 286
  • 300
0

Your code does not compile (you need [] around the index), and you should use the raw string of ID, not the "quoted" string:

GET_TABLE = {[1]=ID}
key = string.format("%s", GET_TABLE[1])

Note that I had to initialize ID and RETURN_TABLE objects to the following:

ID = 'ID'
RETURN_TABLE = {}

Stylistic note: you should only use all-caps names for constants, otherwise too many makes code hard to read

Oliver
  • 27,510
  • 9
  • 72
  • 103