Lua可变参数函数

基础规则

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

Lua 复制代码
function f(a, b)
    return a or b
end
  
CALL        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函数输入数组,返回数组的所有元素:

Lua 复制代码
tb = {1,2,3}
a,b,c = table.unpack(tb)
print(a) --1
print(b) --2
print(c) --3

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

Lua 复制代码
a = table.pack(1,2,3)
print(a) --table: 000002687821C910
print(a.n) --3

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

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

Lua 复制代码
function unpack(tb,i)
    i = i or 1
    if tb[i] then
        return tb[i],unpack(tb,i+1)
    end
end

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

...和arg的应用

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

Lua 复制代码
function printMySelf( ... )
    local strResult = ""
    for i,v in ipairs(table.pack(...)) do
        strResult = strResult..v
    end
    print(strResult)
end

printMySelf(1,"a","b",2) --1ab2

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

Lua 复制代码
function select(n, ...)
    return arg[n]
end

print(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全局关键字而报空:

Lua 复制代码
print(select(1, string.find("hello hello", " hel"))) --> nil
print(select(2, string.find("hello hello", " hel"))) --> nil

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

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

Lua 复制代码
function printMySelf( ... )
    local strResult = ""
    for i,v in ipairs(table.pack(...)) do
        strResult = strResult..v
    end
    print(strResult)
end

local tbNeedPrint = {"hello!","world"}
printMySelf(table.unpack(tbNeedPrint)) --hello!world
相关推荐
游乐码4 小时前
Unity坦克案例疑难记录(一)
unity·单例模式
小贺儿开发6 小时前
Unity3D 编辑器对象锁定工具
unity·编辑器·编程·工具·对象·互动·拓展
AI前沿资讯10 小时前
一站式 AI 3D 创作首选:V2Fun—— 直连 Unity + 多人动捕双核心,重塑轻量化生产管线
人工智能·3d·unity
winlife_19 小时前
Unity 域重载会清空一切:Editor 工具如何让状态在重载后续命
unity·游戏引擎
深度森林21 小时前
无人机“路径规划”高价值专利案例:基于抗干扰粒子群优化的无人机路径规划方法
游戏引擎·cocos2d
小贺儿开发21 小时前
Unity3D 串口通信上位机联调系统
unity·串口·协议·数据·通信·传输·互动
tedcloud1231 天前
ppt-master部署教程:快速搭建智能演示文稿系统
服务器·人工智能·系统架构·游戏引擎·powerpoint
笨鸟先飞的橘猫1 天前
基于Skynet的分布式游戏场景题:大型MMO的跨服战场系统设计
分布式·学习·游戏·面试·lua
垂葛酒肝汤2 天前
Unity的UI扫光效果Shader
ui·unity·游戏引擎
mxwin2 天前
Unity Shader Alpha测试 · 模板测试 · 深度测试
unity·游戏引擎