【问题标题】:How to create a function with variable parameters just like table.insert()?如何创建具有可变参数的函数,就像 table.insert()?
【发布时间】:2018-11-21 09:51:08
【问题描述】:

我知道我可以使用 function(a, b, ...) 来解决可变参数问题。但是,如果我想创建一个类似 table.insert (table, [pos,] value) 的函数,我该怎么办? 当然,不是以下方式:

function (table, pos, value)
    if value == nil then
        pos = value 
        value = nil
    end
    -- do something
end

【问题讨论】:

  • 为什么不采用上面的方式?

标签: lua lua-table


【解决方案1】:

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

【讨论】:

  • thx,有人问我table.insert()的用法,但是觉得变量参数在中间有问题。所以我只是想知道变量参数是否有特殊用法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-01
  • 2012-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多