【问题标题】:Lua Functions .. Optional TableLua 函数 .. 可选表
【发布时间】:2020-07-28 04:18:39
【问题描述】:

如何在可选的lua函数中传递表。

例如

function test(options)
   local a = options.a
end

这个功能应该同时工作

test(options)

test()

【问题讨论】:

    标签: function lua


    【解决方案1】:
    function test(options)
    
      options = options or {}
      local a = options.a or 0 -- or whatever it defaults to
    
    end
    

    您只需or 可选值及其默认值。 如果尚未提供该值并因此为nil,它将解析为ored 值。

    这是一个较短的版本

    function test(options)
      if not options then
        options = {}
      end
      local a = 0
      if options.a then
        a = options.a    
      end
    end
    

    【讨论】:

    • 除了options.a 是实际的false 值之外,在这种情况下or 技巧不会产生正确的结果。最好明确检查nil
    • @tonypdmtr 是的,你是对的,但如果你期望类似 false 的东西,你通常不会将 0 作为默认值。提供任何真实值,但选项表无论如何都会导致错误。简单的代码示例通常没有广泛的验证和错误处理。您也不能将 or false 作为默认值
    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 2014-06-11
    • 2018-10-18
    • 2016-11-19
    • 2018-07-01
    • 2010-10-05
    • 1970-01-01
    • 2017-06-05
    相关资源
    最近更新 更多