Lua 5.2 LUA_GLOBALSINDEX 替代方案 [英] Lua 5.2 LUA_GLOBALSINDEX Alternative

查看:56
本文介绍了Lua 5.2 LUA_GLOBALSINDEX 替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌入 Lua 并实现了一种惰性函数查找形式的程序.

I have a program that embeds Lua and implements a form of lazy function lookup.

它在 Lua 5.1 中的工作方式,每当一个符号未定义时,解释器都会调用一个全局函数钩子,然后解析该符号.

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.

这是实现这种惰性函数查找的一小部分 C 代码:

This is a small portion of C code that implemented this lazy function lookup:

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);

我现在正在尝试将此代码移至 Lua 5.2,但遇到了问题.

I'm now trying to move this code to Lua 5.2 and have run into a problem.

在 Lua 5.2 中不再定义 LUA_GLOBALSINDEX 值,因此这行代码不再编译.

In Lua 5.2 the LUA_GLOBALSINDEX value is no longer defined so this line of code no longer compiles.

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

有一个参考对 LUA_GLOBALSINDEX 的这一更改,但不幸的是它没有帮助.

There is a reference to this change to LUA_GLOBALSINDEX but unfortunately it has not helped.

重写这一行代码以让解释器在发现未解析符号时调用 function_hook 的最佳方法是什么?

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?

推荐答案

全球环境现在存储在注册表的特殊索引处.试试:

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);

这篇关于Lua 5.2 LUA_GLOBALSINDEX 替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆