当前位置: 首页 > news >正文

Lua可变参数函数

基础规则

lua传入参数给一个function时采用的是“多余部分被忽略,缺少部分有nil补足”的形式:

function f(a, b)return a or b
endCALL        PARAMETERS
f(3)        a=3, b=nil
f(3, 4)     a=3, b=4
f(3, 4, 5)  a=3, b=4 (5 is discarded)

unpack/pack

table.unpack和table.pack分别是数组的拆装处理,unpack函数输入数组,返回数组的所有元素:

tb = {1,2,3}
a,b,c = table.unpack(tb)
print(a) --1
print(b) --2
print(c) --3

pack函数输入多值,返回由这些值组成的数组:

a = table.pack(1,2,3)
print(a) --table: 000002687821C910
print(a.n) --3

table.pack(...)就是在外面包一层{},即{ ... }.

实际上table.unpack()函数可以通过以下lua代码来实现:

function unpack(tb,i)i = i or 1if tb[i] thenreturn tb[i],unpack(tb,i+1)end
end

为什么提到unpack函数,是后面需要配合另一个机制使用。

...和arg的应用

在函数参数列表中使用三点(...)表示函数有可变的参数,print实际上就是用了这点来无限拼接字符串:

function printMySelf( ... )local strResult = ""for i,v in ipairs(table.pack(...)) dostrResult = strResult..vendprint(strResult)
endprintMySelf(1,"a","b",2) --1ab2

在lua5.1版本之前,可以在函数中使用arg来定位可变参数,在函数内部arg就等于table.pack(...),即如下:

function select(n, ...)return arg[n]
endprint(string.find("hello hello", " hel")) --> 6 9
print(select(1, string.find("hello hello", " hel"))) --> 6
print(select(2, string.find("hello hello", " hel"))) --> 9

但是5.1版本之后这上面的select函数会因为去掉了arg全局关键字而报空:

print(select(1, string.find("hello hello", " hel"))) --> nil
print(select(2, string.find("hello hello", " hel"))) --> nil

所以后续版本需要显式强调arg才行:local arg = { ... }

由此我们可以传入一个table.unpack的数组,然后用...机制操作参数即可:

function printMySelf( ... )local strResult = ""for i,v in ipairs(table.pack(...)) dostrResult = strResult..vendprint(strResult)
endlocal tbNeedPrint = {"hello!","world"}
printMySelf(table.unpack(tbNeedPrint)) --hello!world
http://www.lryc.cn/news/298742.html

相关文章:

  • Nginx实战:3-日志按天分割
  • springmvc中的数据提交方式
  • unity2017 遇到visual studio 2017(社区版) 30日试用期到了
  • Netty应用(六) 之 异步 Channel
  • STM32CubeMx+MATLAB Simulink串口输出实验,UART/USART串口测试实验
  • 【51单片机】串口通信实验(包括波特率如何计算)
  • Kafka零拷贝技术与传统数据复制次数比较
  • npm ERR! network This is a problem related to network connectivity.
  • 【SQL高频基础题】619.只出现一次的最大数字
  • STM32F1 - GPIO外设
  • 新增同步管理、操作日志模块,支持公共链接分享,DataEase开源数据可视化分析平台v2.3.0发布
  • 跟着pink老师前端入门教程-day19
  • ChatGPT学习第一周
  • 爬爬爬——今天是浏览器窗口切换和给所选人打钩(自动化)
  • Netty应用(五) 之 Netty引入 EventLoop
  • 【c++基础】国王的魔镜
  • 配置DNS正反向解析服务!!!!
  • 大模型2024规模化场景涌现,加速云计算走出第二增长曲线
  • Gitlab和Jenkins集成 实现CI (三)
  • 随机过程及应用学习笔记(二)随机过程的基本概念
  • 【机器学习】Kmeans如何选择k值
  • LeetCode 热题 100 | 链表(下)
  • Ubuntu搭建计算集群
  • 数据结构~~树(2024/2/8)
  • 【教学类-48-03】202402011“闰年”(每4年一次 2月有29日)世纪年必须整除400才是闰年)
  • 如何开发一个属于自己的人工智能语言大模型?
  • 【HTTP】localhost和127.0.0.1的区别是什么?
  • Edge浏览器-常用快捷键
  • C++:Vector动态数组的copy深入理解
  • 【PyTorch】PyTorch中张量(Tensor)切片操作