BizHawk/BizHawk.Client.Common/lua/LuaLibraryBase.cs

91 lines
2.1 KiB
C#
Raw Normal View History

using System;
using System.Reflection;
using BizHawk.Common;
using LuaInterface;
2013-10-31 23:55:17 +00:00
namespace BizHawk.Client.Common
{
public abstract class LuaLibraryBase
{
public abstract string Name { get; }
public abstract string[] Functions { get; }
public virtual void LuaRegister(Lua lua, ILuaDocumentation docs = null)
{
lua.NewTable(Name);
foreach (var methodName in Functions)
{
var func = Name + "." + methodName;
var method = GetType().GetMethod(Name + "_" + methodName);
lua.RegisterFunction(func, this, method);
if (docs != null)
{
docs.Add(Name, methodName, method);
}
}
}
// TODO: eventually only use this, and rename it
public virtual void LuaRegisterNew(Lua lua, ILuaDocumentation docs = null)
{
lua.NewTable(Name);
foreach (var nameLookup in Functions)
{
var luaMethodName = Name + "." + nameLookup.ToLower();
var actualMethodName = GetType().GetMethod(nameLookup);
lua.RegisterFunction(luaMethodName, this, actualMethodName);
if (docs != null)
{
docs.Add(Name, nameLookup, actualMethodName);
}
}
}
protected static int LuaInt(object luaArg)
{
return (int)(double)luaArg;
}
protected static uint LuaUInt(object luaArg)
{
return (uint)(double)luaArg;
}
2014-01-19 16:58:21 +00:00
protected static long LuaLong(object luaArg)
{
return (long)(double)luaArg;
}
protected static ulong LuaULong(object luaArg)
{
return (ulong)(double)luaArg;
}
2014-01-19 16:58:21 +00:00
/// <summary>
/// LuaInterface requires the exact match of parameter count, except optional parameters.
/// So, if you want to support variable arguments, declare them as optional and pass
/// them to this method.
/// </summary>
protected static object[] LuaVarArgs(params object[] luaArgs)
{
int n = luaArgs.Length;
int trim = 0;
for (int i = n - 1; i >= 0; --i)
{
if (luaArgs[i] == null)
{
++trim;
}
}
var lua_result = new object[n - trim];
Array.Copy(luaArgs, lua_result, n - trim);
return lua_result;
}
}
}