ham*_*obi 5 lua coronasdk lua-table
我碰到了像这样的桌子,键周围有方括号。我知道使用lua不需要使用lua ..使用方括号时有什么区别吗?
local commands_json =
{
["request"] = {
["application"] = PW_APPLICATION,
["push_token"] = deviceToken,
["language"] = "en", --OR: system.getPreference( "ui", "language" ),
["hwid"] = system.getInfo("deviceID"),
["timezone"] = -3600, --offset in seconds
["device_type"] = deviceType
}
}
Run Code Online (Sandbox Code Playgroud)
它只是在表中指定键的长形式。您可以在[](除了nil. 和浮点 NaN 之外)之间放置任何值。而没有它们,您只能使用标识符。
例如:
tbl =
{
key name = 5,
}
Run Code Online (Sandbox Code Playgroud)
这是一个编译错误,因为“键名”不是标识符(由于空格)。这有效:
tbl =
{
["key name"] = 5,
}
Run Code Online (Sandbox Code Playgroud)
和这个:
tbl =
{
"key name" = 5,
}
Run Code Online (Sandbox Code Playgroud)
Is also a compile error. If Lua sees a naked value like this, it thinks you're trying to add to the array part of the table. That is, it confuses it with:
tbl =
{
"key name",
}
Run Code Online (Sandbox Code Playgroud)
Which creates a 1-element array, with tbl[1] equal to "key name". By using [], the compiler can easily tell that you meant for something to be a key rather than the value of an array element.
The long form also lets you distinguish between:
local name = "a name";
tbl =
{
["name"] = 5,
[name] = 7,
}
Run Code Online (Sandbox Code Playgroud)
The second part means to evaluate the expression name, the result of which will be the key. So this table has the keys "name" and "a name".