Lua的怪癖与S:格式()
问题描述:
看起来这句法应该工作,但不会:Lua的怪癖与S:格式()
> print "%i":format(42)
%i
[string "return print "%i":format(42)"]:1: attempt to index a nil value
这也将失败:
> print ("%i":format(42))
[string "print ("%i":format(42))"]:1: ')' expected near ':'
这类作品:
> print (("%i"):format(42))
42
=> [string "return print ("%i"):format(42)"]:1: attempt to index a nil value
有人可以解释发生了什么,告诉我应该怎么做?
(我知道的string.format("%i", 42)
但我尝试在文档中显示该其它语法。)
编辑:进一步测试显示这部分是与repl.it.问题在本地运行解释器不会在最后一个示例中显示任何错误。
答
这与string.format
无关,它是Lua的一般语法功能:在复杂表达式的方法调用中,需要将表达式括在圆括号中。
看到Lua BNFprefixexp:
prefixexp ::= var | functioncall | ‘(’ exp ‘)’
functioncall ::= prefixexp args | prefixexp ‘:’ Name args