Lua学习教程之 可变參数数据打包与解包

时间:2022-07-17 04:44:01

利用table的pack与unpack进行数据打包与解包。測试代码例如以下:

print("Test table.pack()----------------");

function printTable ( t )
if type(t) == "table" then
for k,v in pairs(t) do
printTable(v);
end
else
print(t);
end
end local packData =function( ... ) local arg = table.pack(...); --arg.n 得到可变部分的參数的个数
-- print("arg.n:", arg.n) for k,v in pairs(arg) do
print("----------------");
print(k,v);
printTable(v);
print("----------------");
end return arg;
end packData({type=100,param={"param1", "param2", "param3"}});
-- packData("param1", "param2", "param3","param4","param5"); print("\nTest table.unpack()----------------");
local data = {"AA", "BB", "CC", "DD"}
print(table.unpack(data))
print(table.unpack(data, 2))
print(table.unpack(data, 2, 3))

打印数据:

Lua学习教程之 可变參数数据打包与解包