更优雅的方式在LUA中选择默认值并避免"尝试索引字段'x'(零值)"

Jam*_*ton 0 parameters lua default

所以我传递一个包含字段的参数.它将永远有一些领域,有些可能没有.

例如

field = {
  Name  ={  x=0.9833, y=2, h=0.2, w=3.12, f="Times Roman"},
  Suite ={  x=0.6933, y=1.74, h=0.2, w=0.5867}
}

function do_it_with(parm)
  local height=parm.h -- never fails
  local font=parm.f -- errors out if f not specified. 
-- more stuff --
  end

do_it_with(field.Name) -- just fine
do_it_with(field.Suite) -- "attempt to index field 'f' (a nil value)"
Run Code Online (Sandbox Code Playgroud)

哪个我不明白.首先,为什么字体不能变成零?第二,我以为我可以做到

local font=parm.f or "Arial"
Run Code Online (Sandbox Code Playgroud)

但这似乎是失败的同样的错误.所以现在我正在做

if (type(field.f) ~= "string") then field.f = "Arial" end
Run Code Online (Sandbox Code Playgroud)

哪个有效,但它/丑陋/

小智 6

do_it_with尝试中必须有一些地方parm.f.whatever而不是font.whatever代码中的某个地方,或者具有相同构造的其他地方.尝试在.f.编辑器中搜索.

parm.f or "Arial"构造确实是获取默认值的有用且通常的习惯用法.