lua中函数为什么有时候可以省略”()”?
lua中函数为什么有时候可以省略”()”?
DionysosLai(906391500@qq.com)
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问题。
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: 子进程在复制父进程的信号处理方式
- 下一篇: python读取多行文件的三种方法