MrAdityaAlok
MrAdityaAlok

Reputation: 97

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 ?

Upvotes: 4

Views: 1839

Answers (3)

Piglet
Piglet

Reputation: 28994

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' }

Upvotes: 2

Nifim
Nifim

Reputation: 5021

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

Upvotes: 5

lhf
lhf

Reputation: 72422

Use this syntax:

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

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

Upvotes: 4

Related Questions