-- 第 5 章 函数
-- 一种对语句和表达式进行抽象的主要机制
print(os.date()); -- 打印日期 Sun Apr 20 12:44:46 2014
-- 一看到sun,感慨广州没有晴天
-- 函数没有参数也要括号
-- 特殊情况:只有一个参数的时候, 并且参数一个string/table构造式,可不写括号
print "Hello world"
-- dofile "chapter03.lua"
-- 冒号操作符:为面向对象式的调用而提供的函数调用操作符
t = {};
-- 先意会一下下面的功能吧少年, 这东西是《lua程序设计第二版》第15章的内容
t.a = 1;
function t:f(a)
self.a = self.a + a
end
local temp = t;
temp:f(10);
print(temp.a);
t = nil;
-- 5.1 多重返回值(之前提过)
s, e, o = string.find("hello lua users", "lua");
print(s, e, o); -- 7 9 nil
function foo0 () end
function foo1 () return "a" end
function foo2 () return "a", "b" end
-- 书上的代码
-- x, y = foo2();
-- print(x, y);
-- x = foo2()
-- print(x, y);
-- x, y, z = 10, foo2()
-- print(x, y);
-- print(unpack{1, 2, 3});
-- 5.2 变长参数
function add(...)
local s = 0;
for i,v in ipairs(...) do
s = s + v;
end
return s;
end
print(add({1, 2, 3}));
-- 5.3 具名实参
-- 参数传递具有“位置性”, 有时候通过名称来制定参数也是很有用的
function realName(option)
print(option.a, option.b);
end
realName({a = 1, b = 2}) -- 有时候有用,但是这会增加程序员额外的注意力在参数上面