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;