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
相关推荐
zhchyun200811 小时前
# 【Unity UI 进阶】仿 Element UI 打造企业级 Unity UI 组件库(03)
unity
淡海水1 天前
15-02-YooAsset面试篇-Unity架构设计与源码
java·unity·面试·c#·游戏引擎·yooasset
郝学胜-神的一滴1 天前
中级OpenGL教程 030:gl_FragCoord解锁区域渲染与深度可视化新姿势
c++·unity·游戏引擎·图形渲染·unreal engine·opengl
ellis19701 天前
u3d插件xLua[四]Lua访问C#源码分析,反射,生成代码
unity
2401_894915531 天前
GEO 定位优化源码搭建常见报错排查:数据库、伪静态、接口调试
java·数据库·网络协议·tcp/ip·spring·unity
l1t1 天前
用李红艳先生的DuckDB luajit插件批量计算数独
数据库·sql·lua·duckdb
xcLeigh2 天前
Unity基础:C#脚本的创建与挂载——让你的游戏物体活起来
游戏·unity·c#·教程