Search code examples
lualua-tableluajit

How do I use lua keyword as a table key?


Problem

When I use do, a lua keyword as a table's key it gives following error

> table.newKey = { do = 'test' }
stdin:1: unexpected symbol near 'do'
>

I need to use do as key. What should I do ?


Solution

  • sometable.somekey is syntactic sugar for sometable['somekey'],

    similarly { somekey = somevalue } is sugar for { ['somekey'] = somevalue }


    Information like this can be found in this very good resource:

    For such needs, there is another, more general, format. In this format, we explicitly write the index to be initialized as an expression, between square brackets:

    opnames = {["+"] = "add", ["-"] = "sub",
               ["*"] = "mul", ["/"] = "div"}
    

    -- Programming in Lua: 3.6 – Table Constructors