lua中函数为什么有时候可以省略”()”?
20150825
首先,看两个问题背景:
1. 简单的print函数
print "hello" ---> print hello,通常写法是print(“hello”)
print 42 ---> not work,正确写法是print(42)
2. 一个自定义函数,注意黑体字部分;
Set = {};
function Set.new (t)
local set = {};
setmetatable(set, Set.mt);
for i, _v in ipairs(t) do
set[_v] = true;
end
return set;
end
function Set.union (a, b)
<strong>local res = Set.new{};</strong>
for k in pairs(a) do res[k] = true end
for k in pairs(b) do res[k] = true end
return res;
end
一般来讲,对于local res = Set.new{};,一般写法是local res = Set.new();
这里,是由于lua函数在两种情况下,可以省略’()’:函数中参数是一个单独的字符串或者表。因此,myfunc{a = 1, b = 2},是可以正常运行。所以,有时看到一个函数省略了’()’,就应该反应,传递的参数是单个字符串或者单个表。
在lua中,这些美妙语法特性(syntacic sugar),根本原因是由于lua本身是一个数据描述语言。
延伸阅读:http://www.luafaq.org/ 中 1.16问题。