Search code examples
lualua-table

Are fallback tables a common practice in lua?


I have a need to write some Lua code but having come from a C background some of the common practices and programming strategies seem unusual to me. That said I wrote some code that illustrates what I am having trouble with:

local someFunction(myName)
  local fallbackTable = {name = ""}    

  local myTable = getTableOrReturnNil(someArgument) or fallbackTable
  local otherName = myTable["name"]
  --other code that is irrelevant
end

My question is specifically regarding the line local myTable = getTableOrReturnNil(someArgument) or fallbackTable. From what I understand this expression will evaluate to fallbackTable if the return value from getTableOrReturnNil() return nil. It may be worth mentioning that I do not have control over the function getTableOrReturnNil(). Is this a common practice or is there a more standard way to do local otherName = myTable["name"] safely without having to worry about if myTable is nil. I can resort to using a chain of if's but I would rather avoid this if possible.


Solution

  • Fallback values in functions are, especially for optional parameters. Maybe not entire tables as often, but it's not unheard of.

    local function clamp( value, minimum, maximum )
        minimum = minimum or 0
        maximum = maximum or 255
        return math.min( math.max( value, minimum ), maximum )
    end
    
    print(  clamp( -50 ),  clamp( 50 ),  clamp( 500 )  )
    

    0 50 255



    With tables, you're more likely to see metatables used when a value isn't present.

    mytable  = { name = 'nomer' }
    meta  = {  __index  = function( tbl, key ) return 'misnomer' end  }
    
    setmetatable( mytable, meta )
    print( mytable['name'],  mytable['noname'] )
    

    nomer misnomer

    https://www.tutorialspoint.com/lua/lua_metatables.htm