lua-users home
lua-l archive

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

Niccolo Medici <> wrote:

> lauxlib.h has:
>  #define luaL_optstring(L,n,d)  (luaL_optlstring(L, (n), (d), NULL))
>  #define luaL_typename(L,i)     lua_typename(L, lua_type(L,(i)))
> Why are there "(n)" / "(d)" / "(i)" instead of "n" / "d" / "i"? There
> are commas around these letters so there shouldn't be a potential
> precedence problem there, or am I wrong?
> There are #define's there without parentheses:
>  #define luaL_loadbuffer(L,s,sz,n)  luaL_loadbufferx(L,s,sz,n,NULL)
> (Why am I asking this? Because I'll have to duplicate some of these
> macros in my own code ('cos these macros aren't always present: not if
> the various COMPAT macros aren't enabled), and I don't want them to
> have a different style than my current code.)

I can explain this best with a simple example:

#define ackoop(a)  a * 20

ackoop(5 + 7)

This would expand to:

5 + 7 * 20

Which would give you 145, not the 240 you may of been expecting.

#define ackoop(a)  (a) * 20

This would expand to:

(5 + 7) * 20

Which would be the value you would expect. The brackets in the macro simply ensure that the passed parameters, which may be expressions(!), are evaluated in the correct order, without the brackets there is no way to ensure the order of operations will work as you would expect.

As for the macros without brackets, those macros assume the passed in parameters will not be expressions, but rather things like a Lua State pointer, therefore the parameter guard brackets are not necessary.