简体   繁体   English

Lua 5.2 LUA_GLOBALSINDEX 备选方案

[英]Lua 5.2 LUA_GLOBALSINDEX Alternative

I have a program that embeds Lua and implements a form of lazy function lookup.我有一个嵌入 Lua 并实现一种惰性 function 查找形式的程序。

The way it worked in Lua 5.1, whenever a symbol was undefined the interpreter would call a global function hook that would then resolve the symbol.它在 Lua 5.1 中的工作方式,只要符号未定义,解释器就会调用全局 function 挂钩,然后解析该符号。

This is a small portion of C code that implemented this lazy function lookup:这是实现此惰性 function 查找的 C 代码的一小部分:

int function_hook(lua_State *pLuaState)
{
  // do the function lookup here
  ....
  return 1;
}

......

//-- create table containing the hook details
lua_newtable(pLuaState);
lua_pushstring(pLuaState, "__index");
lua_pushcfunction(pLuaState, function_hook);
lua_settable(pLuaState, -3);

//-- set global index callback hook
lua_setmetatable(pLuaState, LUA_GLOBALSINDEX);

I'm now trying to move this code to Lua 5.2 and have run into a problem.我现在正尝试将此代码移至 Lua 5.2,但遇到了问题。

In Lua 5.2 the LUA_GLOBALSINDEX value is no longer defined so this line of code no longer compiles.在 Lua 5.2 中,LUA_GLOBALSINDEX 值不再定义,因此这行代码不再编译。

//-- set global call back hook
lua_setmetatable(pLuaState, LUA_GLOBALSINDEX);

There is a reference to this change to LUA_GLOBALSINDEX but unfortunately it has not helped.有一个对 LUA_GLOBALSINDEX 的更改的引用,但不幸的是它没有帮助。

What would be the best way to re-write this one line of code to have the interpreter call the function_hook whenever it finds an unresolved symbol?重写这一行代码以使解释器在发现未解析的符号时调用 function_hook 的最佳方法是什么?

The global environment is now stored at a special index in the registry .全局环境现在存储在注册表中的一个特殊索引中。 Try:尝试:

//-- get global environment table from registry
lua_rawgeti(pLuaState, LUA_REGISTRYINDEX, LUA_RIDX_GLOBALS);

//-- create table containing the hook details
lua_newtable(pLuaState);
lua_pushstring(pLuaState, "__index");
lua_pushcfunction(pLuaState, function_hook);
lua_settable(pLuaState, -3);

//-- set global index callback hook
lua_setmetatable(pLuaState, -2);

//-- remove the global environment table from the stack
lua_pop(pLuaState, 1);

here is patch: http://lua-users.org/lists/lua-l/2013-01/msg00352.html这是补丁: http://lua-users.org/lists/lua-l/2013-01/msg00352.html

lua_pushvalue(L,LUA_GLOBALSINDEX);
=>
lua_pushglobaltable(L);

len = luaL_getn(L, -1);
=>
len = lua_rawlen(L, -1);

lua_getfenv(L, lo);
=>
lua_getuservalue(L, lo);

lua_setfenv(L, lo);
=>
lua_setuservalue(L, lo);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM