提交 a66e92f0 编写于 作者: 独孤过's avatar 独孤过

语言特性

上级 6bf443e4
# 语言特性
# 数据结构
# 算法
# 设计模式
# 工具库
## 简介
存放lua之行的精选代码,代码按照语言特性、数据结构、算法、设计模式、工具类库分类。
## 语言特性
泛型for迭代器
尾调函数
## 数据结构
## 算法
## 设计模式
## 工具库
## 其他
作者:许聪
CSDN:https://blog.csdn.net/xucongyoushan
gitee:https://gitee.com/solifree
github:https://github.com/xucongandxuchong
--[[
函数的尾调用
函数返回结果是调用单个函数,称之为尾调函数
先从栈空间弹出当前函数,再调用尾调函数,从而降低函数调用过持的栈消耗
--]]
function factorial(n, temp)
temp = temp or 1
if n <= 1 then
return temp
end
return factorial(n - 1, temp * n)
end
print(factorial(5))
local week_day = {
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
}
-- 定义迭代器
local function ipairs(table)
-- 定义迭代函数
local ipairs = function(table, index)
index = index + 1
local value = table[index]
if not value then
index = nil
end
return index, value -- 返回nil,结束泛型for
end
return ipairs, table, 0
end
for k, v in ipairs(week_day) do
print(k .. ": " .. v)
end
-- 定义迭代器
local function pairs(table)
-- 定义迭代函数
local pairs = function(table, key)
key = next(table, key)
return key, table[key]
end
return pairs, table, nil -- 返回迭代函数、遍历集合、初始键
end
for k, v in pairs(week_day) do
print(k .. ": " .. v)
end
-- table.move(src, f, e, t[, dest])
-- 此函数只复制源数组指定范围的元素至目的数组的指定位置,并不会移除源数组指定范围的元素
local src = { 1, 2, 3 }
local dest = {}
_G.table.move(src, 1, #src, 1, dest)
print(next(src))
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册