lua-users home
lua-l archive

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

I like the changes in 5.2.0-work2 to lua_cpcall, not only for reasons
in [1] but also as I mentioned today in the "Current best practice for
C++ exception handling" thread.  However, I think you want to rename
LUA_RIDX_CPCALL to LUA_RIDX_CCALL.  This index references a certain
Lua function, which I'll refer to as `ccall` (currently named
`cpcall`), that pops and calls a given C function provided as
lightuserdata, while accepting and returning values on the Lua stack.
It applies no protection ("P").  ccall is a Lua function analogous to
what a `lua_ccall` API function would be if it existed.

You may pass ccall to pcall/lua_pcall, but there may be cases where
it's useful to call directly without protection.  I often efficiently
implement properties on userdata by defining in C an __index
metamethod that uses the provided key (k) to look up the corresponding
C function (lightuserdata) in a table and call it like a lua_ccall
would.  It's possible I could now rewrite the __index metamethod in

  local ccall = debug.ccall
  local props = {} -- filled in with C function lightuserdata
  function mt.__index(u,k)
    local cf = props[k]
    return cf and ccall(cf, u) or rawget(t,k)
       -- where t is somehow associated with u (via userdata upvalue?)

Such code is simpler and might optimize better under LuaJIT, where
it's recommended to keep code in Lua and limit C-Lua call boundaries.

BTW, I've never needed the "lua_pushglobaltable(L); lua_replace(L,
LUA_ENVIRONINDEX);" in the current implementation of this function,
and I suppose that will nicely go away under the "new proposal for

One thing maybe still lacking in the use case in [1] is a way to push
string and heavy userdata arguments without the immediate danger of a
longjump.  Maybe a a lua_pushlstringornil could push nil upon failure
to allocate memory for the string.