lua-users home
lua-l archive

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


Hi there,

something like this might do it for a C-style case statement (taking
advantage of luas first class functions):

function case(item)
        return function(array)
                if array[item] then 
                        return array[item](item)
                elseif array['default'] then
                        return array['default'](item)
                else
                        return nil
                end
        end
end

-- try

for _,v in {'y', 1, 2} do
        print("Testing "..tostring(v))
        case(v) {
                x = function () print "-> case was x" end,
                y = function () print "-> case was y" end,
                z = function () print "-> case was z" end,
                [1] = function () print "-> case was 1" end,
                default = function (x) print ("-> uncaught value: " .. tostring(x)) end
        }
end

should be reasonably fast, too.

HTH,

Gunnar


ac> Hi,

ac> As far as I can tell, Lua evaluates arguments to functions eagerly.  Is
ac> there any way of treating blocks of code lazily?

ac> For example, if I want to add a "case" statement to Lua that looks
ac> something like:

ac> case x
ac> of   1 do ... end
ac> of   2 do ... end
ac> else   do ... end

ac> would I be able to?  My initial idea was to define case as a vararg
ac> function, but if arguments are evaluated eagerly then this won't work (I
ac> believe).

ac> The syntax in the example above isn't important - what I'm looking for is
ac> a way of handling sections of code as first class objects, and for them
ac> not to be evaluated when passed as arguments, I think.

ac> Cheers,
ac> Andrew