LUA学习笔记(第5-6章)
2016-07-19 17:16
344 查看
x = a or b
如果a为真则x = a
如果a为假则x = b
print(a .. b)
任何非nil类型都会被连接为字符串,输出
多重返回值
local s,e = string.find("Hello World", "Wo")
print(s .. " : " .. e)
自定义函数
unpack函数
print(unpack{20, 50, 10, 40, 30})
它接受一个数组作为参数,并从下标1开始返回数组的所有元素
变长参数
返回所有实参
通常一个函数在遍历其变长参数时只需要使用表达式{ ... }
但是变长参数中含有nil则只能使用函数select了
select("#", ...)返回所有变长参数的总数,包括nil
print(#{1, 2, 3, 4, 5, nil}) -->5
print(select("#", 1,2,3,4,5,nil)) -->6
具名实参
函数调用需要实参表和形参表进行匹配,为了避免匹配出错,而使用具名实参。
例:
深入函数
LUA中函数与所有其他值一样都是匿名的:当讨论一个函数时,实际上是在讨论一个持有某函数的变量。
a = {p = print}
a.p("Hello")
print = os.date()
a.p(print)
一个函数定义实际就是一条语句(赋值语句)
将匿名函数传递给一个变量
foo = function() return "Hello World" end
print(foo())
等价于我们常见的
function foo()
return "Hello World"
end
匿名函数
arr = {
{name = "A", score = 99},
{name = "B", score = 95},
{name = "C", score = 96},
{name = "D", score = 97},
}
table.sort(arr, function (a, b) return (a.name < b.name) end)
for i,v in ipairs(arr) do
print(v.name)
end
如果a为真则x = a
如果a为假则x = b
print(a .. b)
任何非nil类型都会被连接为字符串,输出
多重返回值
local s,e = string.find("Hello World", "Wo")
print(s .. " : " .. e)
自定义函数
function getMax(arr) local maxValue, maxPos maxValue = arr[1] maxPos = 1 for i=1,#arr do if arr[i] > maxValue then maxValue = arr[i] maxPos = i end end return maxPos, maxValue end print(getMax{20, 50, 10, 40, 30})
unpack函数
print(unpack{20, 50, 10, 40, 30})
它接受一个数组作为参数,并从下标1开始返回数组的所有元素
变长参数
function add( ... ) local s = 0 for i,v in ipairs{ ... } do s = s + v end return s end print(add(1, 2, 3, 4))
返回所有实参
function add( ... ) return ... end print(add(1, 2, 3, 4))
通常一个函数在遍历其变长参数时只需要使用表达式{ ... }
但是变长参数中含有nil则只能使用函数select了
select("#", ...)返回所有变长参数的总数,包括nil
print(#{1, 2, 3, 4, 5, nil}) -->5
print(select("#", 1,2,3,4,5,nil)) -->6
具名实参
函数调用需要实参表和形参表进行匹配,为了避免匹配出错,而使用具名实参。
例:
function Window( options ) _Window(options.title, options.x or 0, options.y or 0, options.width, options.height, options.background or "white", options.border ) end w = Window{x = 0, y = 0, width = 300, height = 200, title = "Lua", background = "blue", border = true }
深入函数
LUA中函数与所有其他值一样都是匿名的:当讨论一个函数时,实际上是在讨论一个持有某函数的变量。
a = {p = print}
a.p("Hello")
print = os.date()
a.p(print)
一个函数定义实际就是一条语句(赋值语句)
将匿名函数传递给一个变量
foo = function() return "Hello World" end
print(foo())
等价于我们常见的
function foo()
return "Hello World"
end
匿名函数
arr = {
{name = "A", score = 99},
{name = "B", score = 95},
{name = "C", score = 96},
{name = "D", score = 97},
}
table.sort(arr, function (a, b) return (a.name < b.name) end)
for i,v in ipairs(arr) do
print(v.name)
end
相关文章推荐
- LUA学习笔记(第5-6章)
- 《Lua程序设计》第7章 迭代器与泛型for 学习笔记
- Lua 迭代器与closure
- 传Lua对象到Cpp
- 传Lua对象到Cpp
- 《Lua程序设计》第6章 深入函数 学习笔记
- Lua 正确的尾调用(proper tail call)
- Lua中的closure(闭合函数)
- premake构造工具- 使用premake工具生成工程文件
- Lua中强大的元方法__index详解
- 一个lua 与c交互的小demo
- 如何让EditPlus支持LUA
- 高效调用lua函数
- Lua学习笔记-table转为字符串
- 余额重估(Revaluation Balances)相关设置和操作
- Lua调用C/C++函数
- Lua实现angle角
- Lua5.3——C API函数
- 《Lua程序设计》第5章 函数 学习笔记
- 《Lua程序设计》第4章 语句 学习笔记