Giter Site home page Giter Site logo

override `require` about nlua HOT 6 OPEN

ParadiseFallen avatar ParadiseFallen commented on September 27, 2024
override `require`

from nlua.

Comments (6)

ParadiseFallen avatar ParadiseFallen commented on September 27, 2024
using System.Text;

using KeraLua;

using LuaEmbeded;

var script = """

    require('chunk');
    print(_ENV.package);
    -- testPrint("hello world")
    print('test');

    """;

var chunk = """
    
    function testPrint(arg)
        print(arg .. "hook 2");
    end

    """;

// create engine
var luaEngine = new NLua.Lua(false);

// configure encoding
luaEngine.State.Encoding = Encoding.UTF8;

// configure host functions
// there is extension method that cast it to delegate and pass delegate.Method 
luaEngine.RegisterFunction("print", PrintHook<object>);

Delegate x = LoadHook;
luaEngine.RegisterFunction("require", x.Method);

var bytes = Encoding.UTF8.GetBytes(chunk);
luaEngine.State.LoadBuffer(bytes, "chunk");
luaEngine.State.LoadString(chunk,"chunk");
luaEngine.LoadString(chunk, "chunk");

try
{

    var result = luaEngine.DoString(script, "Main");
    foreach (var item in result)
        Console.WriteLine(item);

}
catch (Exception ex)
{
    Console.WriteLine(ex);
}

static void PrintHook<T>(T text) =>
    Console.WriteLine($"Hooked {text}");

void LoadHook(string packageName)
{
    try
    {
      // this method binds fine BUT
        Console.WriteLine(packageName);
        // if uncomment next line it will throw exception even not calling this method
        // luaEngine.DoString("print(123)");
    }
    catch (Exception ex)
    {
        throw;
    }
}

from nlua.

ParadiseFallen avatar ParadiseFallen commented on September 27, 2024

UPD: what i found is: https://github.com/NLua/NLua/blob/main/tests/src/LuaTests.cs#L252
so basically you need to set context of delegate
if you change to LuaEngine.RegisterFunction("require", this, LoadHook); it dosent crash at least,

btw extensions is:

public static class Extensions
{

    public static void RegisterFunction(this NLua.Lua lua, string path, Delegate @delegate) =>
        lua.RegisterFunction(path, @delegate.Method);

    public static void RegisterFunction(this NLua.Lua lua, string path, object target, Delegate @delegate) =>
       lua.RegisterFunction(path, target, @delegate.Method);

}

from nlua.

ParadiseFallen avatar ParadiseFallen commented on September 27, 2024

after researching found that in hook enough just to DoString and pass chunk there. But there is huge mistake.

Default require method in lua use cache inside lua. if ill override require then import will be not cached

from nlua.

Hi-ImKyle avatar Hi-ImKyle commented on September 27, 2024

I have never passed a method to Lua with RegisterFunction before but you can just do the following

var lua = new Lua()
lua["require"] = (Action<string>)LoadHook;

This completely overrides the original implementation.

from nlua.

ParadiseFallen avatar ParadiseFallen commented on September 27, 2024

@Hi-ImKyle with RegisterFunction i have for some reason many override like f:BeginInvoke() and others. wiered behaviour

from nlua.

vincywindy avatar vincywindy commented on September 27, 2024

I use this,it works!

            using var lua = new Lua();
            lua.State.Encoding = Encoding.UTF8;
           lua["require"] = new Func<string, object?>(d =>
            {
                var str = File.ReadAllText(d + ".lua");
            //any other way to load lua string
                var function = lua.DoString(str);
                if (function.Count() == 1)
                {
           //local a= require 'xx' return if has return values
                    return function[0];
                }
                return null;
            });

from nlua.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.