lua-users home
lua-l archive

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


Right now if you want to retrieve a field using the C API, it takes
three lines per field:
lua_getfield(L, index, "field name");
lua_Integer val = lua_tointeger(L, -1);
lua_pop(L, 1);

plus usually a fourth, blank line if you don't want the code to look
messy. This isn't really ideal for writing concise, clean code.

What would improve this is a function, lua_popinteger(L), which pops
an integer from the stack and returns it. (and the same for other
types, of course.) This combines the lua_tointeger() and lua_pop()
above into one line. More importantly, it would allow the use of a C
macro to condense it even further by abusing the comma operator a bit:

#define LUA_GET_FIELD(L, index, name, type) (lua_getfield((L),
(index), (name)), lua_pop##type(L))

lua_Integer val = LUA_GET_FIELD(L, index, "field name", integer);
//four lines condensed into one
lua_Number x = LUA_GET_FIELD(L, index, "another field", number);
etc... My understanding is that with the current API, such a macro is
not possible without using gcc extensions - the result of (a, b, c) is
c, so either the last statement needs to return the value (which with
the current API is impossible, because the last statement has to be
lua_pop), or we need to store the result somewhere and make it the
last statement, like:
(lua_getfield(), int tmp = lua_toxxx(), lua_pop(), tmp)
but (without using gcc extensions) this is illegal, as you can't
declare a variable there.

Of course if I'm wrong and it is possible to create such a macro
without these new functions, that'd be great too... :-)

-- 
Sent from my toaster.