[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: switch statement
- From: David Jeske <jeske@...>
- Date: Mon, 7 Dec 1998 16:26:58 -0800
On Mon, Dec 07, 1998 at 09:35:13PM -0200, David Jeske wrote:
> With a little trickery, you can make this even cooler...
>
> Switch{
> [1] = function (x) B1 end,
> [2] = function (x) B2 end,
> ["nop"] = function (x) B3 end,
> ["my name"] = function (x) B4 end,
> ["__default__"] = function (x) B5 end
> }[x](arg);
>
> Where the 'Switch' function sets the tag of the table so unknown
> accesses return the "__default__" element.
Or you could put the switchvar and arguments up at the top:
Switch(switch_var,{arg1, arg2}, {
[1] = function (x) B1 end,
[2] = function (x) B2 end,
["nop"] = function (x) B3 end,
["my name"] = function (x) B4 end,
["__default__"] = function (x) B5 end
});
function Switch(sw_var, args, swtbl)
local val;
val = swtbl[sw_var]
if (not val) then
val = swtbl["__default__"];
if (not val) then
lua_error(format("Missing case in switch ("..
tostring(sw_var)..")"));
end
end
if (type(val) ~= "function") then
if (not args) then
return val; -- passive switch
else
lua_error(format("Non function case in switch ("..
tostring(sw_var)..")"));
end
end
return call(val,args); -- I think this is the right syntax for call()
end
======
I have a question for the Lua implementors though. What are the
performance implications of putting this table initialization syntax
within a function call? What is the overhead of putting the above example in a function vs doing it like this:
switch_tbl = {
[1] = function (x) B1 end,
[2] = function (x) B2 end,
["nop"] = function (x) B3 end,
["my name"] = function (x) B4 end,
["__default__"] = function (x) B5 end
};
function a()
Switch(switch_var,{arg1,arg2},switch_tbl);
end
--
David Jeske (N9LCA) + http://www.chat.net/~jeske/ + jeske@chat.net