Caleb Purvis
Caleb Purvis

Reputation: 65

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?

Upvotes: 0

Views: 946

Answers (2)

Oliver
Oliver

Reputation: 29533

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

Upvotes: 0

cdhowie
cdhowie

Reputation: 169038

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

Upvotes: 1

Related Questions