1
\$\begingroup\$

I'm using MoonSharp to add Lua scripting to my game. One use case involves calling a static artificial intelligence function from a static class I've implemented in C#. I know you can easily call static functions using MoonSharp, but can those functions be called if the class is static?

I haven't been able to find an answer so far through Google or on this site. My own experimentation with code hasn't been successful either. There are pretty simple workarounds for the problem I'm asking about (like making the AI class not static), but I'd prefer to avoid them.

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

One soulution could be creating a static callback function that in turn calls the function on the staic c# class

so for exmple

private staic void AiCallback(int anArgument)
{
   AiClass.DoAi(anArgument);
}

private static void RegisterAiFunction(Script aLuaScript)
{
   aluaScript.Globals["DoAi"] = (func<void, int>)AiCallback;
}

private static void DoLua(string someLuaCode)
{
   Script script = new Script();
   script.DoString(someLuacode);
}

where AiClass would be your static class

\$\endgroup\$
1
  • \$\begingroup\$ Thanks for the response :) Still not my ideal solution, but that'll work fine as a wrapper for the static class. \$\endgroup\$
    – Grimelios
    Commented Sep 26, 2016 at 21:19
1
\$\begingroup\$

I know this is an old post, but here is an example of automatically grabbing all public static methods from a class named "LuaGlobalFunctions" that automatically adds them as delegate functions to MoonSharps Script.Globals:

// Get global methods (must be public) and add them to the script.Globals
MethodInfo[] globalMethods = typeof(LuaGlobalFunctions).GetMethods(BindingFlags.Public | BindingFlags.Static);

foreach (var method in globalMethods)
{
    // Get name, parameters and return type so we can build a delegate
    string name = method.Name;
    Type[] parameters = method.GetParameters().Select(p => p.ParameterType).ToArray();
    Type returnType = method.ReturnType;

    // Build a delegate and add to globals with the name of the method, use the correct delegate type based on the return type
    if(returnType == typeof(void))
    {
        Delegate del = Delegate.CreateDelegate(Expression.GetActionType(parameters), method);
        script.Globals[name] = del;
    }
    else
    {
        Delegate del = Delegate.CreateDelegate(Expression.GetFuncType(parameters.Concat(new Type[] { returnType }).ToArray()), method);
        script.Globals[name] = del;
    }
}

Note the following using statements must be used:

using System;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using MoonSharp.Interpreter;
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .