4

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 ?

MrAdityaAlok
  • 95
  • 1
  • 6

3 Answers3

5

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

Nifim
  • 4,758
  • 2
  • 12
  • 31
4

Use this syntax:

t = { ['do'] = 'test' }

or t['do'] to get or set a value.

lhf
  • 70,581
  • 9
  • 108
  • 149
2

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

Read the Lua 5.4 Reference Manual and understand that something like t = { a = b} or t.a = b only works if a is a valid Lua identifier.

3.4.9 - Table constructors

The general syntax for constructors is

tableconstructor ::= ‘{’ [fieldlist] ‘}’

fieldlist ::= field {fieldsep field} [fieldsep]

field ::= ‘[’ exp ‘]’ ‘=’ exp | Name ‘=’ exp | exp

fieldsep ::= ‘,’ | ‘;’

A field of the form name = exp is equivalent to ["name"] = exp.

So why does this not work for do?

3.1 - Lexical Conventsions

Names (also called identifiers) in Lua can be any string of Latin letters, Arabic-Indic digits, and underscores, not beginning with a digit and not being a reserved word. Identifiers are used to name variables, table fields, and labels.

The following keywords are reserved and cannot be used as names:

 and       break     do        else      elseif    end
 false     for       function  goto      if        in
 local     nil       not       or        repeat    return

do is not a name so you need to use the syntax field ::= ‘[’ exp ‘]’ ‘=’ exp

which in your example is table.newKey = { ['do'] = 'test' }

Piglet
  • 27,501
  • 3
  • 20
  • 43