lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 30 March 2012 13:27, Dirk Laurie <dirk.laurie@gmail.com> wrote:
~~~
-- Searches a method in a list of tables. This will be the core
-- of multiple inheritance featur-- Searches an item in a table.
-- Returns true on success, plus the key, otherwise false.
local function table_find(item,table)
       for k in pairs(table) do
               if table[k] == item then return true,k end
       end
       return false
end
~~~

It's more idiomatic to return `nil` if the item is not in the table
and otherwise return the key.

Or do not return anything at all. When `table_find` is called as an _expression_, Lua will adjust the result list (empty, no return) to 1 element with value `nil`, which is equivalent to the idiomatic way. Not everyone will agree, but I find it a bit clearer this way - if found, return something, otherwise "leave it"...