Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 223
MrAdityaAlok Avatar asked Nov 16 '25 07:11

MrAdityaAlok


2 Answers

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

like image 66
Nifim Avatar answered Nov 17 '25 21:11

Nifim


Use this syntax:

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

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

like image 22
lhf Avatar answered Nov 17 '25 20:11

lhf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!