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:52 PM, Nilson <nilson.brazil@gmail.com> wrote:

If you like to try, this is a more powerful implementation of
conditional_item.lua.
The (@@@) indicates relevant changes.

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

local function c_add(...) return ... end --(@@@)
local function c_drop() return nil end

local function c_normalize(tab) -- (@@@)
  local out = {}
  for _,v in pairs(tab) do out[#out+1] = v end
  return out
end

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

local c = { -- (@@@)
  add_if = c_check,
  normalize = c_normalize,
}

-- 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 normalized implementation of ENUMERATION (@@@)
local function ENUMERATION(tab) return c.normalize(tab) end

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

-- ***** HOW TO USE ******
enum1 = ENUMERATION {
  {1,'a'},
  {2,'b'},
  c.add_if(false) {3,'c'},
  c.add_if(true) {4,'d'},
  c.add_if(BIDIRECTIONAL_SUPPORTED) {5,'e'},
  nil,
  {6,'f'},
  -- (@@@)
  c.add_if(true) ( -- to add multiple items use "("
    {7,'g'},
    {8,'h'} -- you cannot put a comma here
  ),
}

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