Lua 没有函数重载或参数类型检查,如果需要,这些应该由需要的人实现。
传达您的功能的用法也取决于您。
如果你对你提供的sn-p不满意,你可以用其他方式重写它,例如:
function(arg1,arg2,arg3)
tab=arg1
if not arg3 then
value=arg2
index=#tab+1
else
assert(type(arg2)=='numer',"bad argument #2 to 'insert' (number expected, got table)")
value=arg3
index=arg2
end
table.insert(tab,index,value)
end
或:
f2=function(a,b)
--do smth
end
f3=function(a,b,c) end
f=function(...)
args={...}
nargin=#args
if nargin==2 then
f2(args[1],args[2]) --one way to use varied arguments
elseif nargin==3 then
f3(...) --other one
else error("wrong number of arguments")
end
end
不过,我不建议您使用可选的中间位置参数来制作函数。至少不是在没有编译时类型检查的语言中,甚至在那些语言中也是如此。
如果您真的想要可选参数,请将它们放在表格中:
function(args)
tab=args.table
index=args.index or #tab+1
value=args.value
--other arguments, options and associated logic here
table.insert(tab,index,value)
end