Search code examples
lualua-tablearray-key

Lua Changing Table Keys


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?


Solution

  • 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