修改Lua Chunk环境:Lua 5.2 [英] Modify Lua Chunk Environment: Lua 5.2

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

问题描述

据我了解,在Lua 5.2中,环境存储在名为_ENV的升值中.这使我在运行之前但在加载之后修改块的环境确实感到困惑.

It is my understanding that in Lua 5.2 that environments are stored in upvalues named _ENV. This has made it really confusing for me to modify the environment of a chunk before running it, but after loading it.

我想加载具有某些功能的文件,并使用块将这些功能注入各种环境.示例:

I would like to load a file with some functions and use the chunk to inject those functions into various environments. Example:

chunk = loadfile( "file" )

-- Inject chunk's definitions
chunk._ENV = someTable -- imaginary syntax
chunk( )

chunk._ENV = someOtherTable
chunk( )

在Lua内部可能吗?我可以找到的唯一修改此升值的示例是

Is this possible from within Lua? The only examples I can find of modifying this upvalue are with the C api (another example from C api), but I am trying to do this from within Lua. Is this possible?

我不确定使用调试库接受答案. 文档指出,该功能可能很慢.我这样做是为了提高效率,这样就不必为了将变量定义注入各种环境而不必从字符串(或文件,甚至更糟)中解析整个块.

I'm unsure of accepting answers using the debug library. The docs state that the functions may be slow. I'm doing this for efficiency so that entire chunks don't have to be parsed from strings (or a file, even worse) just to inject variable definitions into various environments.

看起来这是不可能的:在Lua 5.2

Looks like this is impossible: Recreating setfenv() in Lua 5.2

我想对我来说最好的方法是绑定一个可以修改环境的C函数.尽管这是一种更烦人的解决方法.

I suppose the best way for me to do this is to bind a C function that can modify the environment. Though this is a much more annoying way of going about it.

我相信一种更自然的方法是将所有块加载到单独的环境中.通过设置引用块的全局副本的元表,这些可以被任何其他环境继承".这不需要在加载后进行任何升值修改,但仍允许使用这些函数定义的多个环境.

I believe a more natural way to do this would be to load all chunks into separate environments. These can be "inherited" by any other environment by setting a metatable that refers to a global copy of a chunk. This does not require any upvalue modification post-load, but still allows for multiple environments with those function definitions.

推荐答案

允许块在不同环境中运行的最简单方法是使其明确并使其接受环境.将这一行添加到代码块的顶部即可达到以下目的:

The simplest way to allow a chunk to be run in different environments is to make this explicit and have it receive an environment. Adding this line at the top of the chunk achieves this:

_ENV=...

现在,您可以根据需要拨打chunk(env1)和更高版本的chunk(env2)了.

Now you can call chunk(env1) and later chunk(env2) at your pleasure.

在那里,没有debug具有高价值的魔法.

There, no debug magic with upvalues.

尽管可以清楚地知道您的块中是否包含该行,但是您可以在加载时通​​过编写一个合适的读取器函数来添加它,该函数首先发送该行,然后发送文件的内容.

Although it will be clear if your chunk contains that line, you can add it at load time, by writing a suitable reader function that first sends that line and then the contents of the file.

这篇关于修改Lua Chunk环境:Lua 5.2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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