lua-users home
lua-l archive

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


Difficult. There are few cases in lua where I think macros could (maybe) be
useful (though I don't missed macros at all and I am used to use them in C code
- local functions in lua are far more useful than these C macros). 

C code example of one of the few advantages that macros may offer:

#include <stdlib.h>

#define printint(x) printf("%s = %i\n",#x,x)

int main() {
  int bla = 50;
  printint(bla);
  return 0;
}


The output is "bla = 50". 

This is neat in C for debugging outputs, in some cases even, this is also useful
for writing a macro to bind lua C functions without specifying a special string
(like a macro that takes func as argument (cfunc2lua(func)) where func is a
(int func (lua_State*)) function, and publishes it in lua as a function named
"func" in the global registry index).

However - I can hardly imagine situations in lua where this would be really
useful (though some have asked if it would be possible to find out the variable
name in the called function, which is currently not possible, but I don't see
much sense in it).

Another case could be, that variables are altered without specific assignments:

#define mul2(var) var = var<<1

There is no need in this case to assign a value to a variable, as the macro
takes care of it. A slight more useful case also for lua codes could be
(pseudocode):

#define scale(x,...) for var in ... do var = var*x end
usage: 
scale(3,x,y,z)

contrary, the (valid) lua code looks like this:

function scale (x,...)
  local ret = {}
  for i=1,select('#',...) do
    ret[i] = select(i)*x
  end
  return unpack(ret)
end

x,y,z = 1,2,3
x,y,z = scale(3,x,y,z)

I don't see here much of a drawback contrary to macros. On one hand it requires
more handwriting as it is right now, however macros obfuscate things to a level
where it becomes complicated to figure out what is done by a macro.


Eike

> Hello,
> 
> at the risk of asking something very stupid:
> Can somebody explain to me which are the advantages of using LuaMacro - apart
> 
> from shortening my Lua code and making it more readable?
> 
> Maybe there are some practical examples ...?
> 
> Thanks a lot
> Eva
>