lua 函数 默认值_定义函数参数的默认值

在 Lua 中实现类似 PHP 或 Python 的命名参数和默认值可以通过将参数传递为表来实现。函数内部通过元表的 __index 来处理缺失的参数。可以使用更复杂的表构造和函数来创建自定义的参数风格,例如根据参数名和默认值定义函数。一些有用的辅助函数如 unpack、setfenv(在 5.2 中被替换)和 select 可用于参数转换。
摘要由CSDN通过智能技术生成

If you want named arguments and default values like PHP or Python, you can call your function with a table constructor:

myfunction{a,b=3,c=2}

(This is seen in many places in Lua, such as the advanced forms of LuaSocket's protocol modules and constructors in IUPLua.)

The function itself could have a signature like this:

function myfunction(t)

setmetatable(t,{__index={b=7, c=5}})

local a, b, c =

t[1] or t.a,

t[2] or t.b,

t[3] or t.c

-- function continues down here...

end

Any values missing from the table of parameters will be taken from the __index table in its metatable (see the documentation on metatables).

Of course, more advanced parameter styles are possible using table constructors and functions- you can write whatever you need. For example, here is a function that constructs a function that takes named-o

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值