开发者

Using table keys with periods in Lua

开发者 https://www.devze.com 2023-03-15 22:29 出处:网络
In Lua, assigning a table with a specified key might go like this: a = { x = 4 } ...or perhaps like... a = { [\'x\'] = 4 }

In Lua, assigning a table with a specified key might go like this:

a = { x = 4 }

...or perhaps like...

a = { ['x'] = 4 }

Easy enough. However, if I introduce periods into the key (as in a domain name) nothing seems to work. All of the following fail:

a = { "a.b.c" = 4 }
a = { a.b.c = 4 }
a = { ['a.b.c'] = 4 }
a = { ["a.b.c"] = 4 }
开发者_如何转开发a = { [a.b.c] = 4 }

All of these return the same error:

$ ./script.lua
/usr/bin/lua: ./script.lua:49: `}' expected near `='

What am I missing here? Several of the examples seem quite straight-forward and should work (while others have apparent problems).


In lua table element may be either a Name or an Expression. Citing language reference, "Names (also called identifiers) in Lua can be any string of letters, digits, and underscores, not beginning with a digit.", and everything else is interpreted as an identifier in this context. Therefore, a.b.c as a table index is treated as expression, which is evaluated to get the actual table index. This would work, but would be useless:

a = { b = { c = 1 } }
x = {}
x['a.b.c'] = 7

print(x['a.b.c'])

Also note, that foo.a.b.c is equal to foo['a']['b']['c'] and not to foo['a.b.c'].


a = { ['a.b.c'] = 4 }
a = { ["a.b.c"] = 4 }

These two are all valid.

a = { [a.b.c] = 4 }

This could be valid, depending on the exact identifiers used. For example

b = { c = { d = "Ohai!" } } }
a = { [b.c.d] = 4 }

would be valid.

If your interpreter is telling you they are not valid, then you've either done something else wrong, or there's a bug in the interpreter. The others however would not be valid.


Is there something else wrong in your script?

$ ./lua
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> a = { ["a.b.c"] = 4 }
> print (a["a.b.c"])
4
> print (a.a)
nil
0

精彩评论

暂无评论...
验证码 换一张
取 消