an emulation of enum
Posted: Wed Feb 17, 2010 9:34 pm
There are some cool things in the change log that alterecco found.
We are going to use that to emulate enum.
first the code then I will explain it
First thing that is happening is we are creating a lambda function with three arguments. The % will tell it not to evaluate them so if you pass in name the % argument will have the string name whereas a normal argument would have whatever the variable name contained.
Then we make a block with two temporary variables counter (saying where we are on the list) and func (to contain the function that happens to every item on the list).
Counter gets setq to 0 and func gets a lambda function made out of the variable name and the code to be evaluated. Note that nothing is ran yet but it is evaluated to turn it into a lambda function.
Now we just have a simple loop so we can run the function with every item. Also note that because enum returns the last thing evaluated we need to increment the counter before running the function.
We now have a function that acts just like enum. You can do
(metaEnum '(a b c d) myItem (dbgOutput myItem))
and it would do the same thing as
(enum '(a b c d) myItem (dbgOutput myItem))
Slightly altered enums can be very useful and now we have a way to do them.
We are going to use that to emulate enum.
first the code then I will explain it

Code: Select all
(setq metaEnum (lambda (enumlist %Itemvar %exp)
(block (counter func)
(setq func (eval (list lambda (list %Itemvar) %exp)))
(setq counter 0)
(loop (ls counter (count enumlist))
(block nil
(setq counter (add 1 counter))
(func (item enumList (subtract counter 1)))
)
)
)
))
Then we make a block with two temporary variables counter (saying where we are on the list) and func (to contain the function that happens to every item on the list).
Counter gets setq to 0 and func gets a lambda function made out of the variable name and the code to be evaluated. Note that nothing is ran yet but it is evaluated to turn it into a lambda function.
Now we just have a simple loop so we can run the function with every item. Also note that because enum returns the last thing evaluated we need to increment the counter before running the function.
We now have a function that acts just like enum. You can do
(metaEnum '(a b c d) myItem (dbgOutput myItem))
and it would do the same thing as
(enum '(a b c d) myItem (dbgOutput myItem))
Slightly altered enums can be very useful and now we have a way to do them.