[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Lua as Configuration Conditional Statement inside table definition
- From: steve donovan <steve.j.donovan@...>
- Date: Wed, 10 Nov 2010 13:27:16 +0200
On Wed, Nov 10, 2010 at 12:08 PM, Gopalakrishnan Subramani
<gopalakrishnan.subramani@gmail.com> wrote:
> Is it possible to add anonymous function to the table and through meta
> table, I can check the type of the element added to the table.
> Enum1 = ENUMERATION {
> {2, "Backword"},
>
> function()
> if BIDIERCTIONAL_SUPPORTED then
> return {3, "BiDirectional"}
> end,
Oh yes, that would work. You would iterate over the table and if it
was a function, evaluate it.
function ENUMERATE (spec)
local res = {}
for _, item in ipairs(spec) do
if type(item) == 'function' then item = item() end
if item then
res[item[2]] = res[item[1]]
end
end
Will end up with a table like so {Forward=1,Backword=2,None=4} if the
function failed.
> Thing is, it should be readable format.
Now that's the thing! In which case, I think Luiz' format is
definitely the way to go - read up about how and/or behave in Lua.
But, there's usually always another way in Lua. Make a function that
returns the function
function cond(cond_var, item)
return function()
if _G[cond_var] then return item end
end
end
Then the anonymous function in the table constructor simply becomes
cond('BIDIRECTIONAL_SUPPORTED',{3,"BiDirectional"})
The 'quoting' of the condition is important, if you want this to work
at _run-time_. Otherwise, the condition variable is evaluated at
compile-time.
steve d.