Search code examples
luakey-valuelua-tableself-reference

Accessing the key in the value (right side) of a table key affectation in Lua


The goal is to match a key of a table with a value depending of the key.

example = { ["dummy"] = this .. " example" }
print example.dummy -- print "dummy example"

Where this is the keyword to refer to the key. Is there any way to do that in Lua?


Solution

  • There is no way to do this directly.

    You could do some preprocessing:

    example = { ["dummy"] = "{THIS} example" }
    for k,v in pairs(example) do
        example[k]=v:gsub("{THIS}",k)
    end
    print(example.dummy)