首页 > 解决方案 > Lua 函数 .. 可选表

问题描述

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

例如

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

这个功能应该同时工作

test(options)

test()

标签: functionlua

解决方案


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

推荐阅读