lupa icon indicating copy to clipboard operation
lupa copied to clipboard

Overwrite the behavior of require?

Open stautonico opened this issue 3 years ago • 1 comments

I would like to be able to overwrite the behavior of the require function. I want to be able to manually provide the lua functions (preferably via a string rather than from a file on the filesystem) since I am running in a very isolated environment that should have no filesystem access. How can I do this?

stautonico avatar Apr 04 '23 22:04 stautonico

This is what I came up with. It seems to work, but I'm not sure if it'll be reliable in the long run

 self.lua.globals().require = self.require


def require(self, module_name):
    # Check if the module is already loaded
    if module_name in self.lua.globals().package.loaded:
        return self.lua.globals().package.loaded[module_name]

    # Try to load the .lua file from our custom directory (for debugging, we can get the source of the lua module however we want)
    try:
        with open(f"/tmp/{module_name}.lua", "r") as f:
            module_code = f.read()
    except FileNotFoundError:
        raise ModuleNotFoundError(f"module '{module_name}' not found")

    # Return the module
    self.lua.globals().package.loaded[module_name] = self.lua.execute(module_code)
    return self.lua.globals().package.loaded[module_name]

Also, are there docs for this library? I can't seem to find any and they would really help

stautonico avatar Apr 04 '23 22:04 stautonico