lua-users home
lua-l archive

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


On Wed, Nov 10, 2010 at 5:01 PM, Luiz Henrique de Figueiredo
<lhf@tecgraf.puc-rio.br> wrote:
>> function conditional(test)
>>   function add(item) return item end
>>   function discard() return nil end
>>   if test then return add end
>>   return discard
>> end
>
> This pollutes the global namespace and creates add and discard each time
> it is called.
>

Sorry about that, Gopalakrishnan Subramani. I was concentrated in the
format and missed some important points.

I hope that the following code solves the problems raised by Luiz.

-- begin of the "library" code
-- you can put it in "conditional_item.lua"

local function c_add(item) return item end
local function c_drop() return nil end

local function c_check(cond)
  if cond then return c_add else return c_drop end
end

local c = { conditional = c_check }

-- uncomment the following line if you are
-- creating a "conditional_item.lua" file

-- return c  -- uncomment this

--  here is the end of the "conditional_item.lua"

-- If you created a "conditional_item.lua" file
-- uncomment the following line

-- local c = require "conditional_item.lua"

-- A minimum implementation for ENUMERATION
local function ENUMERATION(tab) return tab end

-- your control var may be a constant or a function
local BIDIERCTIONAL_SUPPORTED = true -- or f()

-- ***** HOW TO USE ******
enum1 = ENUMERATION {
  {1,'a'},
  {2,'b'},
  c.conditional(false){3,'c'},
  c.conditional(true) {4,'d'},
  c.conditional(BIDIERCTIONAL_SUPPORTED) {5,'e'},
}

-- for debug: only dumps the result
for k,v in pairs(enum1) do
  print(k,v[1],v[2])
end