LUA: Finding Effective and Error-Free Default Arguments

Instead of using long lists of arguments in the definitions of my function, I prefer to pass a few fixed parameters and a table of "additional parameters" as follows:

function:doit( text, params )
end

This is nice because it allows me to add new named parameters later without breaking old calls.

The problem I am encountering occurs when I try to force default values ​​for some parameters:

function:doit( text, params )
   local font     = params.font or native.systemBold 
   local fontSize = params.fontSize or 24
   local emboss   = params.emboss or true

   -- ...

end

The above code works fine in all cases, except when I went "false" for embossing:

doit( "Test text", { fontSize = 32, emboss = false } )

The above code will cause the embossing to be set to true when I really need false.

, , , NIL, , -NIL.

, , , NIL, :

function firstNotNil( ... )
   for i = 1, #arg do
      local theArg = arg[i]
      if(theArg ~= nil) then return theArg end
   end
   return nil
end

, :

   local emboss   = firstNotNil(params.emboss, true)

, , , . , .

: , , , lua - :

[c,b,a].detect { |i| i > 0 } -- Assign first non-zero in order: c,b,a
+5
2

Lua (.. ), C- C, a and b or c. a, nil b , a == nil and b or a:

local emboss = (params.emboss == nil) and true or params.emboss

, , .


[snip - Lua]

, , , .

: , , , lua - :

[c, b, a].detect {| | i > 0} - : c, b, a

Lua . Ruby , , firstNotNil(c,b,a). , , , .

Lua vararg select:

function firstNotNil(...)
   for i = 1, select('#',...) do
      local theArg = select(i,...)
      if theArg ~= nil then return theArg end
   end
   return nil
end

, .

- .;)

+8

, - true:

local emboss   = params.emboss or (params.emboss == nil)

, . (params.emboss == nil) true, params.emboss ( ), false. , params.emboss , , , (true false = true).

false, , , :

local emboss   = params.emboss or false
+4

All Articles