我是 的初学者Lua,我对().
这里有一些关于 的例子Lua5.3。
a = '%s %s'
a:format("Hello", "World") -- Hello World
'%s %s':format("Hello", "World") -- stdin:1: unexpected symbol near ''%s %s''
('%s %s'):format("Hello", "World") -- Hello World
type(a) == type('%s %s') -- true
getmetatable(a) -- table: 0x1f20bf0
getmetatable('%s %s') -- table: 0x1f20bf0 for any other hard coded strings
Run Code Online (Sandbox Code Playgroud)
题:
()对硬编码字符串做了什么?在函数调用的第一个示例中强制使用括号(或变量)是由于 Lua 语法规则:这只是语言语法的定义方式,不遵循定义的语法会导致语法/解析错误。
Lua 中的函数调用具有以下语法:
Run Code Online (Sandbox Code Playgroud)functioncall ::= prefixexp args在函数调用中,首先计算 prefixexp 和 args。如果 prefixexp 的值具有类型 function,则使用给定的参数调用此函数。否则,将调用 prefixexp "call" 元方法,将 prefixexp 的值作为第一个参数,然后是原始调用参数(参见第 2.8 节)。
表格
Run Code Online (Sandbox Code Playgroud)functioncall ::= prefixexp `:´ Name args..
其中prefixexp定义为:
Run Code Online (Sandbox Code Playgroud)prefixexp ::= var | functioncall | ( exp )
也就是说,prefixexp 不能是String(或任何其他)文字,但可以是变量 ( var);或括号( ( expr ))内的任何表达式;甚至链式函数调用 ( functioncall)..
由于以下产生式,允许String在该args位置使用(或任何其他)文字:
Run Code Online (Sandbox Code Playgroud)args ::= `(´ [explist] `)´ | tableconstructor | String explist ::= {exp `,´} exp
作为示例的补充案例,请注意,args产生式有一个特殊情况,如果采用单个文字,则不需要括号。因此,即使看起来很奇怪,以下内容也是有效的: String
('Hello %s'):format "World!"
Run Code Online (Sandbox Code Playgroud)