两种写法不一样的
先看文档
void lua_rawget (lua_State *L, int index);
Pushes onto the stack the value t[k]
, where t
is the value at the given valid index and k
is the value at the top of the stack.
This function pops the key from the stack (putting the resulting value in its place). As in Lua, this function may trigger a metamethod for the "index" event (see§2.8).
void luaL_unref (lua_State *L, int t, int ref);
Releases reference ref
from the table at index t
(see luaL_ref
). The entry is removed from the table, so that the referred object can be collected. The reference ref
is also freed to be used again.
再看luaL_unref实现代码
#lauxlib.c
504 LUALIB_API void luaL_unref (lua_State *L, int t, int ref) {
505 if (ref >= 0) {
506 t = abs_index(L, t);
507 lua_rawgeti(L, t, FREELIST_REF);
508 lua_rawseti(L, t, ref); /* t[ref] = t[FREELIST_REF] */
509 lua_pushinteger(L, ref);
510 lua_rawseti(L, t, FREELIST_REF); /* t[FREELIST_REF] = ref */
511 }
512 }
第一种写法, 注意是三行不是两行:
# ngx_http_lua_ctx.c
209 lua_pushliteral(L, ngx_http_lua_ctx_tables_key);
210 lua_rawget(L, LUA_REGISTRYINDEX);
211 luaL_unref(L, -1, clndata->ref);
仔细读一下, 执行到211行时第二个索引参数指向registry[ngx_http_lua_ctx_tables_key]
第二种写法:
lua_pushliteral(L, ngx_http_lua_ctx_tables_key);
lua_unref(L, LUA_REGISTRYINDEX, ctx->ctx_ref);
这个里第二个索引参数指向registry
On Thursday, August 20, 2015 at 5:06:44 PM UTC+8, forever...@gmail.com wrote:
看ngx_lua代码,有个疑问。代码中大量出现类似如下的代码:
lua_rawget(L, LUA_REGISTRYINDEX);
luaL_unref(L, -1, ctx->ctx_ref);
为什么要这样写,而不是写成:
lua_unref(L, LUA_REGISTRYINDEX, ctx->ctx_ref);
搜索了一下,没有一处代码是这么写的。我对lua为c层面提供的api没有多少研究,所以我想知道这样做的考虑是什么呢?这样效率更高吗?
麻烦了解底层细节的同学帮忙解释一下,谢谢!