更新Xlua 到最新版本

This commit is contained in:
2024-09-04 02:07:48 +08:00
parent dba48de5cf
commit 5b79a2d4bb
227 changed files with 5594 additions and 878 deletions
Assets
Plugins
XLua.meta
XLua
CHANGELOG.txtCHANGELOG.txt.meta
Doc
Editor.meta
Editor
Gen.meta
Gen
DelegatesGensBridge.csDelegatesGensBridge.cs.metaEnumWrap.csEnumWrap.cs.metaIMarketingActRetDelBridge.cs.metaLuaMainWrap.cs.metaLuaUIBehaviourWrap.cs.metaPackUnpack.cs.metaSdkControlWrap.csSdkControlWrap.cs.metaSystem_Collections_Generic_List_1_System_Int32_Wrap.cs.metaSystem_Collections_HashtableWrap.cs.metaSystem_Collections_IEnumerableBridge.cs.metaSystem_Collections_IEnumeratorBridge.cs.metaSystem_ObjectWrap.cs.metaTableManagerLuaWrap.cs.metaTutorial_BaseClassWrap.csTutorial_BaseClassWrap.cs.metaTutorial_CSCallLua_ItfDBridge.csTutorial_CSCallLua_ItfDBridge.cs.metaTutorial_DerivedClassExtensionsWrap.csTutorial_DerivedClassExtensionsWrap.cs.metaTutorial_DerivedClassWrap.csTutorial_DerivedClassWrap.cs.metaTutorial_ICalcWrap.csTutorial_ICalcWrap.cs.metaUnityEngine_AnimationClipWrap.cs.metaUnityEngine_AnimationCurveWrap.cs.metaUnityEngine_BehaviourWrap.cs.metaUnityEngine_BoundsWrap.cs.metaUnityEngine_ColorWrap.cs.metaUnityEngine_ComponentWrap.cs.metaUnityEngine_DebugWrap.cs.metaUnityEngine_GameObjectWrap.cs.metaUnityEngine_KeyframeWrap.cs.metaUnityEngine_LightWrap.cs.metaUnityEngine_MathfWrap.cs.metaUnityEngine_MonoBehaviourWrap.cs.metaUnityEngine_ObjectWrap.cs.metaUnityEngine_ParticleSystemWrap.cs.metaUnityEngine_QuaternionWrap.cs.metaUnityEngine_Ray2DWrap.cs.metaUnityEngine_RayWrap.cs.metaUnityEngine_RendererWrap.cs.metaUnityEngine_ResourcesWrap.cs.metaUnityEngine_SkinnedMeshRendererWrap.cs.metaUnityEngine_TextAssetWrap.cs.metaUnityEngine_TimeWrap.cs.metaUnityEngine_TransformWrap.cs.metaUnityEngine_Vector2Wrap.cs.metaUnityEngine_Vector3Wrap.cs.metaUnityEngine_Vector4Wrap.cs.metaUnityEngine_WWWWrap.cs.metaWrapPusher.csWrapPusher.cs.metaXLuaGenAutoRegister.csXLuaGenAutoRegister.cs.metalink.xmllink.xml.meta
Resources
Src.meta
Src
CodeEmit.csCodeEmit.cs.metaCopyByValue.csCopyByValue.cs.metaDelegateBridge.csDelegateBridge.cs.metaEditor.meta
Editor
GenAttributes.csGenAttributes.cs.metaGenericDelegateBridge.csGenericDelegateBridge.cs.metaInternalGlobals.csInternalGlobals.cs.metaLuaBase.csLuaBase.cs.metaLuaDLL.csLuaDLL.cs.metaLuaEnv.csLuaEnv.cs.metaLuaException.csLuaException.cs.metaLuaFunction.csLuaFunction.cs.metaLuaTable.csLuaTable.cs.metaMethodWarpsCache.csMethodWarpsCache.cs.metaObjectCasters.csObjectCasters.cs.metaObjectPool.csObjectPool.cs.metaObjectTranslator.csObjectTranslator.cs.metaObjectTranslatorPool.csObjectTranslatorPool.cs.metaRawObject.csRawObject.cs.metaSignatureLoader.csSignatureLoader.cs.metaStaticLuaCallbacks.csStaticLuaCallbacks.cs.metaTemplateEngine.meta
TemplateEngine
TypeExtensions.csTypeExtensions.cs.metaUtils.csUtils.cs.meta
Tutorial.meta
Tutorial

1922
Assets/XLua/Src/CodeEmit.cs Normal file

File diff suppressed because it is too large Load Diff

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 93ce5fd372271b04199841c920eb0268
timeCreated: 1470883945
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,150 @@
/*
* Tencent is pleased to support the open source community by making xLua available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using System;
namespace XLua
{
public static partial class CopyByValue
{
// for int 8
public static bool Pack(IntPtr buff, int offset, byte field)
{
return LuaAPI.xlua_pack_int8_t(buff, offset, field);
}
public static bool UnPack(IntPtr buff, int offset, out byte field)
{
return LuaAPI.xlua_unpack_int8_t(buff, offset, out field);
}
public static bool Pack(IntPtr buff, int offset, sbyte field)
{
return LuaAPI.xlua_pack_int8_t(buff, offset, (byte)field);
}
public static bool UnPack(IntPtr buff, int offset, out sbyte field)
{
byte tfield;
bool ret = LuaAPI.xlua_unpack_int8_t(buff, offset, out tfield);
field = (sbyte)tfield;
return ret;
}
// for int16
public static bool Pack(IntPtr buff, int offset, short field)
{
return LuaAPI.xlua_pack_int16_t(buff, offset, field);
}
public static bool UnPack(IntPtr buff, int offset, out short field)
{
return LuaAPI.xlua_unpack_int16_t(buff, offset, out field);
}
public static bool Pack(IntPtr buff, int offset, ushort field)
{
return LuaAPI.xlua_pack_int16_t(buff, offset, (short)field);
}
public static bool UnPack(IntPtr buff, int offset, out ushort field)
{
short tfield;
bool ret = LuaAPI.xlua_unpack_int16_t(buff, offset, out tfield);
field = (ushort)tfield;
return ret;
}
// for int32
public static bool Pack(IntPtr buff, int offset, int field)
{
return LuaAPI.xlua_pack_int32_t(buff, offset, field);
}
public static bool UnPack(IntPtr buff, int offset, out int field)
{
return LuaAPI.xlua_unpack_int32_t(buff, offset, out field);
}
public static bool Pack(IntPtr buff, int offset, uint field)
{
return LuaAPI.xlua_pack_int32_t(buff, offset, (int)field);
}
public static bool UnPack(IntPtr buff, int offset, out uint field)
{
int tfield;
bool ret = LuaAPI.xlua_unpack_int32_t(buff, offset, out tfield);
field = (uint)tfield;
return ret;
}
// for int64
public static bool Pack(IntPtr buff, int offset, long field)
{
return LuaAPI.xlua_pack_int64_t(buff, offset, field);
}
public static bool UnPack(IntPtr buff, int offset, out long field)
{
return LuaAPI.xlua_unpack_int64_t(buff, offset, out field);
}
public static bool Pack(IntPtr buff, int offset, ulong field)
{
return LuaAPI.xlua_pack_int64_t(buff, offset, (long)field);
}
public static bool UnPack(IntPtr buff, int offset, out ulong field)
{
long tfield;
bool ret = LuaAPI.xlua_unpack_int64_t(buff, offset, out tfield);
field = (ulong)tfield;
return ret;
}
// for float
public static bool Pack(IntPtr buff, int offset, float field)
{
return LuaAPI.xlua_pack_float(buff, offset, field);
}
public static bool UnPack(IntPtr buff, int offset, out float field)
{
return LuaAPI.xlua_unpack_float(buff, offset, out field);
}
// for double
public static bool Pack(IntPtr buff, int offset, double field)
{
return LuaAPI.xlua_pack_double(buff, offset, field);
}
public static bool UnPack(IntPtr buff, int offset, out double field)
{
return LuaAPI.xlua_unpack_double(buff, offset, out field);
}
// for decimal
public static bool Pack(IntPtr buff, int offset, decimal field)
{
return LuaAPI.xlua_pack_decimal(buff, offset, ref field);
}
public static bool UnPack(IntPtr buff, int offset, out decimal field)
{
byte scale;
byte sign;
int hi32;
ulong lo64;
if (!LuaAPI.xlua_unpack_decimal(buff, offset, out scale, out sign, out hi32, out lo64))
{
field = default(decimal);
return false;
}
field = new Decimal((int)(lo64 & 0xFFFFFFFF), (int)(lo64 >> 32), hi32, (sign & 0x80) != 0, scale);
return true;
}
public static bool IsStruct(Type type)
{
return type.IsValueType() && !type.IsEnum() && !type.IsPrimitive();
}
}
}

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: aba23a1792dbc49438a2357566447979
timeCreated: 1467189953
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,246 @@
/*
* Tencent is pleased to support the open source community by making xLua available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace XLua
{
public abstract class DelegateBridgeBase : LuaBase
{
private Type firstKey = null;
private Delegate firstValue = null;
private Dictionary<Type, Delegate> bindTo = null;
protected int errorFuncRef;
public DelegateBridgeBase(int reference, LuaEnv luaenv) : base(reference, luaenv)
{
errorFuncRef = luaenv.errorFuncRef;
}
public bool TryGetDelegate(Type key, out Delegate value)
{
if(key == firstKey)
{
value = firstValue;
return true;
}
if (bindTo != null)
{
return bindTo.TryGetValue(key, out value);
}
value = null;
return false;
}
public void AddDelegate(Type key, Delegate value)
{
if (key == firstKey)
{
throw new ArgumentException("An element with the same key already exists in the dictionary.");
}
if (firstKey == null && bindTo == null) // nothing
{
firstKey = key;
firstValue = value;
}
else if (firstKey != null && bindTo == null) // one key existed
{
bindTo = new Dictionary<Type, Delegate>();
bindTo.Add(firstKey, firstValue);
firstKey = null;
firstValue = null;
bindTo.Add(key, value);
}
else
{
bindTo.Add(key, value);
}
}
public virtual Delegate GetDelegateByType(Type type)
{
return null;
}
}
public static class HotfixDelegateBridge
{
#if (UNITY_IPHONE || UNITY_TVOS) && !UNITY_EDITOR
[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_get_hotfix_flag(int idx);
[DllImport("__Internal", CallingConvention = CallingConvention.Cdecl)]
public static extern void xlua_set_hotfix_flag(int idx, bool flag);
#else
public static bool xlua_get_hotfix_flag(int idx)
{
return (idx < DelegateBridge.DelegateBridgeList.Length) && (DelegateBridge.DelegateBridgeList[idx] != null);
}
#endif
public static DelegateBridge Get(int idx)
{
return DelegateBridge.DelegateBridgeList[idx];
}
public static void Set(int idx, DelegateBridge val)
{
if (idx >= DelegateBridge.DelegateBridgeList.Length)
{
DelegateBridge[] newList = new DelegateBridge[idx + 1];
for (int i = 0; i < DelegateBridge.DelegateBridgeList.Length; i++)
{
newList[i] = DelegateBridge.DelegateBridgeList[i];
}
DelegateBridge.DelegateBridgeList = newList;
}
DelegateBridge.DelegateBridgeList[idx] = val;
#if (UNITY_IPHONE || UNITY_TVOS) && !UNITY_EDITOR
xlua_set_hotfix_flag(idx, val != null);
#endif
}
}
public partial class DelegateBridge : DelegateBridgeBase
{
internal static DelegateBridge[] DelegateBridgeList = new DelegateBridge[0];
public static bool Gen_Flag = false;
public DelegateBridge(int reference, LuaEnv luaenv) : base(reference, luaenv)
{
}
public void PCall(IntPtr L, int nArgs, int nResults, int errFunc)
{
if (LuaAPI.lua_pcall(L, nArgs, nResults, errFunc) != 0)
luaEnv.ThrowExceptionFromError(errFunc - 1);
}
#if HOTFIX_ENABLE
private int _oldTop = 0;
private Stack<int> _stack = new Stack<int>();
public void InvokeSessionStart()
{
System.Threading.Monitor.Enter(luaEnv.luaEnvLock);
var L = luaEnv.L;
_stack.Push(_oldTop);
_oldTop = LuaAPI.lua_gettop(L);
LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
LuaAPI.lua_getref(L, luaReference);
}
public void Invoke(int nRet)
{
int error = LuaAPI.lua_pcall(luaEnv.L, LuaAPI.lua_gettop(luaEnv.L) - _oldTop - 2, nRet, _oldTop + 1);
if (error != 0)
{
var lastOldTop = _oldTop;
_oldTop = _stack.Pop();
System.Threading.Monitor.Exit(luaEnv.luaEnvLock);
luaEnv.ThrowExceptionFromError(lastOldTop);
}
}
public void InvokeSessionEnd()
{
LuaAPI.lua_settop(luaEnv.L, _oldTop);
_oldTop = _stack.Pop();
System.Threading.Monitor.Exit(luaEnv.luaEnvLock);
}
public TResult InvokeSessionEndWithResult<TResult>()
{
if (LuaAPI.lua_gettop(luaEnv.L) < _oldTop + 2)
{
InvokeSessionEnd();
throw new InvalidOperationException("no result!");
}
try
{
TResult ret;
luaEnv.translator.Get(luaEnv.L, _oldTop + 2, out ret);
return ret;
}
finally
{
InvokeSessionEnd();
}
}
public void InParam<T>(T p)
{
try
{
luaEnv.translator.PushByType(luaEnv.L, p);
}
catch (Exception e)
{
InvokeSessionEnd();
throw e;
}
}
public void InParams<T>(T[] ps)
{
try
{
for (int i = 0; i < ps.Length; i++)
{
luaEnv.translator.PushByType<T>(luaEnv.L, ps[i]);
}
}
catch (Exception e)
{
InvokeSessionEnd();
throw e;
}
}
//pos start from 0
public void OutParam<TResult>(int pos, out TResult ret)
{
if (LuaAPI.lua_gettop(luaEnv.L) < _oldTop + 2 + pos)
{
InvokeSessionEnd();
throw new InvalidOperationException("no result in " + pos);
}
try
{
luaEnv.translator.Get(luaEnv.L, _oldTop + 2 + pos, out ret);
}
catch (Exception e)
{
InvokeSessionEnd();
throw e;
}
}
#endif
}
}

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: b8c4165852e3e92468656dc6efb30a28
timeCreated: 1452574309
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,5 @@
fileFormatVersion: 2
guid: 1e53aa922da0a00469e5760902833e71
folderAsset: yes
DefaultImporter:
userData:

File diff suppressed because it is too large Load Diff

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e866a5f1000c29940843aece98d0c706
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

File diff suppressed because it is too large Load Diff

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: f9f175d9e85601f4da903e391b8b7c77
timeCreated: 1482299911
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 9f94464b9267f9b4cbf2f98681e22880
folderAsset: yes
timeCreated: 1479105499
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,34 @@
using UnityEngine;
using System.Collections.Generic;
using XLua;
using System.IO;
using System.Text;
using System.Linq;
using CSObjectWrapEditor;
public class LinkXmlGen : ScriptableObject
{
public TextAsset Template;
public static IEnumerable<CustomGenTask> GetTasks(LuaEnv lua_env, UserConfig user_cfg)
{
LuaTable data = lua_env.NewTable();
var assembly_infos = (from type in (user_cfg.ReflectionUse.Concat(user_cfg.LuaCallCSharp))
group type by type.Assembly.GetName().Name into assembly_info
select new { FullName = assembly_info.Key, Types = assembly_info.ToList()}).ToList();
data.Set("assembly_infos", assembly_infos);
yield return new CustomGenTask
{
Data = data,
Output = new StreamWriter(GeneratorConfig.common_path + "/link.xml",
false, Encoding.UTF8)
};
}
[GenCodeMenu]//加到Generate Code菜单里头
public static void GenLinkXml()
{
Generator.CustomGen(ScriptableObject.CreateInstance<LinkXmlGen>().Template.text, GetTasks);
}
}

@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 5fa8c6bd6daed854c98654418f48a830
timeCreated: 1482482561
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences:
- Template: {fileID: 4900000, guid: 384feb229d259f549bbbac9e910b782b, type: 3}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,13 @@
<%
require "TemplateCommon"
%>
<linker>
<%ForEachCsList(assembly_infos, function(assembly_info)%>
<assembly fullname="<%=assembly_info.FullName%>">
<%ForEachCsList(assembly_info.Types, function(type)
%><type fullname="<%=type:ToString()%>" preserve="all"/>
<%end)%>
</assembly>
<%end)%>
</linker>

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 384feb229d259f549bbbac9e910b782b
timeCreated: 1481621844
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,57 @@
#if UNITY_5_6_OR_NEWER
namespace XLua
{
using UnityEngine;
using UnityEditor;
using System.Net.Sockets;
using System.Text;
using System.Threading;
[InitializeOnLoad]
public class Report
{
private const string PREFS_KEY = "XLuaReport";
private const string DIALOG_MSG_FORMAT = @"<22><><EFBFBD>Ƿdz<C7B7>ע<EFBFBD><D7A2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>˽Ȩ<CBBD><C8A8><EFBFBD><EFBFBD>Ҫ<EFBFBD>ռ<EFBFBD><D5BC><EFBFBD><EFBFBD>±<EFBFBD>Ҫ<EFBFBD><D2AA>Ϣ<EFBFBD><CFA2><EFBFBD><EFBFBD><E1B9A9><EFBFBD>õķ<C3B5><C4B7><EFBFBD><EFBFBD><EFBFBD>
XLua<EFBFBD><EFBFBD><EFBFBD>{0}
<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>{1}
<EFBFBD><EFBFBD><EFBFBD>ʶ<EFBFBD><EFBFBD>{2}
We attach great importance to your privacy and need to collect the following necessary information to provide better services:
XLua Version: {0}
Unity Version: {1}
Device Identifier: {2}";
static Report()
{
if (EditorPrefs.HasKey(PREFS_KEY) && !EditorPrefs.GetBool(PREFS_KEY))
return;
var version = "2.1.16";
var engine = Application.unityVersion;
var machine = SystemInfo.deviceUniqueIdentifier;
var msg = string.Format("cmd=0&tag=glcoud.xlua.report&version={0}&engine={1}&machine_name={2}", version, engine, machine);
if (!EditorPrefs.HasKey(PREFS_KEY))
{
var dialogMsg = string.Format(DIALOG_MSG_FORMAT, version, engine, machine);
var result = EditorUtility.DisplayDialog(string.Empty, dialogMsg, "<22><><EFBFBD><EFBFBD> Allow", "<22>ܾ<EFBFBD> Deny");
EditorPrefs.SetBool(PREFS_KEY, result);
if (!result)
return;
}
new Thread(() =>
{
var data = Encoding.UTF8.GetBytes(msg);
var client = new UdpClient();
client.Send(data, data.Length, "101.226.141.148", 8080);
client.Close();
}).Start();
}
}
}
#endif

@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1a3eea7e2e9e8e94ca50f9b792bc9416
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,5 @@
fileFormatVersion: 2
guid: 9c7307955fb71fc4090eb2a906a78a0a
folderAsset: yes
DefaultImporter:
userData:

@ -0,0 +1,589 @@
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
<%ForEachCsList(namespaces, function(namespace)%>using <%=namespace%>;<%end)%>
<%
require "TemplateCommon"
local OpNameMap = {
op_Addition = "__AddMeta",
op_Subtraction = "__SubMeta",
op_Multiply = "__MulMeta",
op_Division = "__DivMeta",
op_Equality = "__EqMeta",
op_UnaryNegation = "__UnmMeta",
op_LessThan = "__LTMeta",
op_LessThanOrEqual = "__LEMeta",
op_Modulus = "__ModMeta",
op_BitwiseAnd = "__BandMeta",
op_BitwiseOr = "__BorMeta",
op_ExclusiveOr = "__BxorMeta",
op_OnesComplement = "__BnotMeta",
op_LeftShift = "__ShlMeta",
op_RightShift = "__ShrMeta",
}
local OpCallNameMap = {
op_Addition = "+",
op_Subtraction = "-",
op_Multiply = "*",
op_Division = "/",
op_Equality = "==",
op_UnaryNegation = "-",
op_LessThan = "<",
op_LessThanOrEqual = "<=",
op_Modulus = "%",
op_BitwiseAnd = "&",
op_BitwiseOr = "|",
op_ExclusiveOr = "^",
op_OnesComplement = "~",
op_LeftShift = "<<",
op_RightShift = ">>",
}
local obj_method_count = 0
local obj_getter_count = 0
local obj_setter_count = 0
local meta_func_count = operators.Count
local cls_field_count = 1
local cls_getter_count = 0
local cls_setter_count = 0
ForEachCsList(methods, function(method)
if method.IsStatic then
cls_field_count = cls_field_count + 1
else
obj_method_count = obj_method_count + 1
end
end)
ForEachCsList(events, function(event)
if event.IsStatic then
cls_field_count = cls_field_count + 1
else
obj_method_count = obj_method_count + 1
end
end)
ForEachCsList(getters, function(getter)
if getter.IsStatic then
if getter.ReadOnly then
cls_field_count = cls_field_count + 1
else
cls_getter_count = cls_getter_count + 1
end
else
obj_getter_count = obj_getter_count + 1
end
end)
ForEachCsList(setters, function(setter)
if setter.IsStatic then
cls_setter_count = cls_setter_count + 1
else
obj_setter_count = obj_setter_count + 1
end
end)
ForEachCsList(lazymembers, function(lazymember)
if lazymember.IsStatic == 'true' then
if 'CLS_IDX' == lazymember.Index then
cls_field_count = cls_field_count + 1
elseif 'CLS_GETTER_IDX' == lazymember.Index then
cls_getter_count = cls_getter_count + 1
elseif 'CLS_SETTER_IDX' == lazymember.Index then
cls_setter_count = cls_setter_count + 1
end
else
if 'METHOD_IDX' == lazymember.Index then
obj_method_count = obj_method_count + 1
elseif 'GETTER_IDX' == lazymember.Index then
obj_getter_count = obj_getter_count + 1
elseif 'SETTER_IDX' == lazymember.Index then
obj_setter_count = obj_setter_count + 1
end
end
end)
local generic_arg_list, type_constraints = GenericArgumentList(type)
%>
namespace XLua.CSObjectWrap
{
using Utils = XLua.Utils;
public class <%=CSVariableName(type)%>Wrap<%=generic_arg_list%> <%=type_constraints%>
{
public static void __Register(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
System.Type type = typeof(<%=CsFullTypeName(type)%>);
Utils.BeginObjectRegister(type, L, translator, <%=meta_func_count%>, <%=obj_method_count%>, <%=obj_getter_count%>, <%=obj_setter_count%>);
<%ForEachCsList(operators, function(operator)%>Utils.RegisterFunc(L, Utils.OBJ_META_IDX, "<%=(OpNameMap[operator.Name]):gsub('Meta', ''):lower()%>", <%=OpNameMap[operator.Name]%>);
<%end)%>
<%ForEachCsList(methods, function(method) if not method.IsStatic then %>Utils.RegisterFunc(L, Utils.METHOD_IDX, "<%=method.Name%>", _m_<%=method.Name%>);
<% end end)%>
<%ForEachCsList(events, function(event) if not event.IsStatic then %>Utils.RegisterFunc(L, Utils.METHOD_IDX, "<%=event.Name%>", _e_<%=event.Name%>);
<% end end)%>
<%ForEachCsList(getters, function(getter) if not getter.IsStatic then %>Utils.RegisterFunc(L, Utils.GETTER_IDX, "<%=getter.Name%>", _g_get_<%=getter.Name%>);
<%end end)%>
<%ForEachCsList(setters, function(setter) if not setter.IsStatic then %>Utils.RegisterFunc(L, Utils.SETTER_IDX, "<%=setter.Name%>", _s_set_<%=setter.Name%>);
<%end end)%>
<%ForEachCsList(lazymembers, function(lazymember) if lazymember.IsStatic == 'false' then %>Utils.RegisterLazyFunc(L, Utils.<%=lazymember.Index%>, "<%=lazymember.Name%>", type, <%=lazymember.MemberType%>, <%=lazymember.IsStatic%>);
<%end end)%>
Utils.EndObjectRegister(type, L, translator, <% if type.IsArray or ((indexers.Count or 0) > 0) then %>__CSIndexer<%else%>null<%end%>, <%if type.IsArray or ((newindexers.Count or 0) > 0) then%>__NewIndexer<%else%>null<%end%>,
null, null, null);
Utils.BeginClassRegister(type, L, __CreateInstance, <%=cls_field_count%>, <%=cls_getter_count%>, <%=cls_setter_count%>);
<%ForEachCsList(methods, function(method) if method.IsStatic then %>Utils.RegisterFunc(L, Utils.CLS_IDX, "<%=method.Overloads[0].Name%>", _m_<%=method.Name%>);
<% end end)%>
<%ForEachCsList(events, function(event) if event.IsStatic then %>Utils.RegisterFunc(L, Utils.CLS_IDX, "<%=event.Name%>", _e_<%=event.Name%>);
<% end end)%>
<%ForEachCsList(getters, function(getter) if getter.IsStatic and getter.ReadOnly then %>Utils.RegisterObject(L, translator, Utils.CLS_IDX, "<%=getter.Name%>", <%=CsFullTypeName(type).."."..getter.Name%>);
<%end end)%>
<%ForEachCsList(getters, function(getter) if getter.IsStatic and (not getter.ReadOnly) then %>Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "<%=getter.Name%>", _g_get_<%=getter.Name%>);
<%end end)%>
<%ForEachCsList(setters, function(setter) if setter.IsStatic then %>Utils.RegisterFunc(L, Utils.CLS_SETTER_IDX, "<%=setter.Name%>", _s_set_<%=setter.Name%>);
<%end end)%>
<%ForEachCsList(lazymembers, function(lazymember) if lazymember.IsStatic == 'true' then %>Utils.RegisterLazyFunc(L, Utils.<%=lazymember.Index%>, "<%=lazymember.Name%>", type, <%=lazymember.MemberType%>, <%=lazymember.IsStatic%>);
<%end end)%>
Utils.EndClassRegister(type, L, translator);
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __CreateInstance(RealStatePtr L)
{
<%
if constructors.Count == 0 and (not type.IsValueType) then
%>return LuaAPI.luaL_error(L, "<%=CsFullTypeName(type)%> does not have a constructor!");<%
else %>
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
<%
local hasZeroParamsCtor = false
ForEachCsList(constructors, function(constructor, ci)
local parameters = constructor:GetParameters()
if parameters.Length == 0 then
hasZeroParamsCtor = true
end
local def_count = constructor_def_vals[ci]
local param_count = parameters.Length
local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end)
local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end)
local real_param_count = param_count - def_count
local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1])
local in_pos = 0
%>if(LuaAPI.lua_gettop(L) <%=has_v_params and ">=" or "=="%> <%=in_num + 1 - def_count - (has_v_params and 1 or 0)%><%ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
local parameterType = parameter.ParameterType
if has_v_params and pi == param_count - 1 then parameterType = parameterType:GetElementType() end
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then in_pos = in_pos + 1
%> && <%=GetCheckStatement(parameterType, in_pos+1, has_v_params and pi == param_count - 1)%><%
end
end)%>)
{
<%ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
%><%=GetCasterStatement(parameter.ParameterType, pi+2, LocalName(parameter.Name), true, has_v_params and pi == param_count - 1)%>;
<%end)%>
var gen_ret = new <%=CsFullTypeName(type)%>(<%ForEachCsList(parameters, function(parameter, pi) if pi >= real_param_count then return end; if pi ~=0 then %><%=', '%><% end ;if parameter.IsOut and parameter.ParameterType.IsByRef then %>out <% elseif parameter.ParameterType.IsByRef and not parameter.IsIn then %>ref <% end %><%=LocalName(parameter.Name)%><% end)%>);
<%=GetPushStatement(type, "gen_ret")%>;
<%local in_pos = 0
ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
in_pos = in_pos + 1
end
if parameter.ParameterType.IsByRef then
%><%=GetPushStatement(parameter.ParameterType:GetElementType(), LocalName(parameter.Name))%>;
<%if not parameter.IsOut and parameter.ParameterType.IsByRef and NeedUpdate(parameter.ParameterType) then
%><%=GetUpdateStatement(parameter.ParameterType:GetElementType(), in_pos+1, LocalName(parameter.Name))%>;
<%end%>
<%
end
end)
%>
return <%=out_num + 1%>;
}
<%end)
if (not hasZeroParamsCtor) and type.IsValueType then
%>
if (LuaAPI.lua_gettop(L) == 1)
{
<%=GetPushStatement(type, "default(" .. CsFullTypeName(type).. ")")%>;
return 1;
}
<%end%>
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%> constructor!");
<% end %>
}
<% if type.IsArray or ((indexers.Count or 0) > 0) then %>
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
public static int __CSIndexer(RealStatePtr L)
{
<%if type.IsArray then %>
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
if (<%=GetCheckStatement(type, 1)%> && LuaAPI.lua_isnumber(L, 2))
{
int index = (int)LuaAPI.lua_tonumber(L, 2);
<%=GetSelfStatement(type)%>;
LuaAPI.lua_pushboolean(L, true);
<%=GetPushStatement(type:GetElementType(), "gen_to_be_invoked[index]")%>;
return 2;
}
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
<%elseif indexers.Count > 0 then
%>try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
<%
ForEachCsList(indexers, function(indexer)
local paramter = indexer:GetParameters()[0]
%>
if (<%=GetCheckStatement(type, 1)%> && <%=GetCheckStatement(paramter.ParameterType, 2)%>)
{
<%=GetSelfStatement(type)%>;
<%=GetCasterStatement(paramter.ParameterType, 2, "index", true)%>;
LuaAPI.lua_pushboolean(L, true);
<%=GetPushStatement(indexer.ReturnType, "gen_to_be_invoked[index]")%>;
return 2;
}
<%end)%>
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
<%end%>
LuaAPI.lua_pushboolean(L, false);
return 1;
}
<% end %>
<%if type.IsArray or ((newindexers.Count or 0) > 0) then%>
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
public static int __NewIndexer(RealStatePtr L)
{
<%if type.IsArray or newindexers.Count > 0 then %>ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);<%end%>
<%if type.IsArray then
local elementType = type:GetElementType()
%>
try {
if (<%=GetCheckStatement(type, 1)%> && LuaAPI.lua_isnumber(L, 2) && <%=GetCheckStatement(elementType, 3)%>)
{
int index = (int)LuaAPI.lua_tonumber(L, 2);
<%=GetSelfStatement(type)%>;
<%=GetCasterStatement(elementType, 3, "gen_to_be_invoked[index]")%>;
LuaAPI.lua_pushboolean(L, true);
return 1;
}
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
<%elseif newindexers.Count > 0 then%>
try {
<%ForEachCsList(newindexers, function(newindexer)
local keyType = newindexer:GetParameters()[0].ParameterType
local valueType = newindexer:GetParameters()[1].ParameterType
%>
if (<%=GetCheckStatement(type, 1)%> && <%=GetCheckStatement(keyType, 2)%> && <%=GetCheckStatement(valueType, 3)%>)
{
<%=GetSelfStatement(type)%>;
<%=GetCasterStatement(keyType, 2, "key", true)%>;
<%if IsStruct(valueType) then%><%=GetCasterStatement(valueType, 3, "gen_value", true)%>;
gen_to_be_invoked[key] = gen_value;<%else
%><%=GetCasterStatement(valueType, 3, "gen_to_be_invoked[key]")%>;<%end%>
LuaAPI.lua_pushboolean(L, true);
return 1;
}
<%end)%>
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
<%end%>
LuaAPI.lua_pushboolean(L, false);
return 1;
}
<% end %>
<%ForEachCsList(operators, function(operator) %>
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int <%=OpNameMap[operator.Name]%>(RealStatePtr L)
{
<% if operator.Name ~= "op_UnaryNegation" and operator.Name ~= "op_OnesComplement" then %>
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
<%ForEachCsList(operator.Overloads, function(overload)
local left_param = overload:GetParameters()[0]
local right_param = overload:GetParameters()[1]
%>
if (<%=GetCheckStatement(left_param.ParameterType, 1)%> && <%=GetCheckStatement(right_param.ParameterType, 2)%>)
{
<%=GetCasterStatement(left_param.ParameterType, 1, "leftside", true)%>;
<%=GetCasterStatement(right_param.ParameterType, 2, "rightside", true)%>;
<%=GetPushStatement(overload.ReturnType, "leftside " .. OpCallNameMap[operator.Name] .. " rightside")%>;
return 1;
}
<%end)%>
}
catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return LuaAPI.luaL_error(L, "invalid arguments to right hand of <%=OpCallNameMap[operator.Name]%> operator, need <%=CsFullTypeName(type)%>!");
<%else%>
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
try {
<%=GetCasterStatement(type, 1, "rightside", true)%>;
<%=GetPushStatement(operator.Overloads[0].ReturnType, OpCallNameMap[operator.Name] .. " rightside")%>;
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
<%end%>
}
<%end)%>
<%ForEachCsList(methods, function(method)%>
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _m_<%=method.Name%>(RealStatePtr L)
{
try {
<%
local need_obj = not method.IsStatic
if MethodCallNeedTranslator(method) then
%>
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
<%end%>
<%if need_obj then%>
<%=GetSelfStatement(type)%>;
<%end%>
<%if method.Overloads.Count > 1 then%>
int gen_param_count = LuaAPI.lua_gettop(L);
<%end%>
<%ForEachCsList(method.Overloads, function(overload, oi)
local parameters = MethodParameters(overload)
local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end)
local param_offset = method.IsStatic and 0 or 1
local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end)
local in_pos = 0
local has_return = (overload.ReturnType.FullName ~= "System.Void")
local def_count = method.DefaultValues[oi]
local param_count = parameters.Length
local real_param_count = param_count - def_count
local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1])
if method.Overloads.Count > 1 then
%>if(gen_param_count <%=has_v_params and ">=" or "=="%> <%=in_num+param_offset-def_count - (has_v_params and 1 or 0)%><%
ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
local parameterType = parameter.ParameterType
if has_v_params and pi == param_count - 1 then parameterType = parameterType:GetElementType() end
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then in_pos = in_pos + 1;
%>&& <%=GetCheckStatement(parameterType , in_pos+param_offset, has_v_params and pi == param_count - 1)%><%
end
end)%>) <%end%>
{
<%if overload.Name == "get_Item" and overload.IsSpecialName then
local keyType = overload:GetParameters()[0].ParameterType%>
<%=GetCasterStatement(keyType, 2, "key", true)%>;
<%=GetPushStatement(overload.ReturnType, "gen_to_be_invoked[key]")%>;
<%elseif overload.Name == "set_Item" and overload.IsSpecialName then
local keyType = overload:GetParameters()[0].ParameterType
local valueType = overload:GetParameters()[1].ParameterType%>
<%=GetCasterStatement(keyType, 2, "key", true)%>;
<%=GetCasterStatement(valueType, 3, "gen_value", true)%>;
gen_to_be_invoked[key] = gen_value;
<% else
in_pos = 0;
ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
%><%if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
in_pos = in_pos + 1
%><%=GetCasterStatement(parameter.ParameterType, in_pos+param_offset, LocalName(parameter.Name), true, has_v_params and pi == param_count - 1)%><%
else%><%=CsFullTypeName(parameter.ParameterType)%> <%=LocalName(parameter.Name)%><%end%>;
<%end)%>
<%
if has_return then
%> var gen_ret = <%
end
%><%if method.IsStatic then
%><%=CsFullTypeName(type).."."..UnK(overload.Name)%><%
else
%>gen_to_be_invoked.<%=UnK(overload.Name)%><%
end%>( <%ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
if pi ~= 0 then %>, <% end; if parameter.IsOut and parameter.ParameterType.IsByRef then %>out <% elseif parameter.ParameterType.IsByRef and not parameter.IsIn then %>ref <% end %><%=LocalName(parameter.Name)%><% end) %> );
<%
if has_return then
%> <%=GetPushStatement(overload.ReturnType, "gen_ret")%>;
<%
end
local in_pos = 0
ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
in_pos = in_pos + 1
end
if parameter.ParameterType.IsByRef then
%><%=GetPushStatement(parameter.ParameterType:GetElementType(), LocalName(parameter.Name))%>;
<%if not parameter.IsOut and parameter.ParameterType.IsByRef and NeedUpdate(parameter.ParameterType) then
%><%=GetUpdateStatement(parameter.ParameterType:GetElementType(), in_pos+param_offset, LocalName(parameter.Name))%>;
<%end%>
<%
end
end)
end
%>
<%if NeedUpdate(type) and not method.IsStatic then%>
<%=GetUpdateStatement(type, 1, "gen_to_be_invoked")%>;
<%end%>
return <%=out_num+(has_return and 1 or 0)%>;
}
<% end)%>
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
<%if method.Overloads.Count > 1 then%>
return LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%>.<%=method.Overloads[0].Name%>!");
<%end%>
}
<% end)%>
<%ForEachCsList(getters, function(getter)
if getter.IsStatic and getter.ReadOnly then return end --readonly static
%>
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _g_get_<%=getter.Name%>(RealStatePtr L)
{
try {
<%if AccessorNeedTranslator(getter) then %> ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);<%end%>
<%if not getter.IsStatic then%>
<%=GetSelfStatement(type)%>;
<%=GetPushStatement(getter.Type, "gen_to_be_invoked."..UnK(getter.Name))%>;<% else %> <%=GetPushStatement(getter.Type, CsFullTypeName(type).."."..UnK(getter.Name))%>;<% end%>
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 1;
}
<%end)%>
<%ForEachCsList(setters, function(setter)
local is_struct = IsStruct(setter.Type)
%>
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _s_set_<%=setter.Name%>(RealStatePtr L)
{
try {
<%if AccessorNeedTranslator(setter) then %>ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);<%end%>
<%if not setter.IsStatic then %>
<%=GetSelfStatement(type)%>;
<%if is_struct then %><%=GetCasterStatement(setter.Type, 2, "gen_value", true)%>;
gen_to_be_invoked.<%=UnK(setter.Name)%> = gen_value;<% else
%><%=GetCasterStatement(setter.Type, 2, "gen_to_be_invoked." .. UnK(setter.Name))%>;<%end
else
if is_struct then %><%=GetCasterStatement(setter.Type, 1, "gen_value", true)%>;
<%=CsFullTypeName(type)%>.<%=UnK(setter.Name)%> = gen_value;<%else
%> <%=GetCasterStatement(setter.Type, 1, CsFullTypeName(type) .."." .. UnK(setter.Name))%>;<%end
end%>
<%if NeedUpdate(type) and not setter.IsStatic then%>
<%=GetUpdateStatement(type, 1, "gen_to_be_invoked")%>;
<%end%>
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return 0;
}
<%end)%>
<%ForEachCsList(events, function(event) if not event.IsStatic then %>
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _e_<%=event.Name%>(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
int gen_param_count = LuaAPI.lua_gettop(L);
<%=GetSelfStatement(type)%>;
<%=GetCasterStatement(event.Type, 3, "gen_delegate", true)%>;
if (gen_delegate == null) {
return LuaAPI.luaL_error(L, "#3 need <%=CsFullTypeName(event.Type)%>!");
}
if (gen_param_count == 3)
{
<%if event.CanAdd then%>
if (LuaAPI.xlua_is_eq_str(L, 2, "+")) {
gen_to_be_invoked.<%=UnK(event.Name)%> += gen_delegate;
return 0;
}
<%end%>
<%if event.CanRemove then%>
if (LuaAPI.xlua_is_eq_str(L, 2, "-")) {
gen_to_be_invoked.<%=UnK(event.Name)%> -= gen_delegate;
return 0;
}
<%end%>
}
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%>.<%=event.Name%>!");
return 0;
}
<%end end)%>
<%ForEachCsList(events, function(event) if event.IsStatic then %>
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int _e_<%=event.Name%>(RealStatePtr L)
{
try {
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
int gen_param_count = LuaAPI.lua_gettop(L);
<%=GetCasterStatement(event.Type, 2, "gen_delegate", true)%>;
if (gen_delegate == null) {
return LuaAPI.luaL_error(L, "#2 need <%=CsFullTypeName(event.Type)%>!");
}
<%if event.CanAdd then%>
if (gen_param_count == 2 && LuaAPI.xlua_is_eq_str(L, 1, "+")) {
<%=CsFullTypeName(type)%>.<%=UnK(event.Name)%> += gen_delegate;
return 0;
}
<%end%>
<%if event.CanRemove then%>
if (gen_param_count == 2 && LuaAPI.xlua_is_eq_str(L, 1, "-")) {
<%=CsFullTypeName(type)%>.<%=UnK(event.Name)%> -= gen_delegate;
return 0;
}
<%end%>
} catch(System.Exception gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + gen_e);
}
return LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%>.<%=event.Name%>!");
}
<%end end)%>
}
}

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 8503038eabbabe44dac0f5f749d4411a
timeCreated: 1481620508
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,517 @@
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
<%ForEachCsList(namespaces, function(namespace)%>using <%=namespace%>;<%end)%>
<%
require "TemplateCommon"
local OpNameMap = {
op_Addition = "__AddMeta",
op_Subtraction = "__SubMeta",
op_Multiply = "__MulMeta",
op_Division = "__DivMeta",
op_Equality = "__EqMeta",
op_UnaryNegation = "__UnmMeta",
op_LessThan = "__LTMeta",
op_LessThanOrEqual = "__LEMeta",
op_Modulus = "__ModMeta",
op_BitwiseAnd = "__BandMeta",
op_BitwiseOr = "__BorMeta",
op_ExclusiveOr = "__BxorMeta",
op_OnesComplement = "__BnotMeta",
op_LeftShift = "__ShlMeta",
op_RightShift = "__ShrMeta",
}
local OpCallNameMap = {
op_Addition = "+",
op_Subtraction = "-",
op_Multiply = "*",
op_Division = "/",
op_Equality = "==",
op_UnaryNegation = "-",
op_LessThan = "<",
op_LessThanOrEqual = "<=",
op_Modulus = "%",
op_BitwiseAnd = "&",
op_BitwiseOr = "|",
op_ExclusiveOr = "^",
op_OnesComplement = "~",
op_LeftShift = "<<",
op_RightShift = ">>",
}
local obj_method_count = 0
local obj_getter_count = 0
local obj_setter_count = 0
local meta_func_count = operators.Count
local cls_field_count = 1
local cls_getter_count = 0
local cls_setter_count = 0
ForEachCsList(methods, function(method)
if method.IsStatic then
cls_field_count = cls_field_count + 1
else
obj_method_count = obj_method_count + 1
end
end)
ForEachCsList(events, function(event)
if event.IsStatic then
cls_field_count = cls_field_count + 1
else
obj_method_count = obj_method_count + 1
end
end)
ForEachCsList(getters, function(getter)
if getter.IsStatic then
if getter.ReadOnly then
cls_field_count = cls_field_count + 1
else
cls_getter_count = cls_getter_count + 1
end
else
obj_getter_count = obj_getter_count + 1
end
end)
ForEachCsList(setters, function(setter)
if setter.IsStatic then
cls_setter_count = cls_setter_count + 1
else
obj_setter_count = obj_setter_count + 1
end
end)
ForEachCsList(lazymembers, function(lazymember)
if lazymember.IsStatic == 'true' then
if 'CLS_IDX' == lazymember.Index then
cls_field_count = cls_field_count + 1
elseif 'CLS_GETTER_IDX' == lazymember.Index then
cls_getter_count = cls_getter_count + 1
elseif 'CLS_SETTER_IDX' == lazymember.Index then
cls_setter_count = cls_setter_count + 1
end
else
if 'METHOD_IDX' == lazymember.Index then
obj_method_count = obj_method_count + 1
elseif 'GETTER_IDX' == lazymember.Index then
obj_getter_count = obj_getter_count + 1
elseif 'SETTER_IDX' == lazymember.Index then
obj_setter_count = obj_setter_count + 1
end
end
end)
local v_type_name = CSVariableName(type)
local generic_arg_list, type_constraints = GenericArgumentList(type)
%>
namespace XLua
{
public partial class ObjectTranslator
{
public void __Register<%=v_type_name%><%=generic_arg_list%>(RealStatePtr L) <%=type_constraints%>
{
System.Type type = typeof(<%=CsFullTypeName(type)%>);
Utils.BeginObjectRegister(type, L, this, <%=meta_func_count%>, <%=obj_method_count%>, <%=obj_getter_count%>, <%=obj_setter_count%>);
<%ForEachCsList(operators, function(operator)%>Utils.RegisterFunc(L, Utils.OBJ_META_IDX, "<%=(OpNameMap[operator.Name]):gsub('Meta', ''):lower()%>", <%=v_type_name%><%=OpNameMap[operator.Name]%><%=generic_arg_list%>);
<%end)%>
<%ForEachCsList(methods, function(method) if not method.IsStatic then %>Utils.RegisterFunc(L, Utils.METHOD_IDX, "<%=method.Name%>", <%=v_type_name%>_m_<%=method.Name%><%=generic_arg_list%>);
<% end end)%>
<%ForEachCsList(events, function(event) if not event.IsStatic then %>Utils.RegisterFunc(L, Utils.METHOD_IDX, "<%=event.Name%>", <%=v_type_name%>_e_<%=event.Name%><%=generic_arg_list%>);
<% end end)%>
<%ForEachCsList(getters, function(getter) if not getter.IsStatic then %>Utils.RegisterFunc(L, Utils.GETTER_IDX, "<%=getter.Name%>", <%=v_type_name%>_g_get_<%=getter.Name%><%=generic_arg_list%>);
<%end end)%>
<%ForEachCsList(setters, function(setter) if not setter.IsStatic then %>Utils.RegisterFunc(L, Utils.SETTER_IDX, "<%=setter.Name%>", <%=v_type_name%>_s_set_<%=setter.Name%><%=generic_arg_list%>);
<%end end)%>
<%ForEachCsList(lazymembers, function(lazymember) if lazymember.IsStatic == 'false' then %>Utils.RegisterLazyFunc(L, Utils.<%=lazymember.Index%>, "<%=lazymember.Name%>", type, <%=lazymember.MemberType%>, <%=lazymember.IsStatic%>);
<%end end)%>
Utils.EndObjectRegister(type, L, this, <% if type.IsArray or ((indexers.Count or 0) > 0) then %>__CSIndexer<%=v_type_name%><%=generic_arg_list%><%else%>null<%end%>, <%if type.IsArray or ((newindexers.Count or 0) > 0) then%>__NewIndexer<%=v_type_name%><%=generic_arg_list%><%else%>null<%end%>,
null, null, null);
Utils.BeginClassRegister(type, L, __CreateInstance<%=v_type_name%><%=generic_arg_list%>, <%=cls_field_count%>, <%=cls_getter_count%>, <%=cls_setter_count%>);
<%ForEachCsList(methods, function(method) if method.IsStatic then %>Utils.RegisterFunc(L, Utils.CLS_IDX, "<%=method.Overloads[0].Name%>", <%=v_type_name%>_m_<%=method.Name%><%=generic_arg_list%>);
<% end end)%>
<%ForEachCsList(events, function(event) if event.IsStatic then %>Utils.RegisterFunc(L, Utils.CLS_IDX, "<%=event.Name%>", <%=v_type_name%>_e_<%=event.Name%><%=generic_arg_list%>);
<% end end)%>
<%ForEachCsList(getters, function(getter) if getter.IsStatic and getter.ReadOnly then %>Utils.RegisterObject(L, this, Utils.CLS_IDX, "<%=getter.Name%>", <%=CsFullTypeName(type).."."..getter.Name%>);
<%end end)%>
<%ForEachCsList(getters, function(getter) if getter.IsStatic and (not getter.ReadOnly) then %>Utils.RegisterFunc(L, Utils.CLS_GETTER_IDX, "<%=getter.Name%>", <%=v_type_name%>_g_get_<%=getter.Name%><%=generic_arg_list%>);
<%end end)%>
<%ForEachCsList(setters, function(setter) if setter.IsStatic then %>Utils.RegisterFunc(L, Utils.CLS_SETTER_IDX, "<%=setter.Name%>", <%=v_type_name%>_s_set_<%=setter.Name%><%=generic_arg_list%>);
<%end end)%>
<%ForEachCsList(lazymembers, function(lazymember) if lazymember.IsStatic == 'true' then %>Utils.RegisterLazyFunc(L, Utils.<%=lazymember.Index%>, "<%=lazymember.Name%>", type, <%=lazymember.MemberType%>, <%=lazymember.IsStatic%>);
<%end end)%>
Utils.EndClassRegister(type, L, this);
}
int __CreateInstance<%=v_type_name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%>
{
<%
if constructors.Count == 0 and (not type.IsValueType) then
%>return LuaAPI.luaL_error(L, "<%=CsFullTypeName(type)%> does not have a constructor!");<%
else %>
ObjectTranslator translator = this;
<%
local hasZeroParamsCtor = false
ForEachCsList(constructors, function(constructor, ci)
local parameters = constructor:GetParameters()
if parameters.Length == 0 then
hasZeroParamsCtor = true
end
local def_count = constructor_def_vals[ci]
local param_count = parameters.Length
local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end)
local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end)
local real_param_count = param_count - def_count
local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1])
local in_pos = 0
%>if(gen_param_count <%=has_v_params and ">=" or "=="%> <%=in_num + 1 - def_count - (has_v_params and 1 or 0)%><%ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
local parameterType = parameter.ParameterType
if has_v_params and pi == param_count - 1 then parameterType = parameterType:GetElementType() end
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then in_pos = in_pos + 1
%> && <%=GetCheckStatement(parameterType, in_pos+1, has_v_params and pi == param_count - 1)%><%
end
end)%>)
{
<%ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
%><%=GetCasterStatement(parameter.ParameterType, pi+2, LocalName(parameter.Name), true, has_v_params and pi == param_count - 1)%>;
<%end)%>
var gen_ret = new <%=CsFullTypeName(type)%>(<%ForEachCsList(parameters, function(parameter, pi) if pi >= real_param_count then return end; if pi ~=0 then %><%=', '%><% end ;if parameter.IsOut and parameter.ParameterType.IsByRef then %>out <% elseif parameter.ParameterType.IsByRef and not parameter.IsIn then %>ref <% end %><%=LocalName(parameter.Name)%><% end)%>);
<%=GetPushStatement(type, "gen_ret")%>;
<%local in_pos = 0
ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
in_pos = in_pos + 1
end
if parameter.ParameterType.IsByRef then
%><%=GetPushStatement(parameter.ParameterType:GetElementType(), LocalName(parameter.Name))%>;
<%if not parameter.IsOut and parameter.ParameterType.IsByRef and NeedUpdate(parameter.ParameterType) then
%><%=GetUpdateStatement(parameter.ParameterType:GetElementType(), in_pos+1, LocalName(parameter.Name))%>;
<%end%>
<%
end
end)
%>
return <%=out_num + 1%>;
}
<%end)
if (not hasZeroParamsCtor) and type.IsValueType then
%>
if (gen_param_count == 1)
{
<%=GetPushStatement(type, "default(" .. CsFullTypeName(type).. ")")%>;
return 1;
}
<%end%>
return LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%> constructor!");
<% end %>
}
<% if type.IsArray or ((indexers.Count or 0) > 0) then %>
int __CSIndexer<%=v_type_name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%>
{
<%if type.IsArray then %>
ObjectTranslator translator = this;
if (<%=GetCheckStatement(type, 1)%> && LuaAPI.lua_isnumber(L, 2))
{
int index = (int)LuaAPI.lua_tonumber(L, 2);
<%=GetSelfStatement(type)%>;
LuaAPI.lua_pushboolean(L, true);
<%=GetPushStatement(type:GetElementType(), "gen_to_be_invoked[index]")%>;
return 2;
}
<%elseif indexers.Count > 0 then
%>ObjectTranslator translator = this;
<%
ForEachCsList(indexers, function(indexer)
local paramter = indexer:GetParameters()[0]
%>
if (<%=GetCheckStatement(type, 1)%> && <%=GetCheckStatement(paramter.ParameterType, 2)%>)
{
<%=GetSelfStatement(type)%>;
<%=GetCasterStatement(paramter.ParameterType, 2, "index", true)%>;
LuaAPI.lua_pushboolean(L, true);
<%=GetPushStatement(indexer.ReturnType, "gen_to_be_invoked[index]")%>;
return 2;
}
<%end)
end%>
LuaAPI.lua_pushboolean(L, false);
return 1;
}
<% end %>
<%if type.IsArray or ((newindexers.Count or 0) > 0) then%>
int __NewIndexer<%=v_type_name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%>
{
<%if type.IsArray or newindexers.Count > 0 then %>ObjectTranslator translator = this;<%end%>
<%if type.IsArray then
local elementType = type:GetElementType()
%>
if (<%=GetCheckStatement(type, 1)%> && LuaAPI.lua_isnumber(L, 2) && <%=GetCheckStatement(elementType, 3)%>)
{
int index = (int)LuaAPI.lua_tonumber(L, 2);
<%=GetSelfStatement(type)%>;
<%=GetCasterStatement(elementType, 3, "gen_to_be_invoked[index]")%>;
LuaAPI.lua_pushboolean(L, true);
return 1;
}
<%elseif newindexers.Count > 0 then%>
<%ForEachCsList(newindexers, function(newindexer)
local keyType = newindexer:GetParameters()[0].ParameterType
local valueType = newindexer:GetParameters()[1].ParameterType
%>
if (<%=GetCheckStatement(type, 1)%> && <%=GetCheckStatement(keyType, 2)%> && <%=GetCheckStatement(valueType, 3)%>)
{
<%=GetSelfStatement(type)%>;
<%=GetCasterStatement(keyType, 2, "key", true)%>;
<%if IsStruct(valueType) then%><%=GetCasterStatement(valueType, 3, "gen_value", true)%>;
gen_to_be_invoked[key] = gen_value;<%else
%><%=GetCasterStatement(valueType, 3, "gen_to_be_invoked[key]")%>;<%end%>
LuaAPI.lua_pushboolean(L, true);
return 1;
}
<%end)
end%>
LuaAPI.lua_pushboolean(L, false);
return 1;
}
<% end %>
<%ForEachCsList(operators, function(operator) %>
int <%=v_type_name%><%=OpNameMap[operator.Name]%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%>
{
ObjectTranslator translator = this;
<% if operator.Name ~= "op_UnaryNegation" and operator.Name ~= "op_OnesComplement" then
ForEachCsList(operator.Overloads, function(overload)
local left_param = overload:GetParameters()[0]
local right_param = overload:GetParameters()[1]
%>
if (<%=GetCheckStatement(left_param.ParameterType, 1)%> && <%=GetCheckStatement(right_param.ParameterType, 2)%>)
{
<%=GetCasterStatement(left_param.ParameterType, 1, "leftside", true)%>;
<%=GetCasterStatement(right_param.ParameterType, 2, "rightside", true)%>;
<%=GetPushStatement(overload.ReturnType, "leftside " .. OpCallNameMap[operator.Name] .. " rightside")%>;
return 1;
}
<%end)%>
return LuaAPI.luaL_error(L, "invalid arguments to right hand of <%=OpCallNameMap[operator.Name]%> operator, need <%=CsFullTypeName(type)%>!");
<%else%>
<%=GetCasterStatement(type, 1, "rightside", true)%>;
<%=GetPushStatement(operator.Overloads[0].ReturnType, OpCallNameMap[operator.Name] .. " rightside")%>;
return 1;
<%end%>
}
<%end)%>
<%ForEachCsList(methods, function(method)%>
int <%=v_type_name%>_m_<%=method.Name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%>
{
<%
local need_obj = not method.IsStatic
if MethodCallNeedTranslator(method) then
%>
ObjectTranslator translator = this;
<%end%>
<%if need_obj then%>
<%=GetSelfStatement(type)%>;
<%end%>
<%ForEachCsList(method.Overloads, function(overload, oi)
local parameters = MethodParameters(overload)
local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end)
local param_offset = method.IsStatic and 0 or 1
local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end)
local in_pos = 0
local has_return = (overload.ReturnType.FullName ~= "System.Void")
local def_count = method.DefaultValues[oi]
local param_count = parameters.Length
local real_param_count = param_count - def_count
local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1])
if method.Overloads.Count > 1 then
%>if(gen_param_count <%=has_v_params and ">=" or "=="%> <%=in_num+param_offset-def_count - (has_v_params and 1 or 0)%><%
ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
local parameterType = parameter.ParameterType
if has_v_params and pi == param_count - 1 then parameterType = parameterType:GetElementType() end
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then in_pos = in_pos + 1;
%>&& <%=GetCheckStatement(parameterType , in_pos+param_offset, has_v_params and pi == param_count - 1)%><%
end
end)%>) <%end%>
{
<%if overload.Name == "get_Item" and overload.IsSpecialName then
local keyType = overload:GetParameters()[0].ParameterType%>
<%=GetCasterStatement(keyType, 2, "key", true)%>;
<%=GetPushStatement(overload.ReturnType, "gen_to_be_invoked[key]")%>;
<%elseif overload.Name == "set_Item" and overload.IsSpecialName then
local keyType = overload:GetParameters()[0].ParameterType
local valueType = overload:GetParameters()[1].ParameterType%>
<%=GetCasterStatement(keyType, 2, "key", true)%>;
<%=GetCasterStatement(valueType, 3, "gen_to_be_invoked[key]")%>;
<% else
in_pos = 0;
ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
%><%if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
in_pos = in_pos + 1
%><%=GetCasterStatement(parameter.ParameterType, in_pos+param_offset, LocalName(parameter.Name), true, has_v_params and pi == param_count - 1)%><%
else%><%=CsFullTypeName(parameter.ParameterType)%> <%=LocalName(parameter.Name)%><%end%>;
<%end)%>
<%
if has_return then
%>var gen_ret = <%
end
%><%if method.IsStatic then
%><%=CsFullTypeName(type).."."..UnK(overload.Name)%><%
else
%>gen_to_be_invoked.<%=UnK(overload.Name)%><%
end%>( <%ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
if pi ~= 0 then %>, <% end; if parameter.IsOut and parameter.ParameterType.IsByRef then %>out <% elseif parameter.ParameterType.IsByRef and not parameter.IsIn then %>ref <% end %><%=LocalName(parameter.Name)%><% end) %> );
<%
if has_return then
%><%=GetPushStatement(overload.ReturnType, "gen_ret")%>;
<%
end
local in_pos = 0
ForEachCsList(parameters, function(parameter, pi)
if pi >= real_param_count then return end
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
in_pos = in_pos + 1
end
if parameter.ParameterType.IsByRef then
%><%=GetPushStatement(parameter.ParameterType:GetElementType(), LocalName(parameter.Name))%>;
<%if not parameter.IsOut and parameter.ParameterType.IsByRef and NeedUpdate(parameter.ParameterType) then
%><%=GetUpdateStatement(parameter.ParameterType:GetElementType(), in_pos+param_offset, LocalName(parameter.Name))%>;
<%end%>
<%
end
end)
end
%>
<%if NeedUpdate(type) and not method.IsStatic then%>
<%=GetUpdateStatement(type, 1, "gen_to_be_invoked")%>;
<%end%>
return <%=out_num+(has_return and 1 or 0)%>;
}
<% end)%>
<%if method.Overloads.Count > 1 then%>
return LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%>.<%=method.Overloads[0].Name%>!");
<%end%>
}
<% end)%>
<%ForEachCsList(getters, function(getter)
if getter.IsStatic and getter.ReadOnly then return end --readonly static
%>
int <%=v_type_name%>_g_get_<%=getter.Name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%>
{
<%if AccessorNeedTranslator(getter) then %>ObjectTranslator translator = this;<%end%>
<%if not getter.IsStatic then%>
<%=GetSelfStatement(type)%>;
<%=GetPushStatement(getter.Type, "gen_to_be_invoked."..UnK(getter.Name))%>;<% else %> <%=GetPushStatement(getter.Type, CsFullTypeName(type).."."..UnK(getter.Name))%>;<% end%>
return 1;
}
<%end)%>
<%ForEachCsList(setters, function(setter)
local is_struct = IsStruct(setter.Type)
%>
int <%=v_type_name%>_s_set_<%=setter.Name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%>
{
<%if AccessorNeedTranslator(setter) then %>ObjectTranslator translator = this;<%end%>
<%if not setter.IsStatic then %>
<%=GetSelfStatement(type)%>;
<%if is_struct then %><%=GetCasterStatement(setter.Type, 2, "gen_value", true)%>;
gen_to_be_invoked.<%=UnK(setter.Name)%> = gen_value;<% else
%><%=GetCasterStatement(setter.Type, 2, "gen_to_be_invoked." .. UnK(setter.Name))%>;<%end
else
if is_struct then %><%=GetCasterStatement(setter.Type, 1, "gen_value", true)%>;
<%=CsFullTypeName(type)%>.<%=UnK(setter.Name)%> = gen_value;<%else
%><%=GetCasterStatement(setter.Type, 1, CsFullTypeName(type) .."." .. UnK(setter.Name))%>;<%end
end%>
<%if NeedUpdate(type) and not setter.IsStatic then%>
<%=GetUpdateStatement(type, 1, "gen_to_be_invoked")%>;
<%end%>
return 0;
}
<%end)%>
<%ForEachCsList(events, function(event) if not event.IsStatic then %>
int <%=v_type_name%>_e_<%=event.Name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%>
{
ObjectTranslator translator = this;
<%=GetSelfStatement(type)%>;
<%=GetCasterStatement(event.Type, 3, "gen_delegate", true)%>;
if (gen_delegate == null) {
return LuaAPI.luaL_error(L, "#3 need <%=CsFullTypeName(event.Type)%>!");
}
if (gen_param_count == 3)
{
<%if event.CanAdd then%>
if (LuaAPI.xlua_is_eq_str(L, 2, "+")) {
gen_to_be_invoked.<%=UnK(event.Name)%> += gen_delegate;
return 0;
}
<%end%>
<%if event.CanRemove then%>
if (LuaAPI.xlua_is_eq_str(L, 2, "-")) {
gen_to_be_invoked.<%=UnK(event.Name)%> -= gen_delegate;
return 0;
}
<%end%>
}
LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%>.<%=event.Name%>!");
return 0;
}
<%end end)%>
<%ForEachCsList(events, function(event) if event.IsStatic then %>
int <%=v_type_name%>_e_<%=event.Name%><%=generic_arg_list%>(RealStatePtr L, int gen_param_count) <%=type_constraints%>
{
ObjectTranslator translator = this;
<%=GetCasterStatement(event.Type, 2, "gen_delegate", true)%>;
if (gen_delegate == null) {
return LuaAPI.luaL_error(L, "#2 need <%=CsFullTypeName(event.Type)%>!");
}
<%if event.CanAdd then%>
if (gen_param_count == 2 && LuaAPI.xlua_is_eq_str(L, 1, "+")) {
<%=CsFullTypeName(type)%>.<%=UnK(event.Name)%> += gen_delegate;
return 0;
}
<%end%>
<%if event.CanRemove then%>
if (gen_param_count == 2 && LuaAPI.xlua_is_eq_str(L, 1, "-")) {
<%=CsFullTypeName(type)%>.<%=UnK(event.Name)%> -= gen_delegate;
return 0;
}
<%end%>
return LuaAPI.luaL_error(L, "invalid arguments to <%=CsFullTypeName(type)%>.<%=event.Name%>!");
}
<%end end)%>
}
}

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 2bd79d95fd859724283926ad8fa4df30
timeCreated: 1501232428
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,104 @@
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using System;
<%
require "TemplateCommon"
%>
namespace XLua
{
public partial class DelegateBridge : DelegateBridgeBase
{
<%
ForEachCsList(delegates_groups, function(delegates_group, group_idx)
local delegate = delegates_group.Key
local parameters = delegate:GetParameters()
local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end)
local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end)
local in_pos = 0
local has_return = (delegate.ReturnType.FullName ~= "System.Void")
local return_type_name = has_return and CsFullTypeName(delegate.ReturnType) or "void"
local out_idx = has_return and 2 or 1
if has_return then out_num = out_num + 1 end
%>
public <%=return_type_name%> __Gen_Delegate_Imp<%=group_idx%>(<%ForEachCsList(parameters, function(parameter, pi)
if pi ~= 0 then
%>, <%
end
if parameter.IsOut and parameter.ParameterType.IsByRef then
%>out <%
elseif parameter.ParameterType.IsByRef then
%>ref <%
end
%><%=CsFullTypeName(parameter.ParameterType)%> p<%=pi%><%
end) %>)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
RealStatePtr L = luaEnv.rawL;
int errFunc = LuaAPI.pcall_prepare(L, errorFuncRef, luaReference);
<%if CallNeedTranslator(delegate, "") then %>ObjectTranslator translator = luaEnv.translator;<%end%>
<%
local param_count = parameters.Length
local has_v_params = param_count > 0 and parameters[param_count - 1].IsParamArray
ForEachCsList(parameters, function(parameter, pi)
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
%><%=GetPushStatement(parameter.ParameterType, 'p' .. pi, has_v_params and pi == param_count - 1)%>;
<%
end
end) %>
PCall(L, <%=has_v_params and ((in_num - 1) .. " + (p".. (param_count - 1) .. " == null ? 0 : p" .. (param_count - 1) .. ".Length)" ) or in_num%>, <%=out_num%>, errFunc);
<%ForEachCsList(parameters, function(parameter, pi)
if parameter.IsOut or parameter.ParameterType.IsByRef then
%><%=GetCasterStatement(parameter.ParameterType, "errFunc" .. (" + "..out_idx), 'p' .. pi)%>;
<%
out_idx = out_idx + 1
end
end) %>
<%if has_return then %><%=GetCasterStatement(delegate.ReturnType, "errFunc + 1", "__gen_ret", true)%>;<% end%>
LuaAPI.lua_settop(L, errFunc - 1);
<%if has_return then %>return __gen_ret;<% end%>
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
<%end)%>
static DelegateBridge()
{
Gen_Flag = true;
}
public override Delegate GetDelegateByType(Type type)
{
<%
ForEachCsList(delegates_groups, function(delegates_group, group_idx)
ForEachCsList(delegates_group.Value, function(delegate)
if delegate.DeclaringType then
local delegate_type_name = CsFullTypeName(delegate.DeclaringType)
%>
if (type == typeof(<%=delegate_type_name%>))
{
return new <%=delegate_type_name%>(__Gen_Delegate_Imp<%=group_idx%>);
}
<%
end
end)
end)
%>
return null;
}
}
}

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3d992756e2469044484be75f78e4e556
timeCreated: 1481620508
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,128 @@
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
<%
require "TemplateCommon"
local parameters = delegate:GetParameters()
local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end)
local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end)
local in_pos = 0
local has_return = (delegate.ReturnType.Name ~= "Void")
%>
namespace XLua.CSObjectWrap
{
using Utils = XLua.Utils;
public class <%=CSVariableName(type)%>Wrap
{
public static void __Register(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Utils.BeginObjectRegister(typeof(<%=CsFullTypeName(type)%>), L, translator, 0, 0, 0, 0);
Utils.EndObjectRegister(typeof(<%=CsFullTypeName(type)%>), L, translator, null, null, null, null, null);
Utils.BeginClassRegister(typeof(<%=CsFullTypeName(type)%>), L, null, 1, 0, 0);
Utils.EndClassRegister(typeof(<%=CsFullTypeName(type)%>), L, translator);
}
static Dictionary<string, LuaCSFunction> __MetaFucntions_Dic = new Dictionary<string, LuaCSFunction>(){
{"__call", __CallMeta},
{"__add", __AddMeta},
{"__sub", __SubMeta},
};
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __CallMeta(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
try {
if(LuaAPI.lua_gettop(L) == <%=in_num+1%> && <%=GetCheckStatement(type, 1)%><%
ForEachCsList(parameters, function(parameter)
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then in_pos = in_pos + 1;
%>&& <%=GetCheckStatement(parameter.ParameterType, in_pos+1)%><%
end
end)%>)
{
<%
in_pos = 0;
ForEachCsList(parameters, function(parameter)
%><%
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
in_pos = in_pos + 1
%><%=GetCasterStatement(parameter.ParameterType, in_pos+1, parameter.Name, true)%><%
else%><%=CsFullTypeName(parameter.ParameterType)%> <%=parameter.Name%><%end%>;
<%end)%>
<%=GetSelfStatement(type)%>;
<%
if has_return then
%> var __cl_gen_ret = <%
end
%> __cl_gen_to_be_invoked( <%ForEachCsList(parameters, function(parameter, pi) if pi ~= 0 then %>, <% end; if parameter.IsOut then %>out <% elseif parameter.ParameterType.IsByRef then %>ref <% end %><%=parameter.Name%><% end) %> );
<%
if has_return then
%> <%=GetPushStatement(delegate.ReturnType, "__cl_gen_ret")%>;
<%
end
local in_pos = 0
ForEachCsList(parameters, function(parameter)
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
in_pos = in_pos + 1
end
if parameter.IsOut or parameter.ParameterType.IsByRef then
%><%=GetPushStatement(parameter.ParameterType:GetElementType(), parameter.Name)%>;
<%if not parameter.IsOut and parameter.ParameterType.IsByRef and NeedUpdate(parameter.ParameterType) then
%><%=GetUpdateStatement(parameter.ParameterType:GetElementType(), in_pos+param_offset, parameter.Name)%>;
<%end%>
<%
end
end)
%>
return <%=out_num+(has_return and 1 or 0)%>;
}
} catch(System.Exception __gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + __gen_e);
}
return LuaAPI.luaL_error(L, "invalid arguments to Delegate <%=CsFullTypeName(type)%>!");
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __AddMeta(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
try {
<%=GetCasterStatement(type, 1, "leftside", true)%>;
<%=GetCasterStatement(type, 2, "rightside", true)%>;
<%=GetPushStatement(type, "leftside + rightside")%>;
return 1;
} catch(System.Exception __gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + __gen_e);
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __SubMeta(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
try {
<%=GetCasterStatement(type, 1, "leftside", true)%>;
<%=GetCasterStatement(type, 2, "rightside", true)%>;
<%=GetPushStatement(type, "leftside - rightside")%>;
return 1;
} catch(System.Exception __gen_e) {
return LuaAPI.luaL_error(L, "c# exception:" + __gen_e);
}
}
}
}

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 33b33e1cd617f794b8c801a32f3b2539
timeCreated: 1481620508
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,102 @@
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
<%
require "TemplateCommon"
local enum_or_op = debug.getmetatable(CS.System.Reflection.BindingFlags.Public).__bor
%>
namespace XLua.CSObjectWrap
{
using Utils = XLua.Utils;
<%ForEachCsList(types, function(type)
local fields = type2fields and type2fields[type] or type:GetFields(enum_or_op(CS.System.Reflection.BindingFlags.Public, CS.System.Reflection.BindingFlags.Static))
local fields_to_gen = {}
ForEachCsList(fields, function(field)
if field.Name ~= "value__" and not IsObsolute(field) then
table.insert(fields_to_gen, field)
end
end)
%>
public class <%=CSVariableName(type)%>Wrap
{
public static void __Register(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
Utils.BeginObjectRegister(typeof(<%=CsFullTypeName(type)%>), L, translator, 0, 0, 0, 0);
Utils.EndObjectRegister(typeof(<%=CsFullTypeName(type)%>), L, translator, null, null, null, null, null);
Utils.BeginClassRegister(typeof(<%=CsFullTypeName(type)%>), L, null, <%=fields.Length + 1%>, 0, 0);
<%if #fields_to_gen <= 20 then%>
<% ForEachCsList(fields, function(field)
if field.Name == "value__" or IsObsolute(field) then return end
%>
Utils.RegisterObject(L, translator, Utils.CLS_IDX, "<%=field.Name%>", <%=CsFullTypeName(type)%>.<%=UnK(field.Name)%>);
<%end)%>
<%else%>
Utils.RegisterEnumType(L, typeof(<%=CsFullTypeName(type)%>));
<%end%>
Utils.RegisterFunc(L, Utils.CLS_IDX, "__CastFrom", __CastFrom);
Utils.EndClassRegister(typeof(<%=CsFullTypeName(type)%>), L, translator);
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static int __CastFrom(RealStatePtr L)
{
ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);
LuaTypes lua_type = LuaAPI.lua_type(L, 1);
if (lua_type == LuaTypes.LUA_TNUMBER)
{
translator.Push<%=CSVariableName(type)%>(L, (<%=CsFullTypeName(type)%>)LuaAPI.xlua_tointeger(L, 1));
}
<%if #fields_to_gen > 0 then%>
else if(lua_type == LuaTypes.LUA_TSTRING)
{
<%if #fields_to_gen <= 20 then%>
<%
local is_first = true
ForEachCsList(fields, function(field, i)
if field.Name == "value__" or IsObsolute(field) then return end
%><%=(is_first and "" or "else ")%>if (LuaAPI.xlua_is_eq_str(L, 1, "<%=field.Name%>"))
{
translator.Push<%=CSVariableName(type)%>(L, <%=CsFullTypeName(type)%>.<%=UnK(field.Name)%>);
}
<%
is_first = false
end)
%>else
{
return LuaAPI.luaL_error(L, "invalid string for <%=CsFullTypeName(type)%>!");
}
<%else%>
try
{
translator.TranslateToEnumToTop(L, typeof(<%=CsFullTypeName(type)%>), 1);
}
catch (System.Exception e)
{
return LuaAPI.luaL_error(L, "cast to " + typeof(<%=CsFullTypeName(type)%>) + " exception:" + e);
}
<%end%>
}
<%end%>
else
{
return LuaAPI.luaL_error(L, "invalid lua type for <%=CsFullTypeName(type)%>! Expect number or string, got + " + lua_type);
}
return 1;
}
}
<%end)%>
}

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ae16c73aad9a21a44aef65decb7e4928
timeCreated: 1481620508
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,99 @@
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using XLua;
using System.Collections.Generic;
<%
require "TemplateCommon"
local enum_or_op = debug.getmetatable(CS.System.Reflection.BindingFlags.Public).__bor
%>
namespace XLua
{
public partial class ObjectTranslator
{
<%ForEachCsList(types, function(type)
local fields = type2fields and type2fields[type] or type:GetFields(enum_or_op(CS.System.Reflection.BindingFlags.Public, CS.System.Reflection.BindingFlags.Static))
local fields_to_gen = {}
ForEachCsList(fields, function(field)
if field.Name ~= "value__" and not IsObsolute(field) then
table.insert(fields_to_gen, field)
end
end)
local v_type_name = CSVariableName(type)
%>
public void __Register<%=v_type_name%>(RealStatePtr L)
{
Utils.BeginObjectRegister(typeof(<%=CsFullTypeName(type)%>), L, this, 0, 0, 0, 0);
Utils.EndObjectRegister(typeof(<%=CsFullTypeName(type)%>), L, this, null, null, null, null, null);
Utils.BeginClassRegister(typeof(<%=CsFullTypeName(type)%>), L, null, <%=fields.Length + 1%>, 0, 0);
<%if #fields_to_gen <= 20 then%>
<% ForEachCsList(fields, function(field)
if field.Name == "value__" or IsObsolute(field) then return end
%>
Utils.RegisterObject(L, this, Utils.CLS_IDX, "<%=field.Name%>", <%=CsFullTypeName(type)%>.<%=UnK(field.Name)%>);
<%end)%>
<%else%>
Utils.RegisterEnumType(L, typeof(<%=CsFullTypeName(type)%>));
<%end%>
Utils.RegisterFunc(L, Utils.CLS_IDX, "__CastFrom", __CastFrom<%=v_type_name%>);
Utils.EndClassRegister(typeof(<%=CsFullTypeName(type)%>), L, this);
}
int __CastFrom<%=v_type_name%>(RealStatePtr L, int __gen_top)
{
LuaTypes lua_type = LuaAPI.lua_type(L, 1);
if (lua_type == LuaTypes.LUA_TNUMBER)
{
Push<%=v_type_name%>(L, (<%=CsFullTypeName(type)%>)LuaAPI.xlua_tointeger(L, 1));
}
<%if #fields_to_gen > 0 then%>
else if(lua_type == LuaTypes.LUA_TSTRING)
{
<%if #fields_to_gen <= 20 then%>
<%
local is_first = true
ForEachCsList(fields, function(field, i)
if field.Name == "value__" or IsObsolute(field) then return end
%><%=(is_first and "" or "else ")%>if (LuaAPI.xlua_is_eq_str(L, 1, "<%=field.Name%>"))
{
Push<%=v_type_name%>(L, <%=CsFullTypeName(type)%>.<%=UnK(field.Name)%>);
}
<%
is_first = false
end)
%>else
{
return LuaAPI.luaL_error(L, "invalid string for <%=CsFullTypeName(type)%>!");
}
<%else%>
try
{
TranslateToEnumToTop(L, typeof(<%=CsFullTypeName(type)%>), 1);
}
catch (System.Exception e)
{
return LuaAPI.luaL_error(L, "cast to " + typeof(<%=CsFullTypeName(type)%>) + " exception:" + e);
}
<%end%>
}
<%end%>
else
{
return LuaAPI.luaL_error(L, "invalid lua type for <%=CsFullTypeName(type)%>! Expect number or string, got + " + lua_type);
}
return 1;
}
<%end)%>
}
}

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ea84a5ee7abf8e347a810eb7848add46
timeCreated: 1501232428
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,385 @@
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using XLua;
using System;
<%
require "TemplateCommon"
%>
namespace XLua.CSObjectWrap
{
public class <%=CSVariableName(type)%>Bridge : LuaBase, <%=CsFullTypeName(type)%>
{
public static LuaBase __Create(int reference, LuaEnv luaenv)
{
return new <%=CSVariableName(type)%>Bridge(reference, luaenv);
}
public <%=CSVariableName(type)%>Bridge(int reference, LuaEnv luaenv) : base(reference, luaenv)
{
}
<%
ForEachCsList(methods, function(method)
local parameters = method:GetParameters()
local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end)
local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end)
local in_pos = 0
local has_return = (method.ReturnType.FullName ~= "System.Void")
local return_type_name = has_return and CsFullTypeName(method.ReturnType) or "void"
local out_idx = has_return and 2 or 1
if has_return then out_num = out_num + 1 end
%>
<%=return_type_name%> <%=CsFullTypeName(method.DeclaringType)%>.<%=method.Name%>(<%ForEachCsList(parameters, function(parameter, pi)
if pi ~= 0 then
%>, <%
end
if parameter.IsOut and parameter.ParameterType.IsByRef then
%>out <%
elseif parameter.ParameterType.IsByRef then
%>ref <%
end
%><%=CsFullTypeName(parameter.ParameterType)%> <%=parameter.Name%><%
end) %>)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
RealStatePtr L = luaEnv.L;
int err_func = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
<%if CallNeedTranslator(method, "") then %>ObjectTranslator translator = luaEnv.translator;<%end%>
LuaAPI.lua_getref(L, luaReference);
LuaAPI.xlua_pushasciistring(L, "<%=method.Name%>");
if (0 != LuaAPI.xlua_pgettable(L, -2))
{
luaEnv.ThrowExceptionFromError(err_func - 1);
}
if(!LuaAPI.lua_isfunction(L, -1))
{
LuaAPI.xlua_pushasciistring(L, "no such function <%=method.Name%>");
luaEnv.ThrowExceptionFromError(err_func - 1);
}
LuaAPI.lua_pushvalue(L, -2);
LuaAPI.lua_remove(L, -3);
<%
local param_count = parameters.Length
local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1])
ForEachCsList(parameters, function(parameter, pi)
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
%><%=GetPushStatement(parameter.ParameterType, parameter.Name, has_v_params and pi == param_count - 1)%>;
<%
end
end) %>
int __gen_error = LuaAPI.lua_pcall(L, <%=has_v_params and ((in_num) .. " + (".. parameters[param_count - 1].Name .. " == null ? 0 : " .. parameters[param_count - 1].Name .. ".Length)" ) or (in_num + 1)%>, <%=out_num%>, err_func);
if (__gen_error != 0)
luaEnv.ThrowExceptionFromError(err_func - 1);
<%ForEachCsList(parameters, function(parameter)
if parameter.IsOut or parameter.ParameterType.IsByRef then
%><%=GetCasterStatement(parameter.ParameterType, "err_func" .. (" + "..out_idx), parameter.Name)%>;
<%
out_idx = out_idx + 1
end
end) %>
<%if has_return then %><%=GetCasterStatement(method.ReturnType, "err_func + 1", "__gen_ret", true)%>;<% end%>
LuaAPI.lua_settop(L, err_func - 1);
<%if has_return then %>return __gen_ret;<% end%>
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
<%end)%>
<%
ForEachCsList(propertys, function(property)
%>
<%=CsFullTypeName(property.PropertyType)%> <%=CsFullTypeName(property.DeclaringType)%>.<%=property.Name%>
{
<%if property.CanRead then%>
get
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
RealStatePtr L = luaEnv.L;
int oldTop = LuaAPI.lua_gettop(L);
<%if not JustLuaType(property.PropertyType) then %>ObjectTranslator translator = luaEnv.translator;<%end%>
LuaAPI.lua_getref(L, luaReference);
LuaAPI.xlua_pushasciistring(L, "<%=property.Name%>");
if (0 != LuaAPI.xlua_pgettable(L, -2))
{
luaEnv.ThrowExceptionFromError(oldTop);
}
<%=GetCasterStatement(property.PropertyType, "-1", "__gen_ret", true)%>;
LuaAPI.lua_pop(L, 2);
return __gen_ret;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
<%end%>
<%if property.CanWrite then%>
set
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
RealStatePtr L = luaEnv.L;
int oldTop = LuaAPI.lua_gettop(L);
<%if not JustLuaType(property.PropertyType) then %>ObjectTranslator translator = luaEnv.translator;<%end%>
LuaAPI.lua_getref(L, luaReference);
LuaAPI.xlua_pushasciistring(L, "<%=property.Name%>");
<%=GetPushStatement(property.PropertyType, "value")%>;
if (0 != LuaAPI.xlua_psettable(L, -3))
{
luaEnv.ThrowExceptionFromError(oldTop);
}
LuaAPI.lua_pop(L, 1);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
<%end%>
}
<%end)%>
<%ForEachCsList(events, function(event) %>
event <%=CsFullTypeName(event.EventHandlerType)%> <%=CsFullTypeName(event.DeclaringType)%>.<%=event.Name%>
{<%local parameters = event:GetAddMethod():GetParameters()%>
add
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
RealStatePtr L = luaEnv.L;
int err_func = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
<%if CallNeedTranslator(event:GetAddMethod(), "") then %>ObjectTranslator translator = luaEnv.translator;<%end%>
LuaAPI.lua_getref(L, luaReference);
LuaAPI.xlua_pushasciistring(L, "add_<%=event.Name%>");
if (0 != LuaAPI.xlua_pgettable(L, -2))
{
luaEnv.ThrowExceptionFromError(err_func - 1);
}
if(!LuaAPI.lua_isfunction(L, -1))
{
LuaAPI.xlua_pushasciistring(L, "no such function add_<%=event.Name%>");
luaEnv.ThrowExceptionFromError(err_func - 1);
}
LuaAPI.lua_pushvalue(L, -2);
LuaAPI.lua_remove(L, -3);
<%
local param_count = parameters.Length
local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1])
ForEachCsList(parameters, function(parameter, pi)
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
%><%=GetPushStatement(parameter.ParameterType, parameter.Name, has_v_params and pi == param_count - 1)%>;
<%
end
end) %>
int __gen_error = LuaAPI.lua_pcall(L, 2, 0, err_func);
if (__gen_error != 0)
luaEnv.ThrowExceptionFromError(err_func - 1);
LuaAPI.lua_settop(L, err_func - 1);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
remove
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
RealStatePtr L = luaEnv.L;
int err_func = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
<%if CallNeedTranslator(event:GetRemoveMethod(), "") then %>ObjectTranslator translator = luaEnv.translator;<%end%>
LuaAPI.lua_getref(L, luaReference);
LuaAPI.xlua_pushasciistring(L, "remove_<%=event.Name%>");
if (0 != LuaAPI.xlua_pgettable(L, -2))
{
luaEnv.ThrowExceptionFromError(err_func - 1);
}
if(!LuaAPI.lua_isfunction(L, -1))
{
LuaAPI.xlua_pushasciistring(L, "no such function remove_<%=event.Name%>");
luaEnv.ThrowExceptionFromError(err_func - 1);
}
LuaAPI.lua_pushvalue(L, -2);
LuaAPI.lua_remove(L, -3);
<%
local param_count = parameters.Length
local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1])
ForEachCsList(parameters, function(parameter, pi)
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
%><%=GetPushStatement(parameter.ParameterType, parameter.Name, has_v_params and pi == param_count - 1)%>;
<%
end
end) %>
int __gen_error = LuaAPI.lua_pcall(L, 2, 0, err_func);
if (__gen_error != 0)
luaEnv.ThrowExceptionFromError(err_func - 1);
LuaAPI.lua_settop(L, err_func - 1);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
}
<%end)%>
<%ForEachCsList(indexers, function(indexer)
local ptype = (indexer:GetGetMethod() or indexer:GetSetMethod()):GetParameters()[0].ParameterType
local pname = (indexer:GetGetMethod() or indexer:GetSetMethod()):GetParameters()[0].Name
%>
<%=CsFullTypeName(indexer.PropertyType)%> <%=CsFullTypeName(indexer.DeclaringType)%>.this[<%=CsFullTypeName(ptype)%> <%=pname%>]
{<%if indexer:GetGetMethod() then
local method = indexer:GetGetMethod()
local parameters = method:GetParameters()
local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end)
local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end)
local in_pos = 0
local has_return = (method.ReturnType.FullName ~= "System.Void")
local return_type_name = has_return and CsFullTypeName(method.ReturnType) or "void"
local out_idx = has_return and 2 or 1
if has_return then out_num = out_num + 1 end
%>
get
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
RealStatePtr L = luaEnv.L;
int err_func = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
<%if CallNeedTranslator(method, "") then %>ObjectTranslator translator = luaEnv.translator;<%end%>
LuaAPI.lua_getref(L, luaReference);
LuaAPI.xlua_pushasciistring(L, "<%=method.Name%>");
if (0 != LuaAPI.xlua_pgettable(L, -2))
{
luaEnv.ThrowExceptionFromError(err_func - 1);
}
if(!LuaAPI.lua_isfunction(L, -1))
{
LuaAPI.xlua_pushasciistring(L, "no such function <%=method.Name%>");
luaEnv.ThrowExceptionFromError(err_func - 1);
}
LuaAPI.lua_pushvalue(L, -2);
LuaAPI.lua_remove(L, -3);
<%
local param_count = parameters.Length
local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1])
ForEachCsList(parameters, function(parameter, pi)
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
%><%=GetPushStatement(parameter.ParameterType, parameter.Name, has_v_params and pi == param_count - 1)%>;
<%
end
end) %>
int __gen_error = LuaAPI.lua_pcall(L, <%=has_v_params and ((in_num) .. " + " .. parameters[param_count - 1].Name .. ".Length" ) or (in_num + 1)%>, <%=out_num%>, err_func);
if (__gen_error != 0)
luaEnv.ThrowExceptionFromError(err_func - 1);
<%ForEachCsList(parameters, function(parameter)
if parameter.IsOut or parameter.ParameterType.IsByRef then
%><%=GetCasterStatement(parameter.ParameterType, "err_func" .. (" + "..out_idx), parameter.Name)%>;
<%
out_idx = out_idx + 1
end
end) %>
<%if has_return then %><%=GetCasterStatement(method.ReturnType, "err_func + 1", "__gen_ret", true)%>;<% end%>
LuaAPI.lua_settop(L, err_func - 1);
<%if has_return then %>return __gen_ret;<% end%>
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
<%end%>
<%if indexer:GetSetMethod() then
local method = indexer:GetSetMethod()
local parameters = method:GetParameters()
local in_num = CalcCsList(parameters, function(p) return not (p.IsOut and p.ParameterType.IsByRef) end)
local out_num = CalcCsList(parameters, function(p) return p.IsOut or p.ParameterType.IsByRef end)
local in_pos = 0
local has_return = (method.ReturnType.FullName ~= "System.Void")
local return_type_name = has_return and CsFullTypeName(method.ReturnType) or "void"
local out_idx = has_return and 2 or 1
if has_return then out_num = out_num + 1 end
%>
set
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
RealStatePtr L = luaEnv.L;
int err_func = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
<%if CallNeedTranslator(method, "") then %>ObjectTranslator translator = luaEnv.translator;<%end%>
LuaAPI.lua_getref(L, luaReference);
LuaAPI.xlua_pushasciistring(L, "<%=method.Name%>");
if (0 != LuaAPI.xlua_pgettable(L, -2))
{
luaEnv.ThrowExceptionFromError(err_func - 1);
}
if(!LuaAPI.lua_isfunction(L, -1))
{
LuaAPI.xlua_pushasciistring(L, "no such function <%=method.Name%>");
luaEnv.ThrowExceptionFromError(err_func - 1);
}
LuaAPI.lua_pushvalue(L, -2);
LuaAPI.lua_remove(L, -3);
<%
local param_count = parameters.Length
local has_v_params = param_count > 0 and IsParams(parameters[param_count - 1])
ForEachCsList(parameters, function(parameter, pi)
if not (parameter.IsOut and parameter.ParameterType.IsByRef) then
%><%=GetPushStatement(parameter.ParameterType, parameter.Name, has_v_params and pi == param_count - 1)%>;
<%
end
end) %>
int __gen_error = LuaAPI.lua_pcall(L, <%=has_v_params and ((in_num) .. " + " .. parameters[param_count - 1].Name .. ".Length" ) or (in_num + 1)%>, <%=out_num%>, err_func);
if (__gen_error != 0)
luaEnv.ThrowExceptionFromError(err_func - 1);
<%ForEachCsList(parameters, function(parameter)
if parameter.IsOut or parameter.ParameterType.IsByRef then
%><%=GetCasterStatement(parameter.ParameterType, "err_func" .. (" + "..out_idx), parameter.Name)%>;
<%
out_idx = out_idx + 1
end
end) %>
<%if has_return then %><%=GetCasterStatement(method.ReturnType, "err_func + 1", "__gen_ret", true)%>;<% end%>
LuaAPI.lua_settop(L, err_func - 1);
<%if has_return then %>return __gen_ret;<% end%>
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
<%end%>
}
<%end)%>
}
}

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 7165d08e91378494dadeb10e5338accb
timeCreated: 1481620508
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,140 @@
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using System;
using System.Collections.Generic;
using System.Reflection;
<%
require "TemplateCommon"
%>
namespace XLua.CSObjectWrap
{
public class XLua_Gen_Initer_Register__
{
<%
local split_method_perfix = 'wrapInit'
local split_method_count = 0
local wrap_in_split_method = 0
local max_wrap_in_split_method = 50
%>
<%ForEachCsList(wraps, function(wrap)%>
<%if wrap_in_split_method == 0 then%>static void <%=split_method_perfix%><%=split_method_count%>(LuaEnv luaenv, ObjectTranslator translator)
{
<%end%>
translator.DelayWrapLoader(typeof(<%=CsFullTypeName(wrap)%>), <%=CSVariableName(wrap)%>Wrap.__Register);
<%if wrap_in_split_method == max_wrap_in_split_method then
wrap_in_split_method = 0
split_method_count = split_method_count + 1
%>
}
<%else
wrap_in_split_method = wrap_in_split_method + 1
end
end)%>
<% if generic_wraps then
for generic_def, instances in pairs(generic_wraps) do
for _, args in ipairs(instances) do
local generic_arg_list = "<"
ForEachCsList(args, function(generic_arg, gai)
if gai ~= 0 then generic_arg_list = generic_arg_list .. ", " end
generic_arg_list = generic_arg_list .. CsFullTypeName(generic_arg)
end)
generic_arg_list = generic_arg_list .. ">"
%>
<%if wrap_in_split_method == 0 then%>static void <%=split_method_perfix%><%=split_method_count%>(LuaEnv luaenv, ObjectTranslator translator)
{
<%end%>
translator.DelayWrapLoader(typeof(<%=generic_def.Name:gsub("`%d+", "") .. generic_arg_list%>), <%=CSVariableName(generic_def)%>Wrap<%=generic_arg_list%>.__Register);
<%if wrap_in_split_method == max_wrap_in_split_method then
wrap_in_split_method = 0
split_method_count = split_method_count + 1
%>
}
<%else
wrap_in_split_method = wrap_in_split_method + 1
end
end
end
end%>
<%if wrap_in_split_method ~= 0 then
split_method_count = split_method_count + 1
%>}<%end%>
static void Init(LuaEnv luaenv, ObjectTranslator translator)
{
<%for i = 1, split_method_count do%>
<%=split_method_perfix%><%=(i - 1)%>(luaenv, translator);
<%end%>
<%ForEachCsList(itf_bridges, function(itf_bridge)%>
translator.AddInterfaceBridgeCreator(typeof(<%=CsFullTypeName(itf_bridge)%>), <%=CSVariableName(itf_bridge)%>Bridge.__Create);
<%end)%>
}
static XLua_Gen_Initer_Register__()
{
XLua.LuaEnv.AddIniter(Init);
}
}
}
namespace XLua
{
public partial class ObjectTranslator
{
static XLua.CSObjectWrap.XLua_Gen_Initer_Register__ s_gen_reg_dumb_obj = new XLua.CSObjectWrap.XLua_Gen_Initer_Register__();
static XLua.CSObjectWrap.XLua_Gen_Initer_Register__ gen_reg_dumb_obj {get{return s_gen_reg_dumb_obj;}}
}
internal partial class InternalGlobals
{
<%
local type_to_methods = {}
local seq_tbl = {}
ForEachCsList(extension_methods, function(extension_method, idx)
local parameters = extension_method:GetParameters()
local type = parameters[0].ParameterType
if not type_to_methods[type] then
type_to_methods[type] = {type = type}
table.insert(seq_tbl, type_to_methods[type])
end
table.insert(type_to_methods[type], {method = extension_method, index = idx})
%>
delegate <%=CsFullTypeName(extension_method.ReturnType)%> __GEN_DELEGATE<%=idx%>(<%ForEachCsList(parameters, function(parameter, pi)
%><%if pi ~= 0 then%>, <%end%><%if parameter.IsOut then %>out <% elseif parameter.ParameterType.IsByRef then %>ref <% end %> <%=CsFullTypeName(parameter.ParameterType)%> <%=parameter.Name%><%
end)%>);
<%end)%>
static InternalGlobals()
{
extensionMethodMap = new Dictionary<Type, IEnumerable<MethodInfo>>()
{
<%for _, methods_info in ipairs(seq_tbl) do%>
{typeof(<%=CsFullTypeName(methods_info.type)%>), new List<MethodInfo>(){
<% for _, method_info in ipairs(methods_info) do%>
new __GEN_DELEGATE<%=method_info.index%>(<%=CsFullTypeName(method_info.method.DeclaringType)%>.<%=method_info.method.Name%>)
#if UNITY_WSA && !UNITY_EDITOR
.GetMethodInfo(),
#else
.Method,
#endif
<% end%>
}},
<%end%>
};
genTryArrayGetPtr = StaticLuaCallbacks.__tryArrayGet;
genTryArraySetPtr = StaticLuaCallbacks.__tryArraySet;
}
}
}

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e416b82ec9fe340458f97cf1e3468ef7
timeCreated: 1481620508
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,140 @@
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using System;
using System.Collections.Generic;
using System.Reflection;
<%
require "TemplateCommon"
%>
namespace XLua.CSObjectWrap
{
public class XLua_Gen_Initer_Register__
{
<%
local split_method_perfix = 'wrapInit'
local split_method_count = 0
local wrap_in_split_method = 0
local max_wrap_in_split_method = 50
%>
<%ForEachCsList(wraps, function(wrap)%>
<%if wrap_in_split_method == 0 then%>static void <%=split_method_perfix%><%=split_method_count%>(LuaEnv luaenv, ObjectTranslator translator)
{
<%end%>
translator.DelayWrapLoader(typeof(<%=CsFullTypeName(wrap)%>), translator.__Register<%=CSVariableName(wrap)%>);
<%if wrap_in_split_method == max_wrap_in_split_method then
wrap_in_split_method = 0
split_method_count = split_method_count + 1
%>
}
<%else
wrap_in_split_method = wrap_in_split_method + 1
end
end)%>
<% if generic_wraps then
for generic_def, instances in pairs(generic_wraps) do
for _, args in ipairs(instances) do
local generic_arg_list = "<"
ForEachCsList(args, function(generic_arg, gai)
if gai ~= 0 then generic_arg_list = generic_arg_list .. ", " end
generic_arg_list = generic_arg_list .. CsFullTypeName(generic_arg)
end)
generic_arg_list = generic_arg_list .. ">"
%>
<%if wrap_in_split_method == 0 then%>static void <%=split_method_perfix%><%=split_method_count%>(LuaEnv luaenv, ObjectTranslator translator)
{
<%end%>
translator.DelayWrapLoader(typeof(<%=generic_def.Name:gsub("`%d+", "") .. generic_arg_list%>), translator.__Register<%=CSVariableName(generic_def)%><%=generic_arg_list%>);
<%if wrap_in_split_method == max_wrap_in_split_method then
wrap_in_split_method = 0
split_method_count = split_method_count + 1
%>
}
<%else
wrap_in_split_method = wrap_in_split_method + 1
end
end
end
end%>
<%if wrap_in_split_method ~= 0 then
split_method_count = split_method_count + 1
%>}<%end%>
static void Init(LuaEnv luaenv, ObjectTranslator translator)
{
<%for i = 1, split_method_count do%>
<%=split_method_perfix%><%=(i - 1)%>(luaenv, translator);
<%end%>
<%ForEachCsList(itf_bridges, function(itf_bridge)%>
translator.AddInterfaceBridgeCreator(typeof(<%=CsFullTypeName(itf_bridge)%>), <%=CSVariableName(itf_bridge)%>Bridge.__Create);
<%end)%>
}
static XLua_Gen_Initer_Register__()
{
XLua.LuaEnv.AddIniter(Init);
}
}
}
namespace XLua
{
public partial class ObjectTranslator
{
static XLua.CSObjectWrap.XLua_Gen_Initer_Register__ s_gen_reg_dumb_obj = new XLua.CSObjectWrap.XLua_Gen_Initer_Register__();
static XLua.CSObjectWrap.XLua_Gen_Initer_Register__ gen_reg_dumb_obj {get{return s_gen_reg_dumb_obj;}}
}
internal partial class InternalGlobals
{
<%
local type_to_methods = {}
local seq_tbl = {}
ForEachCsList(extension_methods, function(extension_method, idx)
local parameters = extension_method:GetParameters()
local type = parameters[0].ParameterType
if not type_to_methods[type] then
type_to_methods[type] = {type = type}
table.insert(seq_tbl, type_to_methods[type])
end
table.insert(type_to_methods[type], {method = extension_method, index = idx})
%>
delegate <%=CsFullTypeName(extension_method.ReturnType)%> __GEN_DELEGATE<%=idx%>(<%ForEachCsList(parameters, function(parameter, pi)
%><%if pi ~= 0 then%>, <%end%><%if parameter.IsOut then %>out <% elseif parameter.ParameterType.IsByRef then %>ref <% end %> <%=CsFullTypeName(parameter.ParameterType)%> <%=parameter.Name%><%
end)%>);
<%end)%>
static InternalGlobals()
{
extensionMethodMap = new Dictionary<Type, IEnumerable<MethodInfo>>()
{
<%for _, methods_info in ipairs(seq_tbl) do%>
{typeof(<%=CsFullTypeName(methods_info.type)%>), new List<MethodInfo>(){
<% for _, method_info in ipairs(methods_info) do%>
new __GEN_DELEGATE<%=method_info.index%>(<%=CsFullTypeName(method_info.method.DeclaringType)%>.<%=method_info.method.Name%>)
#if UNITY_WSA && !UNITY_EDITOR
.GetMethodInfo(),
#else
.Method,
#endif
<% end%>
}},
<%end%>
};
genTryArrayGetPtr = StaticLuaCallbacks.__tryArrayGet;
genTryArraySetPtr = StaticLuaCallbacks.__tryArraySet;
}
}
}

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 46c7366d55afbf1459674448d92c44c8
timeCreated: 1501232428
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,233 @@
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using System;
<%
require "TemplateCommon"
%>
namespace XLua
{
public partial class ObjectTranslator
{
<%if purevaluetypes.Count > 0 then
local init_class_name = "IniterAdder" .. CSVariableName(purevaluetypes[0].Type)
%>
class <%=init_class_name%>
{
static <%=init_class_name%>()
{
LuaEnv.AddIniter(Init);
}
static void Init(LuaEnv luaenv, ObjectTranslator translator)
{
<%ForEachCsList(purevaluetypes, function(type_info)
if not type_info.Type.IsValueType then return end
local full_type_name = CsFullTypeName(type_info.Type)%>
translator.RegisterPushAndGetAndUpdate<<%=full_type_name%>>(translator.Push<%=CSVariableName(type_info.Type)%>, translator.Get, translator.Update<%=CSVariableName(type_info.Type)%>);<%
end)%>
<%ForEachCsList(tableoptimzetypes, function(type_info)
local full_type_name = CsFullTypeName(type_info.Type)%>
translator.RegisterCaster<<%=full_type_name%>>(translator.Get);<%
end)%>
}
}
static <%=init_class_name%> s_<%=init_class_name%>_dumb_obj = new <%=init_class_name%>();
static <%=init_class_name%> <%=init_class_name%>_dumb_obj {get{return s_<%=init_class_name%>_dumb_obj;}}
<%end%>
<%ForEachCsList(purevaluetypes, function(type_info)
local type_id_var_name = CSVariableName(type_info.Type) .. '_TypeID'
local enum_ref_var_name = CSVariableName(type_info.Type)..'_EnumRef'
local full_type_name = CsFullTypeName(type_info.Type)
local is_enum = type_info.Type.IsEnum
%>int <%=type_id_var_name%> = -1;<%if is_enum then%>
int <%=enum_ref_var_name%> = -1;
<%end%>
public void Push<%=CSVariableName(type_info.Type)%>(RealStatePtr L, <%=full_type_name%> val)
{
if (<%=type_id_var_name%> == -1)
{
bool is_first;
<%=type_id_var_name%> = getTypeId(L, typeof(<%=full_type_name%>), out is_first);
<%if is_enum then%>
if (<%=enum_ref_var_name%> == -1)
{
Utils.LoadCSTable(L, typeof(<%=full_type_name%>));
<%=enum_ref_var_name%> = LuaAPI.luaL_ref(L, LuaIndexes.LUA_REGISTRYINDEX);
}
<%end%>
}
<%if is_enum then%>
if (LuaAPI.xlua_tryget_cachedud(L, (int)val, <%=enum_ref_var_name%>) == 1)
{
return;
}
<%
end
if type_info.Flag == CS.XLua.OptimizeFlag.PackAsTable then
%>
<%if PushObjectNeedTranslator(type_info) then %> ObjectTranslator translator = ObjectTranslatorPool.Instance.Find(L);<%end%>
LuaAPI.xlua_pushcstable(L, <%=type_info.FieldInfos.Count%>, <%=type_id_var_name%>);
<%ForEachCsList(type_info.FieldInfos, function(fieldInfo)%>
LuaAPI.xlua_pushasciistring(L, "<%=fieldInfo.Name%>");
<%=GetPushStatement(fieldInfo.Type, "val."..fieldInfo.Name)%>;
LuaAPI.lua_rawset(L, -3);
<%end)%>
<%else%>
IntPtr buff = LuaAPI.xlua_pushstruct(L, <%=is_enum and 4 or type_info.Size%>, <%=type_id_var_name%>);
if (!CopyByValue.Pack(buff, 0, <%=is_enum and "(int)" or ""%>val))
{
throw new Exception("pack fail fail for <%=full_type_name%> ,value="+val);
}
<%
end
if is_enum then
%>
LuaAPI.lua_getref(L, <%=enum_ref_var_name%>);
LuaAPI.lua_pushvalue(L, -2);
LuaAPI.xlua_rawseti(L, -2, (int)val);
LuaAPI.lua_pop(L, 1);
<%end%>
}
public void Get(RealStatePtr L, int index, out <%=full_type_name%> val)
{
LuaTypes type = LuaAPI.lua_type(L, index);
if (type == LuaTypes.LUA_TUSERDATA )
{
if (LuaAPI.xlua_gettypeid(L, index) != <%=type_id_var_name%>)
{
throw new Exception("invalid userdata for <%=full_type_name%>");
}
IntPtr buff = LuaAPI.lua_touserdata(L, index);<%if is_enum then%>
int e;
<%end%>if (!CopyByValue.UnPack(buff, 0, out <%=is_enum and "e" or "val"%>))
{
throw new Exception("unpack fail for <%=full_type_name%>");
}<%if is_enum then%>
val = (<%=full_type_name%>)e;
<%end%>
}<%if not is_enum then%>
else if (type ==LuaTypes.LUA_TTABLE)
{
CopyByValue.UnPack(this, L, index, out val);
}<%end%>
else
{
val = (<%=full_type_name%>)objectCasters.GetCaster(typeof(<%=full_type_name%>))(L, index, null);
}
}
public void Update<%=CSVariableName(type_info.Type)%>(RealStatePtr L, int index, <%=full_type_name%> val)
{
<%if type_info.Flag == CS.XLua.OptimizeFlag.PackAsTable then%>
if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TTABLE)
{
return;
}
<%else%>
if (LuaAPI.lua_type(L, index) == LuaTypes.LUA_TUSERDATA)
{
if (LuaAPI.xlua_gettypeid(L, index) != <%=type_id_var_name%>)
{
throw new Exception("invalid userdata for <%=full_type_name%>");
}
IntPtr buff = LuaAPI.lua_touserdata(L, index);
if (!CopyByValue.Pack(buff, 0, <%=is_enum and "(int)" or ""%>val))
{
throw new Exception("pack fail for <%=full_type_name%> ,value="+val);
}
}
<%end%>
else
{
throw new Exception("try to update a data with lua type:" + LuaAPI.lua_type(L, index));
}
}
<%end)%>
// table cast optimze
<%ForEachCsList(tableoptimzetypes, function(type_info)
local full_type_name = CsFullTypeName(type_info.Type)
%>
public void Get(RealStatePtr L, int index, out <%=full_type_name%> val)
{
LuaTypes type = LuaAPI.lua_type(L, index);
if (type == LuaTypes.LUA_TUSERDATA )
{
val = (<%=full_type_name%>)FastGetCSObj(L, index);
}
else if (type == LuaTypes.LUA_TTABLE)
{
val = new <%=full_type_name%>();
int top = LuaAPI.lua_gettop(L);
<%ForEachCsList(type_info.Fields, function(fieldInfo)%>
if (Utils.LoadField(L, index, "<%=fieldInfo.Name%>"))
{
Get(L, top + 1, out val.<%=fieldInfo.Name%>);
}
LuaAPI.lua_pop(L, 1);
<%end)%>
}<%if not type_info.Type.IsValueType then%>
else if (type == LuaTypes.LUA_TNIL || type == LuaTypes.LUA_TNONE)
{
val = null;
}<%end%>
else
{
throw new Exception("can not cast " + LuaAPI.lua_type(L, index) + " to " + typeof(<%=full_type_name%>));
}
}
<%end)%>
}
public partial class StaticLuaCallbacks
{
internal static bool __tryArrayGet(Type type, RealStatePtr L, ObjectTranslator translator, object obj, int index)
{
<%ForEachCsList(purevaluetypes, function(type_info, idx)
if not type_info.Type.IsValueType then return end
local full_type_name = CsFullTypeName(type_info.Type)
%>
<%=(idx == 0 and '' or 'else ')%>if (type == typeof(<%=full_type_name%>[]))
{
<%=full_type_name%>[] array = obj as <%=full_type_name%>[];
translator.Push<%=CSVariableName(type_info.Type)%>(L, array[index]);
return true;
}<%
end)%>
return false;
}
internal static bool __tryArraySet(Type type, RealStatePtr L, ObjectTranslator translator, object obj, int array_idx, int obj_idx)
{
<%
local is_first = true
ForEachCsList(purevaluetypes, tableoptimzetypes, function(type_info)
local full_type_name = CsFullTypeName(type_info.Type)
%>
<%=(is_first and '' or 'else ')%>if (type == typeof(<%=full_type_name%>[]))
{
<%=full_type_name%>[] array = obj as <%=full_type_name%>[];
translator.Get(L, obj_idx, out array[array_idx]);
return true;
}<%
is_first = false
end)%>
return false;
}
}
}

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d1a916469d261d447972d287b6c5b7a0
timeCreated: 1481620508
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,123 @@
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using System;
<%
require "TemplateCommon"
%>
namespace XLua
{
public static partial class CopyByValue
{
<%ForEachCsList(type_infos, function(type_info)
local full_type_name = CsFullTypeName(type_info.Type)
%>
<%if type_info.IsRoot then
ForEachCsList(type_info.FieldInfos, function(fieldInfo) fieldInfo.Name = UnK(fieldInfo.Name) end)
%>
public static void UnPack(ObjectTranslator translator, RealStatePtr L, int idx, out <%=full_type_name%> val)
{
val = new <%=full_type_name%>();
int top = LuaAPI.lua_gettop(L);
<%ForEachCsList(type_info.FieldInfos, function(fieldInfo)%>
if (Utils.LoadField(L, idx, "<%=fieldInfo.Name%>"))
{
<%if fieldInfo.IsField then%>
translator.Get(L, top + 1, out val.<%=fieldInfo.Name%>);
<%else%>
var <%=fieldInfo.Name%> = val.<%=fieldInfo.Name%>;
translator.Get(L, top + 1, out <%=fieldInfo.Name%>);
val.<%=fieldInfo.Name%> = <%=fieldInfo.Name%>;
<%end%>
}
LuaAPI.lua_pop(L, 1);
<%end)%>
}
<%end%>
public static bool Pack(IntPtr buff, int offset, <%=full_type_name%> field)
{
<%
local offset_inner = 0
if not type_info.FieldGroup then
ForEachCsList(type_info.FieldInfos, function(fieldInfo)
%>
if(!Pack(buff, offset<%=(offset_inner == 0 and "" or (" + " .. offset_inner))%>, field.<%=fieldInfo.Name%>))
{
return false;
}
<%
offset_inner = offset_inner + fieldInfo.Size
end)
else
ForEachCsList(type_info.FieldGroup, function(group)
%>
if(!LuaAPI.xlua_pack_float<%=(group.Count == 1 and "" or group.Count)%>(buff, offset<%=(offset_inner == 0 and "" or (" + " .. offset_inner))%><%
ForEachCsList(group, function(fieldInfo, i)
%>, field.<%=fieldInfo.Name%><%
end)
%>))
{
return false;
}
<%
offset_inner = offset_inner + group.Count * 4
end)
end%>
return true;
}
public static bool UnPack(IntPtr buff, int offset, out <%=full_type_name%> field)
{
field = default(<%=full_type_name%>);
<%
local offset_inner = 0
if not type_info.FieldGroup then
ForEachCsList(type_info.FieldInfos, function(fieldInfo)
if fieldInfo.IsField then
%>
if(!UnPack(buff, offset<%=(offset_inner == 0 and "" or (" + " .. offset_inner))%>, out field.<%=fieldInfo.Name%>))
{
return false;
}
<%else%>
var <%=fieldInfo.Name%> = field.<%=fieldInfo.Name%>;
if(!UnPack(buff, offset<%=(offset_inner == 0 and "" or (" + " .. offset_inner))%>, out <%=fieldInfo.Name%>))
{
return false;
}
field.<%=fieldInfo.Name%> = <%=fieldInfo.Name%>;
<%
end
offset_inner = offset_inner + fieldInfo.Size
end)
else
ForEachCsList(type_info.FieldGroup, function(group)
%>
<%ForEachCsList(group, function(fieldInfo)%>float <%=fieldInfo.Name%> = default(float);
<%end)%>
if(!LuaAPI.xlua_unpack_float<%=(group.Count == 1 and "" or group.Count)%>(buff, offset<%=(offset_inner == 0 and "" or (" + " .. offset_inner))%><%
ForEachCsList(group, function(fieldInfo)
%>, out <%=fieldInfo.Name%><%
end)
%>))
{
return false;
}
<%ForEachCsList(group, function(fieldInfo)%>field.<%=fieldInfo.Name%> = <%=fieldInfo.Name%>;
<%end)%>
<%
offset_inner = offset_inner + group.Count * 4
end)
end%>
return true;
}
<%end)%>
}
}

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c9ef7e8f2a3b37744aad49b99370c16b
timeCreated: 1481620508
licenseType: Pro
TextScriptImporter:
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,471 @@
-- Tencent is pleased to support the open source community by making xLua available.
-- Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
-- Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
-- http://opensource.org/licenses/MIT
-- Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
local friendlyNameMap = {
["System.Object"] = "object",
["System.String"] = "string",
["System.Boolean"] = "bool",
["System.Byte"] = "byte",
["System.Char"] = "char",
["System.Decimal"] = "decimal",
["System.Double"] = "double",
["System.Int16"] = "short",
["System.Int32"] = "int",
["System.Int64"] = "long",
["System.SByte"] = "sbyte",
["System.Single"] = "float",
["System.UInt16"] = "ushort",
["System.UInt32"] = "uint",
["System.UInt64"] = "ulong",
["System.Void"] = "void",
}
local csKeywords = {
"abstract", "as", "base", "bool",
"break", "byte", "case", "catch",
"char", "checked", "class", "const",
"continue", "decimal", "default", "delegate",
"do", "double", "else", "enum",
"event", "explicit", "extern", "false",
"finally", "fixed", "float", "for",
"foreach", "goto", "if", "implicit",
"in", "int", "interface",
"internal", "is", "lock", "long",
"namespace", "new", "null", "object",
"operator", "out", "override",
"params", "private", "protected", "public",
"readonly", "ref", "return", "sbyte",
"sealed", "short", "sizeof", "stackalloc",
"static", "string", "struct", "switch",
"this", "throw", "true", "try",
"typeof", "uint", "ulong", "unchecked",
"unsafe", "ushort", "using", "virtual",
"void", "volatile", "while"
}
for _, kw in ipairs(csKeywords) do
csKeywords[kw] = '@'..kw
end
for i = 1, #csKeywords do
csKeywords[i] = nil
end
function UnK(symbol)
return csKeywords[symbol] or symbol
end
local fixChecker = {
--["System.String"] = "LuaAPI.lua_isstring",
["System.Boolean"] = "LuaTypes.LUA_TBOOLEAN == LuaAPI.lua_type",
["System.Byte"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
["System.Char"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
--["System.Decimal"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
["System.Double"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
["System.Int16"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
["System.Int32"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
--["System.Int64"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
["System.SByte"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
["System.Single"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
["System.UInt16"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
["System.UInt32"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
--["System.UInt64"] = "LuaTypes.LUA_TNUMBER == LuaAPI.lua_type",
["System.IntPtr"] = "LuaTypes.LUA_TLIGHTUSERDATA == LuaAPI.lua_type",
}
local typedCaster = {
["System.Byte"] = "LuaAPI.xlua_tointeger",
["System.Char"] = "LuaAPI.xlua_tointeger",
["System.Int16"] = "LuaAPI.xlua_tointeger",
["System.SByte"] = "LuaAPI.xlua_tointeger",
["System.Single"] = "LuaAPI.lua_tonumber",
["System.UInt16"] = "LuaAPI.xlua_tointeger",
}
local fixCaster = {
["System.Double"] = "LuaAPI.lua_tonumber",
["System.String"] = "LuaAPI.lua_tostring",
["System.Boolean"] = "LuaAPI.lua_toboolean",
["System.Byte[]"] = "LuaAPI.lua_tobytes",
["System.IntPtr"] = "LuaAPI.lua_touserdata",
["System.UInt32"] = "LuaAPI.xlua_touint",
["System.UInt64"] = "LuaAPI.lua_touint64",
["System.Int32"] = "LuaAPI.xlua_tointeger",
["System.Int64"] = "LuaAPI.lua_toint64",
}
local fixPush = {
["System.Byte"] = "LuaAPI.xlua_pushinteger",
["System.Char"] = "LuaAPI.xlua_pushinteger",
["System.Int16"] = "LuaAPI.xlua_pushinteger",
["System.Int32"] = "LuaAPI.xlua_pushinteger",
["System.Int64"] = "LuaAPI.lua_pushint64",
["System.SByte"] = "LuaAPI.xlua_pushinteger",
["System.Single"] = "LuaAPI.lua_pushnumber",
["System.UInt16"] = "LuaAPI.xlua_pushinteger",
["System.UInt32"] = "LuaAPI.xlua_pushuint",
["System.UInt64"] = "LuaAPI.lua_pushuint64",
["System.Double"] = "LuaAPI.lua_pushnumber",
["System.String"] = "LuaAPI.lua_pushstring",
["System.Byte[]"] = "LuaAPI.lua_pushstring",
["System.Boolean"] = "LuaAPI.lua_pushboolean",
["System.IntPtr"] = "LuaAPI.lua_pushlightuserdata",
["System.Decimal"] = "translator.PushDecimal",
["System.Object"] = "translator.PushAny",
}
local notranslator = {
["System.Byte"] = true,
["System.Char"] = true,
["System.Int16"] = true,
["System.Int32"] = true,
["System.Int64"] = true,
["System.SByte"] = true,
["System.Single"] = true,
["System.UInt16"] = true,
["System.UInt32"] = true,
["System.UInt64"] = true,
["System.Double"] = true,
["System.String"] = true,
["System.Boolean"] = true,
["System.Void"] = true,
["System.IntPtr"] = true,
["System.Byte[]"] = true,
}
function ForEachCsList(...)
local list_count = select('#', ...) - 1
local callback = select(list_count + 1, ...)
for i = 1, list_count do
local list = select(i, ...)
for i = 0, (list.Count or list.Length) - 1 do
callback(list[i], i)
end
end
end
function CalcCsList(list, predicate)
local count = 0
for i = 0, (list.Count or list.Length) - 1 do
if predicate(list[i], i) then count = count + 1 end
end
return count
end
function IfAny(list, predicate)
for i = 0, (list.Count or list.Length) - 1 do
if predicate(list[i], i) then return true end
end
return false
end
local genPushAndUpdateTypes
function SetGenPushAndUpdateTypes(list)
genPushAndUpdateTypes = {}
ForEachCsList(list, function(t)
genPushAndUpdateTypes[t] = true
end)
end
local xLuaClasses
function SetXLuaClasses(list)
xLuaClasses = {}
ForEachCsList(list, function(t)
xLuaClasses[t.Name] = true
end)
end
local objType = typeof(CS.System.Object)
local valueType = typeof(CS.System.ValueType)
local function _CsFullTypeName(t)
if t.IsArray then
local element_name, element_is_array = _CsFullTypeName(t:GetElementType())
if element_is_array then
local bracket_pos = element_name:find('%[')
return element_name:sub(1, bracket_pos - 1) .. '[' .. string.rep(',', t:GetArrayRank() - 1) .. ']' .. element_name:sub(bracket_pos, -1), true
else
return element_name .. '[' .. string.rep(',', t:GetArrayRank() - 1) .. ']', true
end
elseif t.IsByRef then
return _CsFullTypeName(t:GetElementType())
elseif t.IsGenericParameter then
return (t.BaseType == objType or t.BaseType == valueType) and t.Name or _CsFullTypeName(t.BaseType) --TODO:应该判断是否类型约束
end
local name = t.FullName:gsub("&", ""):gsub("%+", ".")
if not t.IsGenericType then
return friendlyNameMap[name] or name
end
local genericParameter = ""
ForEachCsList(t:GetGenericArguments(), function(at, ati)
if ati ~= 0 then genericParameter = genericParameter .. ', ' end
genericParameter = genericParameter .. _CsFullTypeName(at)
end)
return name:gsub("`%d+", '<' .. genericParameter .. '>'):gsub("%[[^,%]].*", ""), false
end
function CsFullTypeName(t)
if t.DeclaringType then
local name = _CsFullTypeName(t)
local declaringTypeName = _CsFullTypeName(t.DeclaringType);
return xLuaClasses[declaringTypeName] and ("global::" .. name) or name
else
local name = _CsFullTypeName(t)
return xLuaClasses[name] and ("global::" .. name) or name
end
end
function CSVariableName(t)
if t.IsArray then
return CSVariableName(t:GetElementType()) .. '_'.. t:GetArrayRank() ..'_'
end
return t:ToString():gsub("&", ""):gsub("%+", ""):gsub("`", "_"):gsub("%.", ""):gsub("%[", "_"):gsub("%]", "_"):gsub(",", "")
end
local function getSafeFullName(t)
if t == nil then
return ""
end
if t.IsGenericParameter then
return t.BaseType == objType and t.Name or getSafeFullName(t.BaseType)
end
if not t.FullName then return "" end
return t.FullName:gsub("&", "")
end
function GetCheckStatement(t, idx, is_v_params)
local cond_start = is_v_params and "(LuaTypes.LUA_TNONE == LuaAPI.lua_type(L, ".. idx ..") || " or ""
local cond_end = is_v_params and ")" or ""
local testname = getSafeFullName(t)
if testname == "System.String" or testname == "System.Byte[]" then
return cond_start .. "(LuaAPI.lua_isnil(L, " .. idx .. ") || LuaAPI.lua_type(L, ".. idx ..") == LuaTypes.LUA_TSTRING)" .. cond_end
elseif testname == "System.Int64" then
return cond_start .. "(LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, ".. idx ..") || LuaAPI.lua_isint64(L, ".. idx .."))" .. cond_end
elseif testname == "System.UInt64" then
return cond_start .. "(LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, ".. idx ..") || LuaAPI.lua_isuint64(L, ".. idx .."))" .. cond_end
elseif testname == "System.Decimal" then
return cond_start .. "(LuaTypes.LUA_TNUMBER == LuaAPI.lua_type(L, ".. idx ..") || translator.IsDecimal(L, ".. idx .."))" .. cond_end
elseif testname == "XLua.LuaTable" then
return cond_start .. "(LuaAPI.lua_isnil(L, " .. idx .. ") || LuaAPI.lua_type(L, ".. idx ..") == LuaTypes.LUA_TTABLE)" .. cond_end
elseif testname == "XLua.LuaFunction" then
return cond_start .. "(LuaAPI.lua_isnil(L, " .. idx .. ") || LuaAPI.lua_type(L, ".. idx ..") == LuaTypes.LUA_TFUNCTION)" .. cond_end
end
return cond_start .. (fixChecker[testname] or ("translator.Assignable<" .. CsFullTypeName(t).. ">")) .. "(L, ".. idx ..")" .. cond_end
end
local delegateType = typeof(CS.System.Delegate)
local ExtensionAttribute = typeof(CS.System.Runtime.CompilerServices.ExtensionAttribute)
function IsExtensionMethod(method)
return method:IsDefined(ExtensionAttribute, false)
end
function IsDelegate(t)
return delegateType:IsAssignableFrom(t)
end
function MethodParameters(method)
if not IsExtensionMethod(method) then
return method:GetParameters()
else
local parameters = method:GetParameters()
if parameters[0].ParameterType.IsInterface then
return parameters
end
local ret = {}
for i = 1, parameters.Length - 1 do
ret[i - 1] = parameters[i]
end
ret.Length = parameters.Length - 1
return ret
end
end
function IsStruct(t)
if t.IsByRef then t = t:GetElementType() end
return t.IsValueType and not t.IsPrimitive
end
function NeedUpdate(t)
if t.IsByRef then t = t:GetElementType() end
return t.IsValueType and not t.IsPrimitive and not t.IsEnum and t ~= typeof(CS.System.Decimal)
end
function GetCasterStatement(t, idx, var_name, need_declare, is_v_params)
local testname = getSafeFullName(t)
local statement = ""
local is_struct = IsStruct(t)
if need_declare then
statement = CsFullTypeName(t) .. " " .. var_name
if is_struct and not typedCaster[testname] and not fixCaster[testname] then
statement = statement .. ";"
else
statement = statement .. " = "
end
elseif not is_struct then
statement = var_name .. " = "
end
if is_v_params then
return statement .. "translator.GetParams<" .. CsFullTypeName(t:GetElementType()).. ">" .. "(L, ".. idx ..")"
elseif typedCaster[testname] then
return statement .. "(" .. CsFullTypeName(t) .. ")" ..typedCaster[testname] .. "(L, ".. idx ..")"
elseif IsDelegate(t) then
return statement .. "translator.GetDelegate<" .. CsFullTypeName(t).. ">" .. "(L, ".. idx ..")"
elseif fixCaster[testname] then
return statement .. fixCaster[testname] .. "(L, ".. idx ..")"
elseif testname == "System.Object" then
return statement .. "translator.GetObject(L, ".. idx ..", typeof(" .. CsFullTypeName(t) .."))"
elseif is_struct then
return statement .. "translator.Get(L, ".. idx ..", out " .. var_name .. ")"
elseif t.IsGenericParameter and not t.DeclaringMethod then
return statement .. "translator.GetByType<"..t.Name..">(L, ".. idx ..")"
else
return statement .. "("..CsFullTypeName(t)..")translator.GetObject(L, ".. idx ..", typeof(" .. CsFullTypeName(t) .."))"
end
end
local paramsAttriType = typeof(CS.System.ParamArrayAttribute)
function IsParams(pi)
if (not pi.IsDefined) then
return pi.IsParamArray
end
return pi:IsDefined(paramsAttriType, false)
end
local obsoluteAttriType = typeof(CS.System.ObsoleteAttribute)
function IsObsolute(f)
return f:IsDefined(obsoluteAttriType, false)
end
local objectType = typeof(CS.System.Object)
function GetSelfStatement(t)
local fulltypename = CsFullTypeName(t)
local is_struct = IsStruct(t)
if is_struct then
return fulltypename .. " gen_to_be_invoked;translator.Get(L, 1, out gen_to_be_invoked)"
else
if t == objectType then
return "object gen_to_be_invoked = translator.FastGetCSObj(L, 1)"
else
return fulltypename .. " gen_to_be_invoked = (" .. fulltypename .. ")translator.FastGetCSObj(L, 1)"
end
end
end
local GetNullableUnderlyingType = CS.System.Nullable.GetUnderlyingType
function GetPushStatement(t, variable, is_v_params)
if is_v_params then
local item_push = GetPushStatement(t:GetElementType(), variable..'[__gen_i]')
return 'if ('.. variable ..' != null) { for (int __gen_i = 0; __gen_i < ' .. variable .. '.Length; ++__gen_i) ' .. item_push .. '; }'
end
if t.IsByRef then t = t:GetElementType() end
local testname = getSafeFullName(t)
if fixPush[testname] then
return fixPush[testname] .. "(L, ".. variable ..")"
elseif genPushAndUpdateTypes[t] then
return "translator.Push".. CSVariableName(t) .."(L, "..variable..")"
elseif t.IsGenericParameter and not t.DeclaringMethod then
return "translator.PushByType(L, "..variable..")"
elseif t.IsInterface or GetNullableUnderlyingType(t) then
return "translator.PushAny(L, "..variable..")"
else
return "translator.Push(L, "..variable..")"
end
end
function GetUpdateStatement(t, idx, variable)
if t.IsByRef then t = t:GetElementType() end
if typeof(CS.System.Decimal) == t then error('Decimal not update!') end
if genPushAndUpdateTypes[t] then
return "translator.Update".. CSVariableName(t) .."(L, ".. idx ..", "..variable..")"
else
return "translator.Update(L, ".. idx ..", "..variable..")"
end
end
function JustLuaType(t)
return notranslator[getSafeFullName(t)]
end
function CallNeedTranslator(overload, isdelegate)
if not overload.IsStatic and not isdelegate then return true end
local ret_type_name = getSafeFullName(overload.ReturnType)
if not notranslator[ret_type_name] then return true end
local parameters = overload:GetParameters()
return IfAny(overload:GetParameters(), function(parameter)
return IsParams(parameter) or (not notranslator[getSafeFullName(parameter.ParameterType)])
end)
end
function MethodCallNeedTranslator(method)
return IfAny(method.Overloads, function(overload) return CallNeedTranslator(overload) end)
end
function AccessorNeedTranslator(accessor)
return not accessor.IsStatic or not JustLuaType(accessor.Type)
end
function PushObjectNeedTranslator(type_info)
return IfAny(type_info.FieldInfos, function(field_info) return not JustLuaType(field_info.Type) end)
end
local GenericParameterAttributes = CS.System.Reflection.GenericParameterAttributes
local enum_and_op = debug.getmetatable(CS.System.Reflection.BindingFlags.Public).__band
local has_generic_flag = function(f1, f2)
return (f1 ~= GenericParameterAttributes.None) and (enum_and_op(f1, f2) == f2)
end
function GenericArgumentList(type)
local generic_arg_list = ""
local type_constraints = ""
if type.IsGenericTypeDefinition then
generic_arg_list = "<"
local constraints = {}
ForEachCsList(type:GetGenericArguments(), function(generic_arg, gai)
local constraint = {}
if gai ~= 0 then generic_arg_list = generic_arg_list .. ", " end
generic_arg_list = generic_arg_list .. generic_arg.Name
if has_generic_flag(generic_arg.GenericParameterAttributes, GenericParameterAttributes.ReferenceTypeConstraint) then
table.insert(constraint, 'class')
end
if has_generic_flag(generic_arg.GenericParameterAttributes, GenericParameterAttributes.NotNullableValueTypeConstraint) then
table.insert(constraint, 'struct')
end
ForEachCsList(generic_arg:GetGenericParameterConstraints(), function(gpc)
if gpc ~= typeof(CS.System.ValueType) or not has_generic_flag(generic_arg.GenericParameterAttributes, GenericParameterAttributes.NotNullableValueTypeConstraint) then
table.insert(constraint, CsFullTypeName(gpc))
end
end)
if not has_generic_flag(generic_arg.GenericParameterAttributes, GenericParameterAttributes.NotNullableValueTypeConstraint) and has_generic_flag(generic_arg.GenericParameterAttributes, GenericParameterAttributes.DefaultConstructorConstraint) then
table.insert(constraint, 'new()')
end
if #constraint > 0 then
table.insert(constraints, 'where ' .. generic_arg.Name .. ' : ' .. table.concat(constraint, ','))
end
end)
generic_arg_list = generic_arg_list .. ">"
if #constraints > 0 then
type_constraints = table.concat(constraints, ',')
end
end
return generic_arg_list, type_constraints
end
function LocalName(name)
return "_" .. name
end

@ -0,0 +1,4 @@
fileFormatVersion: 2
guid: cb41d53afe75a9443b182e284298feeb
TextScriptImporter:
userData:

@ -0,0 +1,20 @@
using UnityEngine;
using System.Collections;
namespace XLua
{
public class TemplateRef : ScriptableObject
{
public TextAsset LuaClassWrap;
public TextAsset LuaClassWrapGCM;
public TextAsset LuaDelegateBridge;
public TextAsset LuaDelegateWrap;
public TextAsset LuaEnumWrap;
public TextAsset LuaEnumWrapGCM;
public TextAsset LuaInterfaceBridge;
public TextAsset LuaRegister;
public TextAsset LuaRegisterGCM;
public TextAsset LuaWrapPusher;
public TextAsset PackUnpack;
public TextAsset TemplateCommon;
}
}

@ -0,0 +1,25 @@
fileFormatVersion: 2
guid: 4898604144dd928468ddca1af81d58ae
timeCreated: 1501232546
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences:
- LuaClassWrap: {fileID: 4900000, guid: 8503038eabbabe44dac0f5f749d4411a, type: 3}
- LuaClassWrapGCM: {fileID: 4900000, guid: 2bd79d95fd859724283926ad8fa4df30, type: 3}
- LuaDelegateBridge: {fileID: 4900000, guid: 3d992756e2469044484be75f78e4e556, type: 3}
- LuaDelegateWrap: {fileID: 4900000, guid: 33b33e1cd617f794b8c801a32f3b2539, type: 3}
- LuaEnumWrap: {fileID: 4900000, guid: ae16c73aad9a21a44aef65decb7e4928, type: 3}
- LuaEnumWrapGCM: {fileID: 4900000, guid: ea84a5ee7abf8e347a810eb7848add46, type: 3}
- LuaInterfaceBridge: {fileID: 4900000, guid: 7165d08e91378494dadeb10e5338accb,
type: 3}
- LuaRegister: {fileID: 4900000, guid: e416b82ec9fe340458f97cf1e3468ef7, type: 3}
- LuaRegisterGCM: {fileID: 4900000, guid: 46c7366d55afbf1459674448d92c44c8, type: 3}
- LuaWrapPusher: {fileID: 4900000, guid: d1a916469d261d447972d287b6c5b7a0, type: 3}
- PackUnpack: {fileID: 4900000, guid: c9ef7e8f2a3b37744aad49b99370c16b, type: 3}
- TemplateCommon: {fileID: 4900000, guid: cb41d53afe75a9443b182e284298feeb, type: 3}
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,168 @@
/*
* Tencent is pleased to support the open source community by making xLua available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
namespace XLua
{
public enum GenFlag
{
No = 0,
[Obsolete("use GCOptimizeAttribute instead")]
GCOptimize = 1
}
//如果你要生成Lua调用CSharp的代码加这个标签
public class LuaCallCSharpAttribute : Attribute
{
GenFlag flag;
public GenFlag Flag {
get
{
return flag;
}
}
public LuaCallCSharpAttribute(GenFlag flag = GenFlag.No)
{
this.flag = flag;
}
}
//生成CSharp调用Lua加这标签
//[AttributeUsage(AttributeTargets.Delegate | AttributeTargets.Interface)]
public class CSharpCallLuaAttribute : Attribute
{
}
//如果某属性、方法不需要生成,加这个标签
public class BlackListAttribute : Attribute
{
}
[Flags]
public enum OptimizeFlag
{
Default = 0,
PackAsTable = 1
}
//如果想对struct生成免GC代码加这个标签
public class GCOptimizeAttribute : Attribute
{
OptimizeFlag flag;
public OptimizeFlag Flag
{
get
{
return flag;
}
}
public GCOptimizeAttribute(OptimizeFlag flag = OptimizeFlag.Default)
{
this.flag = flag;
}
}
//如果想在反射下使用,加这个标签
public class ReflectionUseAttribute : Attribute
{
}
//只能标注Dictionary<Type, List<string>>的field或者property
public class DoNotGenAttribute : Attribute
{
}
public class AdditionalPropertiesAttribute : Attribute
{
}
[Flags]
public enum HotfixFlag
{
Stateless = 0,
[Obsolete("use xlua.util.state instead!", true)]
Stateful = 1,
ValueTypeBoxing = 2,
IgnoreProperty = 4,
IgnoreNotPublic = 8,
Inline = 16,
IntKey = 32,
AdaptByDelegate = 64,
IgnoreCompilerGenerated = 128,
NoBaseProxy = 256,
}
public class HotfixAttribute : Attribute
{
HotfixFlag flag;
public HotfixFlag Flag
{
get
{
return flag;
}
}
public HotfixAttribute(HotfixFlag e = HotfixFlag.Stateless)
{
flag = e;
}
}
[AttributeUsage(AttributeTargets.Delegate)]
internal class HotfixDelegateAttribute : Attribute
{
}
#if !XLUA_GENERAL
public static class SysGenConfig
{
[GCOptimize]
static List<Type> GCOptimize
{
get
{
return new List<Type>() {
typeof(UnityEngine.Vector2),
typeof(UnityEngine.Vector3),
typeof(UnityEngine.Vector4),
typeof(UnityEngine.Color),
typeof(UnityEngine.Quaternion),
typeof(UnityEngine.Ray),
typeof(UnityEngine.Bounds),
typeof(UnityEngine.Ray2D),
};
}
}
[AdditionalProperties]
static Dictionary<Type, List<string>> AdditionalProperties
{
get
{
return new Dictionary<Type, List<string>>()
{
{ typeof(UnityEngine.Ray), new List<string>() { "origin", "direction" } },
{ typeof(UnityEngine.Ray2D), new List<string>() { "origin", "direction" } },
{ typeof(UnityEngine.Bounds), new List<string>() { "center", "extents" } },
};
}
}
}
#endif
}

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 4455254bac5b6644893ae8183b9eb87c
timeCreated: 1452509750
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,255 @@
/*
* Tencent is pleased to support the open source community by making xLua available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
using System;
using LuaAPI = XLua.LuaDLL.Lua;
namespace XLua {
public partial class DelegateBridge : DelegateBridgeBase {
public void Action() {
#if THREAD_SAFE || HOTFIX_ENABLE
lock(luaEnv.luaEnvLock) {
#endif
var L = luaEnv.L;
int oldTop = LuaAPI.lua_gettop(L);
int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
LuaAPI.lua_getref(L, luaReference);
int error = LuaAPI.lua_pcall(L, 0, 0, errFunc);
if (error != 0)
luaEnv.ThrowExceptionFromError(oldTop);
LuaAPI.lua_settop(L, oldTop);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public void Action<T1>(T1 p1) {
#if THREAD_SAFE || HOTFIX_ENABLE
lock(luaEnv.luaEnvLock) {
#endif
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
LuaAPI.lua_getref(L, luaReference);
translator.PushByType(L, p1);
int error = LuaAPI.lua_pcall(L, 1, 0, errFunc);
if (error != 0)
luaEnv.ThrowExceptionFromError(oldTop);
LuaAPI.lua_settop(L, oldTop);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public void Action<T1, T2>(T1 p1, T2 p2) {
#if THREAD_SAFE || HOTFIX_ENABLE
lock(luaEnv.luaEnvLock) {
#endif
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
LuaAPI.lua_getref(L, luaReference);
translator.PushByType(L, p1);
translator.PushByType(L, p2);
int error = LuaAPI.lua_pcall(L, 2, 0, errFunc);
if (error != 0)
luaEnv.ThrowExceptionFromError(oldTop);
LuaAPI.lua_settop(L, oldTop);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public void Action<T1, T2, T3>(T1 p1, T2 p2, T3 p3) {
#if THREAD_SAFE || HOTFIX_ENABLE
lock(luaEnv.luaEnvLock) {
#endif
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
LuaAPI.lua_getref(L, luaReference);
translator.PushByType(L, p1);
translator.PushByType(L, p2);
translator.PushByType(L, p3);
int error = LuaAPI.lua_pcall(L, 3, 0, errFunc);
if (error != 0)
luaEnv.ThrowExceptionFromError(oldTop);
LuaAPI.lua_settop(L, oldTop);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public void Action<T1, T2, T3, T4>(T1 p1, T2 p2, T3 p3, T4 p4) {
#if THREAD_SAFE || HOTFIX_ENABLE
lock(luaEnv.luaEnvLock) {
#endif
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
LuaAPI.lua_getref(L, luaReference);
translator.PushByType(L, p1);
translator.PushByType(L, p2);
translator.PushByType(L, p3);
translator.PushByType(L, p4);
int error = LuaAPI.lua_pcall(L, 4, 0, errFunc);
if (error != 0)
luaEnv.ThrowExceptionFromError(oldTop);
LuaAPI.lua_settop(L, oldTop);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public TResult Func<TResult>() {
#if THREAD_SAFE || HOTFIX_ENABLE
lock(luaEnv.luaEnvLock) {
#endif
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
LuaAPI.lua_getref(L, luaReference);
int error = LuaAPI.lua_pcall(L, 0, 1, errFunc);
if (error != 0)
luaEnv.ThrowExceptionFromError(oldTop);
TResult ret;
try {
translator.Get(L, -1, out ret);
} catch (Exception e) {
throw e;
} finally {
LuaAPI.lua_settop(L, oldTop);
}
return ret;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public TResult Func<T1, TResult>(T1 p1) {
#if THREAD_SAFE || HOTFIX_ENABLE
lock(luaEnv.luaEnvLock) {
#endif
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
LuaAPI.lua_getref(L, luaReference);
translator.PushByType(L, p1);
int error = LuaAPI.lua_pcall(L, 1, 1, errFunc);
if (error != 0)
luaEnv.ThrowExceptionFromError(oldTop);
TResult ret;
try {
translator.Get(L, -1, out ret);
} catch (Exception e) {
throw e;
} finally {
LuaAPI.lua_settop(L, oldTop);
}
return ret;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public TResult Func<T1, T2, TResult>(T1 p1, T2 p2) {
#if THREAD_SAFE || HOTFIX_ENABLE
lock(luaEnv.luaEnvLock) {
#endif
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
LuaAPI.lua_getref(L, luaReference);
translator.PushByType(L, p1);
translator.PushByType(L, p2);
int error = LuaAPI.lua_pcall(L, 2, 1, errFunc);
if (error != 0)
luaEnv.ThrowExceptionFromError(oldTop);
TResult ret;
try {
translator.Get(L, -1, out ret);
} catch (Exception e) {
throw e;
} finally {
LuaAPI.lua_settop(L, oldTop);
}
return ret;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public TResult Func<T1, T2, T3, TResult>(T1 p1, T2 p2, T3 p3) {
#if THREAD_SAFE || HOTFIX_ENABLE
lock(luaEnv.luaEnvLock) {
#endif
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
LuaAPI.lua_getref(L, luaReference);
translator.PushByType(L, p1);
translator.PushByType(L, p2);
translator.PushByType(L, p3);
int error = LuaAPI.lua_pcall(L, 3, 1, errFunc);
if (error != 0)
luaEnv.ThrowExceptionFromError(oldTop);
TResult ret;
try {
translator.Get(L, -1, out ret);
} catch (Exception e) {
throw e;
} finally {
LuaAPI.lua_settop(L, oldTop);
}
return ret;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public TResult Func<T1, T2, T3, T4, TResult>(T1 p1, T2 p2, T3 p3, T4 p4) {
#if THREAD_SAFE || HOTFIX_ENABLE
lock(luaEnv.luaEnvLock) {
#endif
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
LuaAPI.lua_getref(L, luaReference);
translator.PushByType(L, p1);
translator.PushByType(L, p2);
translator.PushByType(L, p3);
translator.PushByType(L, p4);
int error = LuaAPI.lua_pcall(L, 4, 1, errFunc);
if (error != 0)
luaEnv.ThrowExceptionFromError(oldTop);
TResult ret;
try {
translator.Get(L, -1, out ret);
} catch (Exception e) {
throw e;
} finally {
LuaAPI.lua_settop(L, oldTop);
}
return ret;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
}
}

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 1bd0a3260371756449c4f642cc7ead00
timeCreated: 1537950363
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,69 @@
/*
* Tencent is pleased to support the open source community by making xLua available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using System;
using System.Collections.Generic;
using System.Reflection;
namespace XLua
{
internal partial class InternalGlobals
{
#if !THREAD_SAFE && !HOTFIX_ENABLE
internal static byte[] strBuff = new byte[256];
#endif
internal delegate bool TryArrayGet(Type type, RealStatePtr L, ObjectTranslator translator, object obj, int index);
internal delegate bool TryArraySet(Type type, RealStatePtr L, ObjectTranslator translator, object obj, int array_idx, int obj_idx);
internal static volatile TryArrayGet genTryArrayGetPtr = null;
internal static volatile TryArraySet genTryArraySetPtr = null;
internal static volatile ObjectTranslatorPool objectTranslatorPool = new ObjectTranslatorPool();
internal static volatile int LUA_REGISTRYINDEX = -10000;
internal static volatile Dictionary<string, string> supportOp = new Dictionary<string, string>()
{
{ "op_Addition", "__add" },
{ "op_Subtraction", "__sub" },
{ "op_Multiply", "__mul" },
{ "op_Division", "__div" },
{ "op_Equality", "__eq" },
{ "op_UnaryNegation", "__unm" },
{ "op_LessThan", "__lt" },
{ "op_LessThanOrEqual", "__le" },
{ "op_Modulus", "__mod" },
{ "op_BitwiseAnd", "__band" },
{ "op_BitwiseOr", "__bor" },
{ "op_ExclusiveOr", "__bxor" },
{ "op_OnesComplement", "__bnot" },
{ "op_LeftShift", "__shl" },
{ "op_RightShift", "__shr" },
};
internal static volatile Dictionary<Type, IEnumerable<MethodInfo>> extensionMethodMap = null;
#if GEN_CODE_MINIMIZE
internal static volatile LuaDLL.CSharpWrapperCaller CSharpWrapperCallerPtr = new LuaDLL.CSharpWrapperCaller(StaticLuaCallbacks.CSharpWrapperCallerImpl);
#endif
internal static volatile LuaCSFunction LazyReflectionWrap = new LuaCSFunction(Utils.LazyReflectionCall);
}
}

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: bacb817c6d0b48644892c8dc3cb6cfc1
timeCreated: 1496994941
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

117
Assets/XLua/Src/LuaBase.cs Normal file

@ -0,0 +1,117 @@
/*
* Tencent is pleased to support the open source community by making xLua available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using System;
namespace XLua
{
public abstract class LuaBase : IDisposable
{
protected bool disposed;
protected readonly int luaReference;
protected readonly LuaEnv luaEnv;
#if UNITY_EDITOR || XLUA_GENERAL
protected int _errorFuncRef { get { return luaEnv.errorFuncRef; } }
protected RealStatePtr _L { get { return luaEnv.L; } }
protected ObjectTranslator _translator { get { return luaEnv.translator; } }
#endif
public LuaBase(int reference, LuaEnv luaenv)
{
luaReference = reference;
luaEnv = luaenv;
}
~LuaBase()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public virtual void Dispose(bool disposeManagedResources)
{
if (!disposed)
{
if (luaReference != 0)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
bool is_delegate = this is DelegateBridgeBase;
if (disposeManagedResources)
{
luaEnv.translator.ReleaseLuaBase(luaEnv.L, luaReference, is_delegate);
}
else //will dispse by LuaEnv.GC
{
luaEnv.equeueGCAction(new LuaEnv.GCAction { Reference = luaReference, IsDelegate = is_delegate });
}
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
disposed = true;
}
}
public override bool Equals(object o)
{
if (o != null && this.GetType() == o.GetType())
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
LuaBase rhs = (LuaBase)o;
var L = luaEnv.L;
if (L != rhs.luaEnv.L)
return false;
int top = LuaAPI.lua_gettop(L);
LuaAPI.lua_getref(L, rhs.luaReference);
LuaAPI.lua_getref(L, luaReference);
int equal = LuaAPI.lua_rawequal(L, -1, -2);
LuaAPI.lua_settop(L, top);
return (equal != 0);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
else return false;
}
public override int GetHashCode()
{
LuaAPI.lua_getref(luaEnv.L, luaReference);
var pointer = LuaAPI.lua_topointer(luaEnv.L, -1);
LuaAPI.lua_pop(luaEnv.L, 1);
return pointer.ToInt32();
}
internal virtual void push(RealStatePtr L)
{
LuaAPI.lua_getref(L, luaReference);
}
}
}

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 36f6e0ab03586ce4493d45dbc2a0ff5c
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

599
Assets/XLua/Src/LuaDLL.cs Normal file

@ -0,0 +1,599 @@
/*
* Tencent is pleased to support the open source community by making xLua available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
namespace XLua.LuaDLL
{
using System;
using System.Runtime.InteropServices;
using System.Text;
using XLua;
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN || XLUA_GENERAL || (UNITY_WSA && !UNITY_EDITOR)
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int lua_CSFunction(IntPtr L);
#if GEN_CODE_MINIMIZE
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate int CSharpWrapperCaller(IntPtr L, int funcidx, int top);
#endif
#else
public delegate int lua_CSFunction(IntPtr L);
#if GEN_CODE_MINIMIZE
public delegate int CSharpWrapperCaller(IntPtr L, int funcidx, int top);
#endif
#endif
public partial class Lua
{
#if (UNITY_IPHONE || UNITY_TVOS || UNITY_WEBGL || UNITY_SWITCH) && !UNITY_EDITOR
const string LUADLL = "__Internal";
#else
const string LUADLL = "xlua";
#endif
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr lua_tothread(IntPtr L, int index);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int xlua_get_lib_version();
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_gc(IntPtr L, LuaGCOptions what, int data);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr lua_getupvalue(IntPtr L, int funcindex, int n);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr lua_setupvalue(IntPtr L, int funcindex, int n);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_pushthread(IntPtr L);
public static bool lua_isfunction(IntPtr L, int stackPos)
{
return lua_type(L, stackPos) == LuaTypes.LUA_TFUNCTION;
}
public static bool lua_islightuserdata(IntPtr L, int stackPos)
{
return lua_type(L, stackPos) == LuaTypes.LUA_TLIGHTUSERDATA;
}
public static bool lua_istable(IntPtr L, int stackPos)
{
return lua_type(L, stackPos) == LuaTypes.LUA_TTABLE;
}
public static bool lua_isthread(IntPtr L, int stackPos)
{
return lua_type(L, stackPos) == LuaTypes.LUA_TTHREAD;
}
public static int luaL_error(IntPtr L, string message) //[-0, +1, m]
{
xlua_csharp_str_error(L, message);
return 0;
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_setfenv(IntPtr L, int stackPos);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr luaL_newstate();
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_close(IntPtr L);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] //[-0, +0, m]
public static extern void luaopen_xlua(IntPtr L);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)] //[-0, +0, m]
public static extern void luaL_openlibs(IntPtr L);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern uint xlua_objlen(IntPtr L, int stackPos);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_createtable(IntPtr L, int narr, int nrec);//[-0, +0, m]
public static void lua_newtable(IntPtr L)//[-0, +0, m]
{
lua_createtable(L, 0, 0);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int xlua_getglobal(IntPtr L, string name);//[-1, +0, m]
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int xlua_setglobal(IntPtr L, string name);//[-1, +0, m]
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void xlua_getloaders(IntPtr L);
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern void lua_settop(IntPtr L, int newTop);
public static void lua_pop(IntPtr L, int amount)
{
lua_settop(L, -(amount) - 1);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_insert(IntPtr L, int newTop);
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern void lua_remove(IntPtr L, int index);
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern int lua_rawget(IntPtr L, int index);
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern void lua_rawset(IntPtr L, int index);//[-2, +0, m]
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern int lua_setmetatable(IntPtr L, int objIndex);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_rawequal(IntPtr L, int index1, int index2);
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern void lua_pushvalue(IntPtr L, int index);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_pushcclosure(IntPtr L, IntPtr fn, int n);//[-n, +1, m]
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern void lua_replace(IntPtr L, int index);
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern int lua_gettop(IntPtr L);
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern LuaTypes lua_type(IntPtr L, int index);
public static bool lua_isnil(IntPtr L, int index)
{
return (lua_type(L,index)==LuaTypes.LUA_TNIL);
}
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern bool lua_isnumber(IntPtr L, int index);
public static bool lua_isboolean(IntPtr L, int index)
{
return lua_type(L,index)==LuaTypes.LUA_TBOOLEAN;
}
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern int luaL_ref(IntPtr L, int registryIndex);
public static int luaL_ref(IntPtr L)//[-1, +0, m]
{
return luaL_ref(L,LuaIndexes.LUA_REGISTRYINDEX);
}
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern void xlua_rawgeti(IntPtr L, int tableIndex, long index);
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern void xlua_rawseti(IntPtr L, int tableIndex, long index);//[-1, +0, m]
public static void lua_getref(IntPtr L, int reference)
{
xlua_rawgeti(L,LuaIndexes.LUA_REGISTRYINDEX,reference);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int pcall_prepare(IntPtr L, int error_func_ref, int func_ref);
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern void luaL_unref(IntPtr L, int registryIndex, int reference);
public static void lua_unref(IntPtr L, int reference)
{
luaL_unref(L,LuaIndexes.LUA_REGISTRYINDEX,reference);
}
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern bool lua_isstring(IntPtr L, int index);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool lua_isinteger(IntPtr L, int index);
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern void lua_pushnil(IntPtr L);
public static void lua_pushstdcallcfunction(IntPtr L, lua_CSFunction function, int n = 0)//[-0, +1, m]
{
#if XLUA_GENERAL || (UNITY_WSA && !UNITY_EDITOR)
GCHandle.Alloc(function);
#endif
IntPtr fn = Marshal.GetFunctionPointerForDelegate(function);
xlua_push_csharp_function(L, fn, n);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int xlua_upvalueindex(int n);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int lua_pcall(IntPtr L, int nArgs, int nResults, int errfunc);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern double lua_tonumber(IntPtr L, int index);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int xlua_tointeger(IntPtr L, int index);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern uint xlua_touint(IntPtr L, int index);
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern bool lua_toboolean(IntPtr L, int index);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr lua_topointer(IntPtr L, int index);
[DllImport(LUADLL,CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr lua_tolstring(IntPtr L, int index, out IntPtr strLen);//[-0, +0, m]
public static string lua_tostring(IntPtr L, int index)
{
IntPtr strlen;
IntPtr str = lua_tolstring(L, index, out strlen);
if (str != IntPtr.Zero)
{
#if XLUA_GENERAL || (UNITY_WSA && !UNITY_EDITOR)
int len = strlen.ToInt32();
byte[] buffer = new byte[len];
Marshal.Copy(str, buffer, 0, len);
return Encoding.UTF8.GetString(buffer);
#else
string ret = Marshal.PtrToStringAnsi(str, strlen.ToInt32());
if (ret == null)
{
int len = strlen.ToInt32();
byte[] buffer = new byte[len];
Marshal.Copy(str, buffer, 0, len);
return Encoding.UTF8.GetString(buffer);
}
return ret;
#endif
}
else
{
return null;
}
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr lua_atpanic(IntPtr L, lua_CSFunction panicf);
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern void lua_pushnumber(IntPtr L, double number);
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern void lua_pushboolean(IntPtr L, bool value);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void xlua_pushinteger(IntPtr L, int value);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void xlua_pushuint(IntPtr L, uint value);
#if NATIVE_LUA_PUSHSTRING
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_pushstring(IntPtr L, string str);
#else
public static void lua_pushstring(IntPtr L, string str) //业务使用
{
if (str == null)
{
lua_pushnil(L);
}
else
{
#if !THREAD_SAFE && !HOTFIX_ENABLE
if (Encoding.UTF8.GetByteCount(str) > InternalGlobals.strBuff.Length)
{
byte[] bytes = Encoding.UTF8.GetBytes(str);
xlua_pushlstring(L, bytes, bytes.Length);
}
else
{
int bytes_len = Encoding.UTF8.GetBytes(str, 0, str.Length, InternalGlobals.strBuff, 0);
xlua_pushlstring(L, InternalGlobals.strBuff, bytes_len);
}
#else
var bytes = Encoding.UTF8.GetBytes(str);
xlua_pushlstring(L, bytes, bytes.Length);
#endif
}
}
#endif
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void xlua_pushlstring(IntPtr L, byte[] str, int size);
public static void xlua_pushasciistring(IntPtr L, string str) // for inner use only
{
if (str == null)
{
lua_pushnil(L);
}
else
{
#if NATIVE_LUA_PUSHSTRING
lua_pushstring(L, str);
#else
#if !THREAD_SAFE && !HOTFIX_ENABLE
int str_len = str.Length;
if (InternalGlobals.strBuff.Length < str_len)
{
InternalGlobals.strBuff = new byte[str_len];
}
int bytes_len = Encoding.UTF8.GetBytes(str, 0, str_len, InternalGlobals.strBuff, 0);
xlua_pushlstring(L, InternalGlobals.strBuff, bytes_len);
#else
var bytes = Encoding.UTF8.GetBytes(str);
xlua_pushlstring(L, bytes, bytes.Length);
#endif
#endif
}
}
public static void lua_pushstring(IntPtr L, byte[] str)
{
if (str == null)
{
lua_pushnil(L);
}
else
{
xlua_pushlstring(L, str, str.Length);
}
}
public static byte[] lua_tobytes(IntPtr L, int index)//[-0, +0, m]
{
if (lua_type(L, index) == LuaTypes.LUA_TSTRING)
{
IntPtr strlen;
IntPtr str = lua_tolstring(L, index, out strlen);
if (str != IntPtr.Zero)
{
int buff_len = strlen.ToInt32();
byte[] buffer = new byte[buff_len];
Marshal.Copy(str, buffer, 0, buff_len);
return buffer;
}
}
return null;
}
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern int luaL_newmetatable(IntPtr L, string meta);//[-0, +1, m]
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int xlua_pgettable(IntPtr L, int idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int xlua_psettable(IntPtr L, int idx);
public static void luaL_getmetatable(IntPtr L, string meta)
{
xlua_pushasciistring(L, meta);
lua_rawget(L, LuaIndexes.LUA_REGISTRYINDEX);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int xluaL_loadbuffer(IntPtr L, byte[] buff, int size, string name);
public static int luaL_loadbuffer(IntPtr L, string buff, string name)//[-0, +1, m]
{
byte[] bytes = Encoding.UTF8.GetBytes(buff);
return xluaL_loadbuffer(L, bytes, bytes.Length, name);
}
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern int xlua_tocsobj_safe(IntPtr L,int obj);//[-0, +0, m]
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern int xlua_tocsobj_fast(IntPtr L,int obj);
public static int lua_error(IntPtr L)
{
xlua_csharp_error(L);
return 0;
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool lua_checkstack(IntPtr L,int extra);//[-0, +0, m]
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern int lua_next(IntPtr L,int index);//[-1, +(2|0), e]
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern void lua_pushlightuserdata(IntPtr L, IntPtr udata);
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr xlua_tag();
[DllImport(LUADLL,CallingConvention=CallingConvention.Cdecl)]
public static extern void luaL_where (IntPtr L, int level);//[-0, +1, m]
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int xlua_tryget_cachedud(IntPtr L, int key, int cache_ref);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void xlua_pushcsobj(IntPtr L, int key, int meta_ref, bool need_cache, int cache_ref);//[-0, +1, m]
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]//[,,m]
public static extern int gen_obj_indexer(IntPtr L);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]//[,,m]
public static extern int gen_obj_newindexer(IntPtr L);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]//[,,m]
public static extern int gen_cls_indexer(IntPtr L);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]//[,,m]
public static extern int gen_cls_newindexer(IntPtr L);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]//[,,m]
public static extern int get_error_func_ref(IntPtr L);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]//[,,m]
public static extern int load_error_func(IntPtr L, int Ref);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int luaopen_i64lib(IntPtr L);//[,,m]
#if (!UNITY_SWITCH && !UNITY_WEBGL) || UNITY_EDITOR
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int luaopen_socket_core(IntPtr L);//[,,m]
#endif
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_pushint64(IntPtr L, long n);//[,,m]
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void lua_pushuint64(IntPtr L, ulong n);//[,,m]
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool lua_isint64(IntPtr L, int idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool lua_isuint64(IntPtr L, int idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern long lua_toint64(IntPtr L, int idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern ulong lua_touint64(IntPtr L, int idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void xlua_push_csharp_function(IntPtr L, IntPtr fn, int n);//[-0,+1,m]
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int xlua_csharp_str_error(IntPtr L, string message);//[-0,+1,m]
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]//[-0,+0,m]
public static extern int xlua_csharp_error(IntPtr L);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_pack_int8_t(IntPtr buff, int offset, byte field);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_unpack_int8_t(IntPtr buff, int offset, out byte field);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_pack_int16_t(IntPtr buff, int offset, short field);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_unpack_int16_t(IntPtr buff, int offset, out short field);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_pack_int32_t(IntPtr buff, int offset, int field);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_unpack_int32_t(IntPtr buff, int offset, out int field);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_pack_int64_t(IntPtr buff, int offset, long field);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_unpack_int64_t(IntPtr buff, int offset, out long field);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_pack_float(IntPtr buff, int offset, float field);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_unpack_float(IntPtr buff, int offset, out float field);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_pack_double(IntPtr buff, int offset, double field);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_unpack_double(IntPtr buff, int offset, out double field);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr xlua_pushstruct(IntPtr L, uint size, int meta_ref);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void xlua_pushcstable(IntPtr L, uint field_count, int meta_ref);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr lua_touserdata(IntPtr L, int idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int xlua_gettypeid(IntPtr L, int idx);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int xlua_get_registry_index();
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int xlua_pgettable_bypath(IntPtr L, int idx, string path);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern int xlua_psettable_bypath(IntPtr L, int idx, string path);
//[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
//public static extern void xlua_pushbuffer(IntPtr L, byte[] buff);
//对于Unity仅浮点组成的struct较多这几个api用于优化这类struct
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_pack_float2(IntPtr buff, int offset, float f1, float f2);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_unpack_float2(IntPtr buff, int offset, out float f1, out float f2);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_pack_float3(IntPtr buff, int offset, float f1, float f2, float f3);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_unpack_float3(IntPtr buff, int offset, out float f1, out float f2, out float f3);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_pack_float4(IntPtr buff, int offset, float f1, float f2, float f3, float f4);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_unpack_float4(IntPtr buff, int offset, out float f1, out float f2, out float f3, out float f4);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_pack_float5(IntPtr buff, int offset, float f1, float f2, float f3, float f4, float f5);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_unpack_float5(IntPtr buff, int offset, out float f1, out float f2, out float f3, out float f4, out float f5);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_pack_float6(IntPtr buff, int offset, float f1, float f2, float f3, float f4, float f5, float f6);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_unpack_float6(IntPtr buff, int offset, out float f1, out float f2, out float f3, out float f4, out float f5, out float f6);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_pack_decimal(IntPtr buff, int offset, ref decimal dec);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_unpack_decimal(IntPtr buff, int offset, out byte scale, out byte sign, out int hi32, out ulong lo64);
public static bool xlua_is_eq_str(IntPtr L, int index, string str)
{
return xlua_is_eq_str(L, index, str, str.Length);
}
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern bool xlua_is_eq_str(IntPtr L, int index, string str, int str_len);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr xlua_gl(IntPtr L);
#if GEN_CODE_MINIMIZE
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void xlua_set_csharp_wrapper_caller(IntPtr wrapper);
[DllImport(LUADLL, CallingConvention = CallingConvention.Cdecl)]
public static extern void xlua_push_csharp_wrapper(IntPtr L, int wrapperID);
public static void xlua_set_csharp_wrapper_caller(CSharpWrapperCaller wrapper_caller)
{
#if XLUA_GENERAL || (UNITY_WSA && !UNITY_EDITOR)
GCHandle.Alloc(wrapper);
#endif
xlua_set_csharp_wrapper_caller(Marshal.GetFunctionPointerForDelegate(wrapper_caller));
}
#endif
}
}

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d60cef534e986e849a829838fbeb74b5
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

747
Assets/XLua/Src/LuaEnv.cs Normal file

@ -0,0 +1,747 @@
/*
* Tencent is pleased to support the open source community by making xLua available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
namespace XLua
{
using System;
using System.Collections.Generic;
public class LuaEnv : IDisposable
{
public const string CSHARP_NAMESPACE = "xlua_csharp_namespace";
public const string MAIN_SHREAD = "xlua_main_thread";
internal RealStatePtr rawL;
internal RealStatePtr L
{
get
{
if (rawL == RealStatePtr.Zero)
{
throw new InvalidOperationException("this lua env had disposed!");
}
return rawL;
}
}
private LuaTable _G;
internal ObjectTranslator translator;
internal int errorFuncRef = -1;
#if THREAD_SAFE || HOTFIX_ENABLE
internal /*static*/ object luaLock = new object();
internal object luaEnvLock
{
get
{
return luaLock;
}
}
#endif
const int LIB_VERSION_EXPECT = 105;
public LuaEnv()
{
if (LuaAPI.xlua_get_lib_version() != LIB_VERSION_EXPECT)
{
throw new InvalidProgramException("wrong lib version expect:"
+ LIB_VERSION_EXPECT + " but got:" + LuaAPI.xlua_get_lib_version());
}
#if THREAD_SAFE || HOTFIX_ENABLE
lock(luaEnvLock)
#endif
{
LuaIndexes.LUA_REGISTRYINDEX = LuaAPI.xlua_get_registry_index();
#if GEN_CODE_MINIMIZE
LuaAPI.xlua_set_csharp_wrapper_caller(InternalGlobals.CSharpWrapperCallerPtr);
#endif
// Create State
rawL = LuaAPI.luaL_newstate();
//Init Base Libs
LuaAPI.luaopen_xlua(rawL);
LuaAPI.luaopen_i64lib(rawL);
translator = new ObjectTranslator(this, rawL);
translator.createFunctionMetatable(rawL);
translator.OpenLib(rawL);
ObjectTranslatorPool.Instance.Add(rawL, translator);
LuaAPI.lua_atpanic(rawL, StaticLuaCallbacks.Panic);
#if !XLUA_GENERAL
LuaAPI.lua_pushstdcallcfunction(rawL, StaticLuaCallbacks.Print);
if (0 != LuaAPI.xlua_setglobal(rawL, "print"))
{
throw new Exception("call xlua_setglobal fail!");
}
#endif
//template engine lib register
TemplateEngine.LuaTemplate.OpenLib(rawL);
AddSearcher(StaticLuaCallbacks.LoadBuiltinLib, 2); // just after the preload searcher
AddSearcher(StaticLuaCallbacks.LoadFromCustomLoaders, 3);
#if !XLUA_GENERAL
AddSearcher(StaticLuaCallbacks.LoadFromResource, 4);
AddSearcher(StaticLuaCallbacks.LoadFromStreamingAssetsPath, -1);
#endif
DoString(init_xlua, "Init");
init_xlua = null;
#if (!UNITY_SWITCH && !UNITY_WEBGL) || UNITY_EDITOR
AddBuildin("socket.core", StaticLuaCallbacks.LoadSocketCore);
AddBuildin("socket", StaticLuaCallbacks.LoadSocketCore);
#endif
AddBuildin("CS", StaticLuaCallbacks.LoadCS);
LuaAPI.lua_newtable(rawL); //metatable of indexs and newindexs functions
LuaAPI.xlua_pushasciistring(rawL, "__index");
LuaAPI.lua_pushstdcallcfunction(rawL, StaticLuaCallbacks.MetaFuncIndex);
LuaAPI.lua_rawset(rawL, -3);
LuaAPI.xlua_pushasciistring(rawL, Utils.LuaIndexsFieldName);
LuaAPI.lua_newtable(rawL);
LuaAPI.lua_pushvalue(rawL, -3);
LuaAPI.lua_setmetatable(rawL, -2);
LuaAPI.lua_rawset(rawL, LuaIndexes.LUA_REGISTRYINDEX);
LuaAPI.xlua_pushasciistring(rawL, Utils.LuaNewIndexsFieldName);
LuaAPI.lua_newtable(rawL);
LuaAPI.lua_pushvalue(rawL, -3);
LuaAPI.lua_setmetatable(rawL, -2);
LuaAPI.lua_rawset(rawL, LuaIndexes.LUA_REGISTRYINDEX);
LuaAPI.xlua_pushasciistring(rawL, Utils.LuaClassIndexsFieldName);
LuaAPI.lua_newtable(rawL);
LuaAPI.lua_pushvalue(rawL, -3);
LuaAPI.lua_setmetatable(rawL, -2);
LuaAPI.lua_rawset(rawL, LuaIndexes.LUA_REGISTRYINDEX);
LuaAPI.xlua_pushasciistring(rawL, Utils.LuaClassNewIndexsFieldName);
LuaAPI.lua_newtable(rawL);
LuaAPI.lua_pushvalue(rawL, -3);
LuaAPI.lua_setmetatable(rawL, -2);
LuaAPI.lua_rawset(rawL, LuaIndexes.LUA_REGISTRYINDEX);
LuaAPI.lua_pop(rawL, 1); // pop metatable of indexs and newindexs functions
LuaAPI.xlua_pushasciistring(rawL, MAIN_SHREAD);
LuaAPI.lua_pushthread(rawL);
LuaAPI.lua_rawset(rawL, LuaIndexes.LUA_REGISTRYINDEX);
LuaAPI.xlua_pushasciistring(rawL, CSHARP_NAMESPACE);
if (0 != LuaAPI.xlua_getglobal(rawL, "CS"))
{
throw new Exception("get CS fail!");
}
LuaAPI.lua_rawset(rawL, LuaIndexes.LUA_REGISTRYINDEX);
#if !XLUA_GENERAL && (!UNITY_WSA || UNITY_EDITOR)
translator.Alias(typeof(Type), "System.MonoType");
#endif
if (0 != LuaAPI.xlua_getglobal(rawL, "_G"))
{
throw new Exception("get _G fail!");
}
translator.Get(rawL, -1, out _G);
LuaAPI.lua_pop(rawL, 1);
errorFuncRef = LuaAPI.get_error_func_ref(rawL);
if (initers != null)
{
for (int i = 0; i < initers.Count; i++)
{
initers[i](this, translator);
}
}
translator.CreateArrayMetatable(rawL);
translator.CreateDelegateMetatable(rawL);
translator.CreateEnumerablePairs(rawL);
}
}
private static List<Action<LuaEnv, ObjectTranslator>> initers = null;
public static void AddIniter(Action<LuaEnv, ObjectTranslator> initer)
{
if (initers == null)
{
initers = new List<Action<LuaEnv, ObjectTranslator>>();
}
initers.Add(initer);
}
public LuaTable Global
{
get
{
return _G;
}
}
public T LoadString<T>(byte[] chunk, string chunkName = "chunk", LuaTable env = null)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnvLock)
{
#endif
if (typeof(T) != typeof(LuaFunction) && !typeof(T).IsSubclassOf(typeof(Delegate)))
{
throw new InvalidOperationException(typeof(T).Name + " is not a delegate type nor LuaFunction");
}
var _L = L;
int oldTop = LuaAPI.lua_gettop(_L);
if (LuaAPI.xluaL_loadbuffer(_L, chunk, chunk.Length, chunkName) != 0)
ThrowExceptionFromError(oldTop);
if (env != null)
{
env.push(_L);
LuaAPI.lua_setfenv(_L, -2);
}
T result = (T)translator.GetObject(_L, -1, typeof(T));
LuaAPI.lua_settop(_L, oldTop);
return result;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public T LoadString<T>(string chunk, string chunkName = "chunk", LuaTable env = null)
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(chunk);
return LoadString<T>(bytes, chunkName, env);
}
public LuaFunction LoadString(string chunk, string chunkName = "chunk", LuaTable env = null)
{
return LoadString<LuaFunction>(chunk, chunkName, env);
}
public object[] DoString(byte[] chunk, string chunkName = "chunk", LuaTable env = null)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnvLock)
{
#endif
var _L = L;
int oldTop = LuaAPI.lua_gettop(_L);
int errFunc = LuaAPI.load_error_func(_L, errorFuncRef);
if (LuaAPI.xluaL_loadbuffer(_L, chunk, chunk.Length, chunkName) == 0)
{
if (env != null)
{
env.push(_L);
LuaAPI.lua_setfenv(_L, -2);
}
if (LuaAPI.lua_pcall(_L, 0, -1, errFunc) == 0)
{
LuaAPI.lua_remove(_L, errFunc);
return translator.popValues(_L, oldTop);
}
else
ThrowExceptionFromError(oldTop);
}
else
ThrowExceptionFromError(oldTop);
return null;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public object[] DoString(string chunk, string chunkName = "chunk", LuaTable env = null)
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(chunk);
return DoString(bytes, chunkName, env);
}
private void AddSearcher(LuaCSFunction searcher, int index)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnvLock)
{
#endif
var _L = L;
//insert the loader
LuaAPI.xlua_getloaders(_L);
if (!LuaAPI.lua_istable(_L, -1))
{
throw new Exception("Can not set searcher!");
}
uint len = LuaAPI.xlua_objlen(_L, -1);
index = index < 0 ? (int)(len + index + 2) : index;
for (int e = (int)len + 1; e > index; e--)
{
LuaAPI.xlua_rawgeti(_L, -1, e - 1);
LuaAPI.xlua_rawseti(_L, -2, e);
}
LuaAPI.lua_pushstdcallcfunction(_L, searcher);
LuaAPI.xlua_rawseti(_L, -2, index);
LuaAPI.lua_pop(_L, 1);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public void Alias(Type type, string alias)
{
translator.Alias(type, alias);
}
#if !XLUA_GENERAL
int last_check_point = 0;
int max_check_per_tick = 20;
static bool ObjectValidCheck(object obj)
{
return (!(obj is UnityEngine.Object)) || ((obj as UnityEngine.Object) != null);
}
Func<object, bool> object_valid_checker = new Func<object, bool>(ObjectValidCheck);
#endif
public void Tick()
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnvLock)
{
#endif
var _L = L;
lock (refQueue)
{
while (refQueue.Count > 0)
{
GCAction gca = refQueue.Dequeue();
translator.ReleaseLuaBase(_L, gca.Reference, gca.IsDelegate);
}
}
#if !XLUA_GENERAL
last_check_point = translator.objects.Check(last_check_point, max_check_per_tick, object_valid_checker, translator.reverseMap);
#endif
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
//<2F><><EFBFBD><EFBFBD>API
public void GC()
{
Tick();
}
public LuaTable NewTable()
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnvLock)
{
#endif
var _L = L;
int oldTop = LuaAPI.lua_gettop(_L);
LuaAPI.lua_newtable(_L);
LuaTable returnVal = (LuaTable)translator.GetObject(_L, -1, typeof(LuaTable));
LuaAPI.lua_settop(_L, oldTop);
return returnVal;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
private bool disposed = false;
public void Dispose()
{
FullGc();
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
Dispose(true);
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
}
public virtual void Dispose(bool dispose)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnvLock)
{
#endif
if (disposed) return;
Tick();
if (!translator.AllDelegateBridgeReleased())
{
throw new InvalidOperationException("try to dispose a LuaEnv with C# callback!");
}
ObjectTranslatorPool.Instance.Remove(L);
LuaAPI.lua_close(L);
translator = null;
rawL = IntPtr.Zero;
disposed = true;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public void ThrowExceptionFromError(int oldTop)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnvLock)
{
#endif
object err = translator.GetObject(L, -1);
LuaAPI.lua_settop(L, oldTop);
// A pre-wrapped exception - just rethrow it (stack trace of InnerException will be preserved)
Exception ex = err as Exception;
if (ex != null) throw ex;
// A non-wrapped Lua error (best interpreted as a string) - wrap it and throw it
if (err == null) err = "Unknown Lua Error";
throw new LuaException(err.ToString());
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
internal struct GCAction
{
public int Reference;
public bool IsDelegate;
}
Queue<GCAction> refQueue = new Queue<GCAction>();
internal void equeueGCAction(GCAction action)
{
lock (refQueue)
{
refQueue.Enqueue(action);
}
}
private string init_xlua = @"
local metatable = {}
local rawget = rawget
local setmetatable = setmetatable
local import_type = xlua.import_type
local import_generic_type = xlua.import_generic_type
local load_assembly = xlua.load_assembly
function metatable:__index(key)
local fqn = rawget(self,'.fqn')
fqn = ((fqn and fqn .. '.') or '') .. key
local obj = import_type(fqn)
if obj == nil then
-- It might be an assembly, so we load it too.
obj = { ['.fqn'] = fqn }
setmetatable(obj, metatable)
elseif obj == true then
return rawget(self, key)
end
-- Cache this lookup
rawset(self, key, obj)
return obj
end
function metatable:__newindex()
error('No such type: ' .. rawget(self,'.fqn'), 2)
end
-- A non-type has been called; e.g. foo = System.Foo()
function metatable:__call(...)
local n = select('#', ...)
local fqn = rawget(self,'.fqn')
if n > 0 then
local gt = import_generic_type(fqn, ...)
if gt then
return rawget(CS, gt)
end
end
error('No such type: ' .. fqn, 2)
end
CS = CS or {}
setmetatable(CS, metatable)
typeof = function(t) return t.UnderlyingSystemType end
cast = xlua.cast
if not setfenv or not getfenv then
local function getfunction(level)
local info = debug.getinfo(level + 1, 'f')
return info and info.func
end
function setfenv(fn, env)
if type(fn) == 'number' then fn = getfunction(fn + 1) end
local i = 1
while true do
local name = debug.getupvalue(fn, i)
if name == '_ENV' then
debug.upvaluejoin(fn, i, (function()
return env
end), 1)
break
elseif not name then
break
end
i = i + 1
end
return fn
end
function getfenv(fn)
if type(fn) == 'number' then fn = getfunction(fn + 1) end
local i = 1
while true do
local name, val = debug.getupvalue(fn, i)
if name == '_ENV' then
return val
elseif not name then
break
end
i = i + 1
end
end
end
xlua.hotfix = function(cs, field, func)
if func == nil then func = false end
local tbl = (type(field) == 'table') and field or {[field] = func}
for k, v in pairs(tbl) do
local cflag = ''
if k == '.ctor' then
cflag = '_c'
k = 'ctor'
end
local f = type(v) == 'function' and v or nil
xlua.access(cs, cflag .. '__Hotfix0_'..k, f) -- at least one
pcall(function()
for i = 1, 99 do
xlua.access(cs, cflag .. '__Hotfix'..i..'_'..k, f)
end
end)
end
xlua.private_accessible(cs)
end
xlua.getmetatable = function(cs)
return xlua.metatable_operation(cs)
end
xlua.setmetatable = function(cs, mt)
return xlua.metatable_operation(cs, mt)
end
xlua.setclass = function(parent, name, impl)
impl.UnderlyingSystemType = parent[name].UnderlyingSystemType
rawset(parent, name, impl)
end
local base_mt = {
__index = function(t, k)
local csobj = t['__csobj']
local func = csobj['<>xLuaBaseProxy_'..k]
return function(_, ...)
return func(csobj, ...)
end
end
}
base = function(csobj)
return setmetatable({__csobj = csobj}, base_mt)
end
";
public delegate byte[] CustomLoader(ref string filepath);
internal List<CustomLoader> customLoaders = new List<CustomLoader>();
//loader : CustomLoader<65><72> filepath<74><68><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ref<65><66><EFBFBD>ͣ<EFBFBD><CDA3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>require<72>IJ<EFBFBD><C4B2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ҫ֧<D2AA>ֵ<EFBFBD><D6B5>ԣ<EFBFBD><D4A3><EFBFBD>Ҫ<EFBFBD><D2AA><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʵ·<CAB5><C2B7><EFBFBD><EFBFBD>
// <20><><EFBFBD><EFBFBD>ֵ<EFBFBD><D6B5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>null<6C><6C><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ظ<EFBFBD>Դ<EFBFBD><D4B4><EFBFBD>޺<EFBFBD><DEBA>ʵ<EFBFBD><CAB5>ļ<EFBFBD><C4BC><EFBFBD><EFBFBD><EFBFBD><EFBFBD>򷵻<EFBFBD>UTF8<46><38><EFBFBD><EFBFBD><EFBFBD><EFBFBD>byte[]
public void AddLoader(CustomLoader loader)
{
customLoaders.Add(loader);
}
internal Dictionary<string, LuaCSFunction> buildin_initer = new Dictionary<string, LuaCSFunction>();
public void AddBuildin(string name, LuaCSFunction initer)
{
if (!Utils.IsStaticPInvokeCSFunction(initer))
{
throw new Exception("initer must be static and has MonoPInvokeCallback Attribute!");
}
buildin_initer.Add(name, initer);
}
//The garbage-collector pause controls how long the collector waits before starting a new cycle.
//Larger values make the collector less aggressive. Values smaller than 100 mean the collector
//will not wait to start a new cycle. A value of 200 means that the collector waits for the total
//memory in use to double before starting a new cycle.
public int GcPause
{
get
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnvLock)
{
#endif
int val = LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSETPAUSE, 200);
LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSETPAUSE, val);
return val;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
set
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnvLock)
{
#endif
LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSETPAUSE, value);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
}
//The step multiplier controls the relative speed of the collector relative to memory allocation.
//Larger values make the collector more aggressive but also increase the size of each incremental
//step. Values smaller than 100 make the collector too slow and can result in the collector never
//finishing a cycle. The default, 200, means that the collector runs at "twice" the speed of memory
//allocation.
public int GcStepmul
{
get
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnvLock)
{
#endif
int val = LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSETSTEPMUL, 200);
LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSETSTEPMUL, val);
return val;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
set
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnvLock)
{
#endif
LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSETSTEPMUL, value);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
}
public void FullGc()
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnvLock)
{
#endif
LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCCOLLECT, 0);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public void StopGc()
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnvLock)
{
#endif
LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSTOP, 0);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public void RestartGc()
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnvLock)
{
#endif
LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCRESTART, 0);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public bool GcStep(int data)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnvLock)
{
#endif
return LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCSTEP, data) != 0;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public int Memroy
{
get
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnvLock)
{
#endif
return LuaAPI.lua_gc(L, LuaGCOptions.LUA_GCCOUNT, 0);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
}
}
}

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1a72df23459239b4d901cdacabd469d1
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

@ -0,0 +1,19 @@
/*
* Tencent is pleased to support the open source community by making xLua available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
using System;
namespace XLua
{
[Serializable]
public class LuaException : Exception
{
public LuaException(string message) : base(message)
{}
}
}

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: b209468b680ef7d4195de21a39bfcae0
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

@ -0,0 +1,235 @@
/*
* Tencent is pleased to support the open source community by making xLua available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using System;
using System.Collections.Generic;
namespace XLua
{
public partial class LuaFunction : LuaBase
{
public LuaFunction(int reference, LuaEnv luaenv) : base(reference, luaenv)
{
}
//Action和Func是方便使用的无gc api如果需要用到outref参数建议使用delegate
//如果需要其它个数的Action和Func 这个类声明为partial可以自己加
public void Action<T>(T a)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
LuaAPI.lua_getref(L, luaReference);
translator.PushByType(L, a);
int error = LuaAPI.lua_pcall(L, 1, 0, errFunc);
if (error != 0)
luaEnv.ThrowExceptionFromError(oldTop);
LuaAPI.lua_settop(L, oldTop);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public TResult Func<T, TResult>(T a)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
LuaAPI.lua_getref(L, luaReference);
translator.PushByType(L, a);
int error = LuaAPI.lua_pcall(L, 1, 1, errFunc);
if (error != 0)
luaEnv.ThrowExceptionFromError(oldTop);
TResult ret;
try
{
translator.Get(L, -1, out ret);
}
catch (Exception e)
{
throw e;
}
finally
{
LuaAPI.lua_settop(L, oldTop);
}
return ret;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public void Action<T1, T2>(T1 a1, T2 a2)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
LuaAPI.lua_getref(L, luaReference);
translator.PushByType(L, a1);
translator.PushByType(L, a2);
int error = LuaAPI.lua_pcall(L, 2, 0, errFunc);
if (error != 0)
luaEnv.ThrowExceptionFromError(oldTop);
LuaAPI.lua_settop(L, oldTop);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public TResult Func<T1, T2, TResult>(T1 a1, T2 a2)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
LuaAPI.lua_getref(L, luaReference);
translator.PushByType(L, a1);
translator.PushByType(L, a2);
int error = LuaAPI.lua_pcall(L, 2, 1, errFunc);
if (error != 0)
luaEnv.ThrowExceptionFromError(oldTop);
TResult ret;
try
{
translator.Get(L, -1, out ret);
}
catch (Exception e)
{
throw e;
}
finally
{
LuaAPI.lua_settop(L, oldTop);
}
return ret;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
//deprecated
public object[] Call(object[] args, Type[] returnTypes)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
int nArgs = 0;
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
int errFunc = LuaAPI.load_error_func(L, luaEnv.errorFuncRef);
LuaAPI.lua_getref(L, luaReference);
if (args != null)
{
nArgs = args.Length;
for (int i = 0; i < args.Length; i++)
{
translator.PushAny(L, args[i]);
}
}
int error = LuaAPI.lua_pcall(L, nArgs, -1, errFunc);
if (error != 0)
luaEnv.ThrowExceptionFromError(oldTop);
LuaAPI.lua_remove(L, errFunc);
if (returnTypes != null)
return translator.popValues(L, oldTop, returnTypes);
else
return translator.popValues(L, oldTop);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
//deprecated
public object[] Call(params object[] args)
{
return Call(args, null);
}
public T Cast<T>()
{
if (!typeof(T).IsSubclassOf(typeof(Delegate)))
{
throw new InvalidOperationException(typeof(T).Name + " is not a delegate type");
}
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
var L = luaEnv.L;
var translator = luaEnv.translator;
push(L);
T ret = (T)translator.GetObject(L, -1, typeof(T));
LuaAPI.lua_pop(luaEnv.L, 1);
return ret;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public void SetEnv(LuaTable env)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
var L = luaEnv.L;
int oldTop = LuaAPI.lua_gettop(L);
push(L);
env.push(L);
LuaAPI.lua_setfenv(L, -2);
LuaAPI.lua_settop(L, oldTop);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
internal override void push(RealStatePtr L)
{
LuaAPI.lua_getref(L, luaReference);
}
public override string ToString()
{
return "function :" + luaReference;
}
}
}

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 7c45cd490d853cb409d042c641784718
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

390
Assets/XLua/Src/LuaTable.cs Normal file

@ -0,0 +1,390 @@
/*
* Tencent is pleased to support the open source community by making xLua available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
namespace XLua
{
public partial class LuaTable : LuaBase
{
public LuaTable(int reference, LuaEnv luaenv) : base(reference, luaenv)
{
}
// no boxing version get
public void Get<TKey, TValue>(TKey key, out TValue value)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
LuaAPI.lua_getref(L, luaReference);
translator.PushByType(L, key);
if (0 != LuaAPI.xlua_pgettable(L, -2))
{
string err = LuaAPI.lua_tostring(L, -1);
LuaAPI.lua_settop(L, oldTop);
throw new Exception("get field [" + key + "] error:" + err);
}
LuaTypes lua_type = LuaAPI.lua_type(L, -1);
Type type_of_value = typeof(TValue);
if (lua_type == LuaTypes.LUA_TNIL && type_of_value.IsValueType())
{
throw new InvalidCastException("can not assign nil to " + type_of_value.GetFriendlyName());
}
try
{
translator.Get(L, -1, out value);
}
catch (Exception e)
{
throw e;
}
finally
{
LuaAPI.lua_settop(L, oldTop);
}
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
// no boxing version get
public bool ContainsKey<TKey>(TKey key)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
LuaAPI.lua_getref(L, luaReference);
translator.PushByType(L, key);
if (0 != LuaAPI.xlua_pgettable(L, -2))
{
string err = LuaAPI.lua_tostring(L, -1);
LuaAPI.lua_settop(L, oldTop);
throw new Exception("get field [" + key + "] error:" + err);
}
bool ret = LuaAPI.lua_type(L, -1) != LuaTypes.LUA_TNIL;
LuaAPI.lua_settop(L, oldTop);
return ret;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
//no boxing version set
public void Set<TKey, TValue>(TKey key, TValue value)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
var L = luaEnv.L;
int oldTop = LuaAPI.lua_gettop(L);
var translator = luaEnv.translator;
LuaAPI.lua_getref(L, luaReference);
translator.PushByType(L, key);
translator.PushByType(L, value);
if (0 != LuaAPI.xlua_psettable(L, -3))
{
luaEnv.ThrowExceptionFromError(oldTop);
}
LuaAPI.lua_settop(L, oldTop);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public T GetInPath<T>(string path)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
LuaAPI.lua_getref(L, luaReference);
if (0 != LuaAPI.xlua_pgettable_bypath(L, -1, path))
{
luaEnv.ThrowExceptionFromError(oldTop);
}
LuaTypes lua_type = LuaAPI.lua_type(L, -1);
if (lua_type == LuaTypes.LUA_TNIL && typeof(T).IsValueType())
{
throw new InvalidCastException("can not assign nil to " + typeof(T).GetFriendlyName());
}
T value;
try
{
translator.Get(L, -1, out value);
}
catch (Exception e)
{
throw e;
}
finally
{
LuaAPI.lua_settop(L, oldTop);
}
return value;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public void SetInPath<T>(string path, T val)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
var L = luaEnv.L;
int oldTop = LuaAPI.lua_gettop(L);
LuaAPI.lua_getref(L, luaReference);
luaEnv.translator.PushByType(L, val);
if (0 != LuaAPI.xlua_psettable_bypath(L, -2, path))
{
luaEnv.ThrowExceptionFromError(oldTop);
}
LuaAPI.lua_settop(L, oldTop);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
[Obsolete("use no boxing version: GetInPath/SetInPath Get/Set instead!")]
public object this[string field]
{
get
{
return GetInPath<object>(field);
}
set
{
SetInPath(field, value);
}
}
[Obsolete("use no boxing version: GetInPath/SetInPath Get/Set instead!")]
public object this[object field]
{
get
{
return Get<object>(field);
}
set
{
Set(field, value);
}
}
public void ForEach<TKey, TValue>(Action<TKey, TValue> action)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
try
{
LuaAPI.lua_getref(L, luaReference);
LuaAPI.lua_pushnil(L);
while (LuaAPI.lua_next(L, -2) != 0)
{
if (translator.Assignable<TKey>(L, -2))
{
TKey key;
TValue val;
translator.Get(L, -2, out key);
translator.Get(L, -1, out val);
action(key, val);
}
LuaAPI.lua_pop(L, 1);
}
}
finally
{
LuaAPI.lua_settop(L, oldTop);
}
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public int Length
{
get
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
var L = luaEnv.L;
int oldTop = LuaAPI.lua_gettop(L);
LuaAPI.lua_getref(L, luaReference);
var len = (int)LuaAPI.xlua_objlen(L, -1);
LuaAPI.lua_settop(L, oldTop);
return len;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
}
#if THREAD_SAFE || HOTFIX_ENABLE
[Obsolete("not thread safe!", true)]
#endif
public IEnumerable GetKeys()
{
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
try
{
LuaAPI.lua_getref(L, luaReference);
LuaAPI.lua_pushnil(L);
while (LuaAPI.lua_next(L, -2) != 0)
{
yield return translator.GetObject(L, -2);
LuaAPI.lua_pop(L, 1);
}
}
finally
{
LuaAPI.lua_settop(L, oldTop);
}
}
#if THREAD_SAFE || HOTFIX_ENABLE
[Obsolete("not thread safe!", true)]
#endif
public IEnumerable<T> GetKeys<T>()
{
var L = luaEnv.L;
var translator = luaEnv.translator;
int oldTop = LuaAPI.lua_gettop(L);
try
{
LuaAPI.lua_getref(L, luaReference);
LuaAPI.lua_pushnil(L);
while (LuaAPI.lua_next(L, -2) != 0)
{
if (translator.Assignable<T>(L, -2))
{
T v;
translator.Get(L, -2, out v);
yield return v;
}
LuaAPI.lua_pop(L, 1);
}
}
finally
{
LuaAPI.lua_settop(L, oldTop);
}
}
[Obsolete("use no boxing version: Get<TKey, TValue> !")]
public T Get<T>(object key)
{
T ret;
Get(key, out ret);
return ret;
}
public TValue Get<TKey, TValue>(TKey key)
{
TValue ret;
Get(key, out ret);
return ret;
}
public TValue Get<TValue>(string key)
{
TValue ret;
Get(key, out ret);
return ret;
}
public void SetMetaTable(LuaTable metaTable)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
push(luaEnv.L);
metaTable.push(luaEnv.L);
LuaAPI.lua_setmetatable(luaEnv.L, -2);
LuaAPI.lua_pop(luaEnv.L, 1);
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
public T Cast<T>()
{
var L = luaEnv.L;
var translator = luaEnv.translator;
#if THREAD_SAFE || HOTFIX_ENABLE
lock (luaEnv.luaEnvLock)
{
#endif
push(L);
T ret = (T)translator.GetObject(L, -1, typeof(T));
LuaAPI.lua_pop(luaEnv.L, 1);
return ret;
#if THREAD_SAFE || HOTFIX_ENABLE
}
#endif
}
internal override void push(RealStatePtr L)
{
LuaAPI.lua_getref(L, luaReference);
}
public override string ToString()
{
return "table :" + luaReference;
}
}
}

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3a4d72d338110544b8538c1a5fd33c11
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

@ -0,0 +1,583 @@
/*
* Tencent is pleased to support the open source community by making xLua available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using System.Collections.Generic;
using System;
using System.Reflection;
namespace XLua
{
public class OverloadMethodWrap
{
ObjectTranslator translator;
Type targetType;
MethodBase method;
ObjectCheck[] checkArray;
ObjectCast[] castArray;
int[] inPosArray;
int[] outPosArray;
bool[] isOptionalArray;
object[] defaultValueArray;
bool isVoid = true;
int luaStackPosStart = 1;
bool targetNeeded = false;
object[] args;
int[] refPos;
Type paramsType = null;
public bool HasDefalutValue{ get; private set; }
public OverloadMethodWrap(ObjectTranslator translator, Type targetType, MethodBase method)
{
this.translator = translator;
this.targetType = targetType;
this.method = method;
HasDefalutValue = false;
}
public void Init(ObjectCheckers objCheckers, ObjectCasters objCasters)
{
if ((typeof(Delegate) != targetType && typeof(Delegate).IsAssignableFrom(targetType)) ||
!method.IsStatic || method.IsConstructor)
{
luaStackPosStart = 2;
if (!method.IsConstructor)
{
targetNeeded = true;
}
}
var paramInfos = method.GetParameters();
refPos = new int[paramInfos.Length];
List<int> inPosList = new List<int>();
List<int> outPosList = new List<int>();
List<ObjectCheck> paramsChecks = new List<ObjectCheck>();
List<ObjectCast> paramsCasts = new List<ObjectCast>();
List<bool> isOptionalList = new List<bool>();
List<object> defaultValueList = new List<object>();
for(int i = 0; i < paramInfos.Length; i++)
{
refPos[i] = -1;
if (!paramInfos[i].IsIn && paramInfos[i].IsOut) // out parameter
{
outPosList.Add(i);
}
else
{
if(paramInfos[i].ParameterType.IsByRef)
{
var ttype = paramInfos[i].ParameterType.GetElementType();
if(CopyByValue.IsStruct(ttype) && ttype != typeof(decimal))
{
refPos[i] = inPosList.Count;
}
outPosList.Add(i);
}
inPosList.Add(i);
var paramType = paramInfos[i].IsDefined(typeof(ParamArrayAttribute), false) || (!paramInfos[i].ParameterType.IsArray && paramInfos[i].ParameterType.IsByRef ) ?
paramInfos[i].ParameterType.GetElementType() : paramInfos[i].ParameterType;
paramsChecks.Add (objCheckers.GetChecker(paramType));
paramsCasts.Add (objCasters.GetCaster(paramType));
isOptionalList.Add(paramInfos[i].IsOptional);
var defalutValue = paramInfos[i].DefaultValue;
if (paramInfos[i].IsOptional)
{
if (defalutValue != null && defalutValue.GetType() != paramInfos[i].ParameterType)
{
defalutValue = defalutValue.GetType() == typeof(Missing) ? (paramInfos[i].ParameterType.IsValueType() ? Activator.CreateInstance(paramInfos[i].ParameterType) : Missing.Value)
: Convert.ChangeType(defalutValue, paramInfos[i].ParameterType);
}
HasDefalutValue = true;
}
defaultValueList.Add(paramInfos[i].IsOptional ? defalutValue : null);
}
}
checkArray = paramsChecks.ToArray();
castArray = paramsCasts.ToArray();
inPosArray = inPosList.ToArray();
outPosArray = outPosList.ToArray();
isOptionalArray = isOptionalList.ToArray();
defaultValueArray = defaultValueList.ToArray();
if (paramInfos.Length > 0 && paramInfos[paramInfos.Length - 1].IsDefined(typeof(ParamArrayAttribute), false))
{
paramsType = paramInfos[paramInfos.Length - 1].ParameterType.GetElementType();
}
args = new object[paramInfos.Length];
if (method is MethodInfo) //constructor is not MethodInfo?
{
isVoid = (method as MethodInfo).ReturnType == typeof(void);
}
else if(method is ConstructorInfo)
{
isVoid = false;
}
}
public bool Check(RealStatePtr L)
{
int luaTop = LuaAPI.lua_gettop(L);
int luaStackPos = luaStackPosStart;
for(int i = 0; i < checkArray.Length; i++)
{
if ((i == (checkArray.Length - 1)) && (paramsType != null))
{
break;
}
if(luaStackPos > luaTop && !isOptionalArray[i])
{
return false;
}
else if(luaStackPos <= luaTop && !checkArray[i](L, luaStackPos))
{
return false;
}
if (luaStackPos <= luaTop || !isOptionalArray[i])
{
luaStackPos++;
}
}
return paramsType != null ? (luaStackPos < luaTop + 1 ?
checkArray[checkArray.Length - 1](L, luaStackPos) : true) : luaStackPos == luaTop + 1;
}
public int Call(RealStatePtr L)
{
try
{
#if UNITY_EDITOR && !DISABLE_OBSOLETE_WARNING
if (method.IsDefined(typeof(ObsoleteAttribute), true))
{
ObsoleteAttribute info = Attribute.GetCustomAttribute(method, typeof(ObsoleteAttribute)) as ObsoleteAttribute;
UnityEngine.Debug.LogWarning("Obsolete Method [" + method.DeclaringType.ToString() + "." + method.Name + "]: " + info.Message);
}
#endif
object target = null;
MethodBase toInvoke = method;
if (luaStackPosStart > 1)
{
target = translator.FastGetCSObj(L, 1);
if (target is Delegate)
{
Delegate delegateInvoke = (Delegate)target;
#if UNITY_WSA && !UNITY_EDITOR
toInvoke = delegateInvoke.GetMethodInfo();
#else
toInvoke = delegateInvoke.Method;
#endif
}
}
int luaTop = LuaAPI.lua_gettop(L);
int luaStackPos = luaStackPosStart;
for (int i = 0; i < castArray.Length; i++)
{
//UnityEngine.Debug.Log("inPos:" + inPosArray[i]);
if (luaStackPos > luaTop) //after check
{
if (paramsType != null && i == castArray.Length - 1)
{
args[inPosArray[i]] = Array.CreateInstance(paramsType, 0);
}
else
{
args[inPosArray[i]] = defaultValueArray[i];
}
}
else
{
if (paramsType != null && i == castArray.Length - 1)
{
args[inPosArray[i]] = translator.GetParams(L, luaStackPos, paramsType);
}
else
{
args[inPosArray[i]] = castArray[i](L, luaStackPos, null);
}
luaStackPos++;
}
//UnityEngine.Debug.Log("value:" + args[inPosArray[i]]);
}
object ret = null;
ret = toInvoke.IsConstructor ? ((ConstructorInfo)method).Invoke(args) : method.Invoke(targetNeeded ? target : null, args);
if (targetNeeded && targetType.IsValueType())
{
translator.Update(L, 1, target);
}
int nRet = 0;
if (!isVoid)
{
//UnityEngine.Debug.Log(toInvoke.ToString() + " ret:" + ret);
translator.PushAny(L, ret);
nRet++;
}
for (int i = 0; i < outPosArray.Length; i++)
{
if (refPos[outPosArray[i]] != -1)
{
translator.Update(L, luaStackPosStart + refPos[outPosArray[i]], args[outPosArray[i]]);
}
translator.PushAny(L, args[outPosArray[i]]);
nRet++;
}
return nRet;
}
finally
{
for(int i = 0; i < args.Length; i++)
{
args[i] = null;
}
}
}
}
public class MethodWrap
{
private string methodName;
private List<OverloadMethodWrap> overloads = new List<OverloadMethodWrap>();
private bool forceCheck;
public MethodWrap(string methodName, List<OverloadMethodWrap> overloads, bool forceCheck)
{
this.methodName = methodName;
this.overloads = overloads;
this.forceCheck = forceCheck;
}
public int Call(RealStatePtr L)
{
try
{
if (overloads.Count == 1 && !overloads[0].HasDefalutValue && !forceCheck) return overloads[0].Call(L);
for (int i = 0; i < overloads.Count; ++i)
{
var overload = overloads[i];
if (overload.Check(L))
{
return overload.Call(L);
}
}
return LuaAPI.luaL_error(L, "invalid arguments to " + methodName);
}
catch (System.Reflection.TargetInvocationException e)
{
return LuaAPI.luaL_error(L, "c# exception:" + e.InnerException.Message + ",stack:" + e.InnerException.StackTrace);
}
catch (System.Exception e)
{
return LuaAPI.luaL_error(L, "c# exception:" + e.Message + ",stack:" + e.StackTrace);
}
}
}
public class MethodWrapsCache
{
ObjectTranslator translator;
ObjectCheckers objCheckers;
ObjectCasters objCasters;
Dictionary<Type, LuaCSFunction> constructorCache = new Dictionary<Type, LuaCSFunction>();
Dictionary<Type, Dictionary<string, LuaCSFunction>> methodsCache = new Dictionary<Type, Dictionary<string, LuaCSFunction>>();
Dictionary<Type, LuaCSFunction> delegateCache = new Dictionary<Type, LuaCSFunction>();
public MethodWrapsCache(ObjectTranslator translator, ObjectCheckers objCheckers, ObjectCasters objCasters)
{
this.translator = translator;
this.objCheckers = objCheckers;
this.objCasters = objCasters;
}
public LuaCSFunction GetConstructorWrap(Type type)
{
//UnityEngine.Debug.LogWarning("GetConstructor:" + type);
if (!constructorCache.ContainsKey(type))
{
var constructors = type.GetConstructors();
if (type.IsAbstract() || constructors == null || constructors.Length == 0)
{
if (type.IsValueType())
{
constructorCache[type] = (L) =>
{
translator.PushAny(L, Activator.CreateInstance(type));
return 1;
};
}
else
{
return null;
}
}
else
{
LuaCSFunction ctor = _GenMethodWrap(type, ".ctor", constructors, true).Call;
if (type.IsValueType())
{
bool hasZeroParamsCtor = false;
for (int i = 0; i < constructors.Length; i++)
{
if (constructors[i].GetParameters().Length == 0)
{
hasZeroParamsCtor = true;
break;
}
}
if (hasZeroParamsCtor)
{
constructorCache[type] = ctor;
}
else
{
constructorCache[type] = (L) =>
{
if (LuaAPI.lua_gettop(L) == 1)
{
translator.PushAny(L, Activator.CreateInstance(type));
return 1;
}
else
{
return ctor(L);
}
};
}
}
else
{
constructorCache[type] = ctor;
}
}
}
return constructorCache[type];
}
public LuaCSFunction GetMethodWrap(Type type, string methodName)
{
//UnityEngine.Debug.LogWarning("GetMethodWrap:" + type + " " + methodName);
if (!methodsCache.ContainsKey(type))
{
methodsCache[type] = new Dictionary<string, LuaCSFunction>();
}
var methodsOfType = methodsCache[type];
if (!methodsOfType.ContainsKey(methodName))
{
MemberInfo[] methods = type.GetMember(methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
if (methods == null || methods.Length == 0 ||
#if UNITY_WSA && !UNITY_EDITOR
methods[0] is MethodBase
#else
methods[0].MemberType != MemberTypes.Method
#endif
)
{
return null;
}
methodsOfType[methodName] = _GenMethodWrap(type, methodName, methods).Call;
}
return methodsOfType[methodName];
}
public LuaCSFunction GetMethodWrapInCache(Type type, string methodName)
{
//string retriKey = type.ToString() + "." + methodName;
//return methodsCache.ContainsKey(retriKey) ? methodsCache[retriKey] : null;
if (!methodsCache.ContainsKey(type))
{
methodsCache[type] = new Dictionary<string, LuaCSFunction>();
}
var methodsOfType = methodsCache[type];
return methodsOfType.ContainsKey(methodName) ? methodsOfType[methodName] : null;
}
public LuaCSFunction GetDelegateWrap(Type type)
{
//UnityEngine.Debug.LogWarning("GetDelegateWrap:" + type );
if (!typeof(Delegate).IsAssignableFrom(type))
{
return null;
}
if (!delegateCache.ContainsKey(type))
{
delegateCache[type] = _GenMethodWrap(type, type.ToString(), new MethodBase[] { type.GetMethod("Invoke") }).Call;
}
return delegateCache[type];
}
public LuaCSFunction GetEventWrap(Type type, string eventName)
{
if (!methodsCache.ContainsKey(type))
{
methodsCache[type] = new Dictionary<string, LuaCSFunction>();
}
var methodsOfType = methodsCache[type];
if (!methodsOfType.ContainsKey(eventName))
{
{
EventInfo eventInfo = type.GetEvent(eventName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.NonPublic);
if (eventInfo == null)
{
throw new Exception(type.Name + " has no event named: " + eventName);
}
int start_idx = 0;
MethodInfo add = eventInfo.GetAddMethod(true);
MethodInfo remove = eventInfo.GetRemoveMethod(true);
if (add == null && remove == null)
{
throw new Exception(type.Name + "'s " + eventName + " has either add nor remove");
}
bool is_static = add != null ? add.IsStatic : remove.IsStatic;
if (!is_static) start_idx = 1;
methodsOfType[eventName] = (L) =>
{
object obj = null;
if (!is_static)
{
obj = translator.GetObject(L, 1, type);
if (obj == null)
{
return LuaAPI.luaL_error(L, "invalid #1, needed:" + type);
}
}
try
{
object handlerDelegate = translator.CreateDelegateBridge(L, eventInfo.EventHandlerType, start_idx + 2);
if (handlerDelegate == null)
{
return LuaAPI.luaL_error(L, "invalid #" + (start_idx + 2) + ", needed:" + eventInfo.EventHandlerType);
}
switch (LuaAPI.lua_tostring(L, start_idx + 1))
{
case "+":
if (add == null)
{
return LuaAPI.luaL_error(L, "no add for event " + eventName);
}
add.Invoke(obj, new object[] { handlerDelegate });
break;
case "-":
if (remove == null)
{
return LuaAPI.luaL_error(L, "no remove for event " + eventName);
}
remove.Invoke(obj, new object[] { handlerDelegate });
break;
default:
return LuaAPI.luaL_error(L, "invalid #" + (start_idx + 1) + ", needed: '+' or '-'" + eventInfo.EventHandlerType);
}
}
catch (System.Exception e)
{
return LuaAPI.luaL_error(L, "c# exception:" + e + ",stack:" + e.StackTrace);
}
return 0;
};
}
}
return methodsOfType[eventName];
}
public MethodWrap _GenMethodWrap(Type type, string methodName, IEnumerable<MemberInfo> methodBases, bool forceCheck = false)
{
List<OverloadMethodWrap> overloads = new List<OverloadMethodWrap>();
foreach(var methodBase in methodBases)
{
var mb = methodBase as MethodBase;
if (mb == null)
continue;
if (mb.IsGenericMethodDefinition
#if !ENABLE_IL2CPP
&& !tryMakeGenericMethod(ref mb)
#endif
)
continue;
var overload = new OverloadMethodWrap(translator, type, mb);
overload.Init(objCheckers, objCasters);
overloads.Add(overload);
}
return new MethodWrap(methodName, overloads, forceCheck);
}
private static bool tryMakeGenericMethod(ref MethodBase method)
{
try
{
if (!(method is MethodInfo) || !Utils.IsSupportedMethod(method as MethodInfo) )
{
return false;
}
var genericArguments = method.GetGenericArguments();
var constraintedArgumentTypes = new Type[genericArguments.Length];
for (var i = 0; i < genericArguments.Length; i++)
{
var argumentType = genericArguments[i];
var parameterConstraints = argumentType.GetGenericParameterConstraints();
constraintedArgumentTypes[i] = parameterConstraints[0];
}
method = ((MethodInfo)method).MakeGenericMethod(constraintedArgumentTypes);
return true;
}
catch (Exception)
{
return false;
}
}
}
}

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d5f029e1a01fd984f92bf8d5c2b51923
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

@ -0,0 +1,743 @@
/*
* Tencent is pleased to support the open source community by making xLua available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using System.Collections;
using System.Collections.Generic;
using System;
using System.Reflection;
namespace XLua
{
public delegate bool ObjectCheck(RealStatePtr L, int idx);
public delegate object ObjectCast(RealStatePtr L, int idx, object target); // if target is null, will new one
public class ObjectCheckers
{
Dictionary<Type, ObjectCheck> checkersMap = new Dictionary<Type, ObjectCheck>();
ObjectTranslator translator;
public ObjectCheckers(ObjectTranslator translator)
{
this.translator = translator;
checkersMap[typeof(sbyte)] = numberCheck;
checkersMap[typeof(byte)] = numberCheck;
checkersMap[typeof(short)] = numberCheck;
checkersMap[typeof(ushort)] = numberCheck;
checkersMap[typeof(int)] = numberCheck;
checkersMap[typeof(uint)] = numberCheck;
checkersMap[typeof(long)] = int64Check;
checkersMap[typeof(ulong)] = uint64Check;
checkersMap[typeof(double)] = numberCheck;
checkersMap[typeof(char)] = numberCheck;
checkersMap[typeof(float)] = numberCheck;
checkersMap[typeof(decimal)] = decimalCheck;
checkersMap[typeof(bool)] = boolCheck;
checkersMap[typeof(string)] = strCheck;
checkersMap[typeof(object)] = objectCheck;
checkersMap[typeof(byte[])] = bytesCheck;
checkersMap[typeof(IntPtr)] = intptrCheck;
checkersMap[typeof(LuaTable)] = luaTableCheck;
checkersMap[typeof(LuaFunction)] = luaFunctionCheck;
}
private static bool objectCheck(RealStatePtr L, int idx)
{
return true;
}
private bool luaTableCheck(RealStatePtr L, int idx)
{
return LuaAPI.lua_isnil(L, idx) || LuaAPI.lua_istable(L, idx) || (LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TUSERDATA && translator.SafeGetCSObj(L, idx) is LuaTable);
}
private bool numberCheck(RealStatePtr L, int idx)
{
return LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TNUMBER;
}
private bool decimalCheck(RealStatePtr L, int idx)
{
return LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TNUMBER || translator.IsDecimal(L, idx);
}
private bool strCheck(RealStatePtr L, int idx)
{
return LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TSTRING || LuaAPI.lua_isnil(L, idx);
}
private bool bytesCheck(RealStatePtr L, int idx)
{
return LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TSTRING || LuaAPI.lua_isnil(L, idx) || (LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TUSERDATA && translator.SafeGetCSObj(L, idx) is byte[]);
}
private bool boolCheck(RealStatePtr L, int idx)
{
return LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TBOOLEAN;
}
private bool int64Check(RealStatePtr L, int idx)
{
return LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TNUMBER || LuaAPI.lua_isint64(L, idx);
}
private bool uint64Check(RealStatePtr L, int idx)
{
return LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TNUMBER || LuaAPI.lua_isuint64(L, idx);
}
private bool luaFunctionCheck(RealStatePtr L, int idx)
{
return LuaAPI.lua_isnil(L, idx) || LuaAPI.lua_isfunction(L, idx) || (LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TUSERDATA && translator.SafeGetCSObj(L, idx) is LuaFunction);
}
private bool intptrCheck(RealStatePtr L, int idx)
{
return LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TLIGHTUSERDATA;
}
private ObjectCheck genChecker(Type type)
{
ObjectCheck fixTypeCheck = (RealStatePtr L, int idx) =>
{
if (LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TUSERDATA)
{
object obj = translator.SafeGetCSObj(L, idx);
if (obj != null)
{
return type.IsAssignableFrom(obj.GetType());
}
else
{
Type type_of_obj = translator.GetTypeOf(L, idx);
if (type_of_obj != null) return type.IsAssignableFrom(type_of_obj);
}
}
return false;
};
if (!type.IsAbstract() && typeof(Delegate).IsAssignableFrom(type))
{
return (RealStatePtr L, int idx) =>
{
return LuaAPI.lua_isnil(L, idx) || LuaAPI.lua_isfunction(L, idx) || fixTypeCheck(L, idx);
};
}
else if (type.IsEnum())
{
return fixTypeCheck;
}
else if (type.IsInterface())
{
return (RealStatePtr L, int idx) =>
{
return LuaAPI.lua_isnil(L, idx) || LuaAPI.lua_istable(L, idx) || fixTypeCheck(L, idx);
};
}
else
{
if ((type.IsClass() && type.GetConstructor(System.Type.EmptyTypes) != null)) //class has default construtor
{
return (RealStatePtr L, int idx) =>
{
return LuaAPI.lua_isnil(L, idx) || LuaAPI.lua_istable(L, idx) || fixTypeCheck(L, idx);
};
}
else if (type.IsValueType())
{
return (RealStatePtr L, int idx) =>
{
return LuaAPI.lua_istable(L, idx) || fixTypeCheck(L, idx);
};
}
else if (type.IsArray)
{
return (RealStatePtr L, int idx) =>
{
return LuaAPI.lua_isnil(L, idx) || LuaAPI.lua_istable(L, idx) || fixTypeCheck(L, idx);
};
}
else
{
return (RealStatePtr L, int idx) =>
{
return LuaAPI.lua_isnil(L, idx) || fixTypeCheck(L, idx);
};
}
}
}
public ObjectCheck genNullableChecker(ObjectCheck oc)
{
return (RealStatePtr L, int idx) =>
{
return LuaAPI.lua_isnil(L, idx) || oc(L, idx);
};
}
public void AddChecker(Type type, ObjectCheck oc)
{
checkersMap[type] = oc;
}
public ObjectCheck GetChecker(Type type)
{
if (type.IsByRef) type = type.GetElementType();
Type underlyingType = Nullable.GetUnderlyingType(type);
if (underlyingType != null)
{
return genNullableChecker(GetChecker(underlyingType));
}
ObjectCheck oc;
if (!checkersMap.TryGetValue(type, out oc))
{
oc = genChecker(type);
checkersMap.Add(type, oc);
}
return oc;
}
}
public class ObjectCasters
{
Dictionary<Type, ObjectCast> castersMap = new Dictionary<Type, ObjectCast>();
ObjectTranslator translator;
public ObjectCasters(ObjectTranslator translator)
{
this.translator = translator;
castersMap[typeof(char)] = charCaster;
castersMap[typeof(sbyte)] = sbyteCaster;
castersMap[typeof(byte)] = byteCaster;
castersMap[typeof(short)] = shortCaster;
castersMap[typeof(ushort)] = ushortCaster;
castersMap[typeof(int)] = intCaster;
castersMap[typeof(uint)] = uintCaster;
castersMap[typeof(long)] = longCaster;
castersMap[typeof(ulong)] = ulongCaster;
castersMap[typeof(double)] = getDouble;
castersMap[typeof(float)] = floatCaster;
castersMap[typeof(decimal)] = decimalCaster;
castersMap[typeof(bool)] = getBoolean;
castersMap[typeof(string)] = getString;
castersMap[typeof(object)] = getObject;
castersMap[typeof(byte[])] = getBytes;
castersMap[typeof(IntPtr)] = getIntptr;
//special type
castersMap[typeof(LuaTable)] = getLuaTable;
castersMap[typeof(LuaFunction)] = getLuaFunction;
}
private static object charCaster(RealStatePtr L, int idx, object target)
{
return (char)LuaAPI.xlua_tointeger(L, idx);
}
private static object sbyteCaster(RealStatePtr L, int idx, object target)
{
return (sbyte)LuaAPI.xlua_tointeger(L, idx);
}
private static object byteCaster(RealStatePtr L, int idx, object target)
{
return (byte)LuaAPI.xlua_tointeger(L, idx);
}
private static object shortCaster(RealStatePtr L, int idx, object target)
{
return (short)LuaAPI.xlua_tointeger(L, idx);
}
private static object ushortCaster(RealStatePtr L, int idx, object target)
{
return (ushort)LuaAPI.xlua_tointeger(L, idx);
}
private static object intCaster(RealStatePtr L, int idx, object target)
{
return LuaAPI.xlua_tointeger(L, idx);
}
private static object uintCaster(RealStatePtr L, int idx, object target)
{
return LuaAPI.xlua_touint(L, idx);
}
private static object longCaster(RealStatePtr L, int idx, object target)
{
return LuaAPI.lua_toint64(L, idx);
}
private static object ulongCaster(RealStatePtr L, int idx, object target)
{
return LuaAPI.lua_touint64(L, idx);
}
private static object getDouble(RealStatePtr L, int idx, object target)
{
return LuaAPI.lua_tonumber(L, idx);
}
private static object floatCaster(RealStatePtr L, int idx, object target)
{
return (float)LuaAPI.lua_tonumber(L, idx);
}
private object decimalCaster(RealStatePtr L, int idx, object target)
{
decimal ret;
translator.Get(L, idx, out ret);
return ret;
}
private static object getBoolean(RealStatePtr L, int idx, object target)
{
return LuaAPI.lua_toboolean(L, idx);
}
private static object getString(RealStatePtr L, int idx, object target)
{
return LuaAPI.lua_tostring(L, idx);
}
private object getBytes(RealStatePtr L, int idx, object target)
{
if(LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TSTRING)
{
return LuaAPI.lua_tobytes(L, idx);
}
object obj = translator.SafeGetCSObj(L, idx);
return (obj is RawObject) ? (obj as RawObject).Target : obj as byte[];
}
private object getIntptr(RealStatePtr L, int idx, object target)
{
return LuaAPI.lua_touserdata(L, idx);
}
private object getObject(RealStatePtr L, int idx, object target)
{
//return translator.getObject(L, idx); //TODO: translator.getObject move to here??
LuaTypes type = (LuaTypes)LuaAPI.lua_type(L, idx);
switch (type)
{
case LuaTypes.LUA_TNUMBER:
{
if (LuaAPI.lua_isint64(L, idx))
{
return LuaAPI.lua_toint64(L, idx);
}
else if(LuaAPI.lua_isinteger(L, idx))
{
return LuaAPI.xlua_tointeger(L, idx);
}
else
{
return LuaAPI.lua_tonumber(L, idx);
}
}
case LuaTypes.LUA_TSTRING:
{
return LuaAPI.lua_tostring(L, idx);
}
case LuaTypes.LUA_TBOOLEAN:
{
return LuaAPI.lua_toboolean(L, idx);
}
case LuaTypes.LUA_TTABLE:
{
return getLuaTable(L, idx, null);
}
case LuaTypes.LUA_TFUNCTION:
{
return getLuaFunction(L, idx, null);
}
case LuaTypes.LUA_TUSERDATA:
{
if (LuaAPI.lua_isint64(L, idx))
{
return LuaAPI.lua_toint64(L, idx);
}
else if(LuaAPI.lua_isuint64(L, idx))
{
return LuaAPI.lua_touint64(L, idx);
}
else
{
object obj = translator.SafeGetCSObj(L, idx);
return (obj is RawObject) ? (obj as RawObject).Target : obj;
}
}
default:
return null;
}
}
private object getLuaTable(RealStatePtr L, int idx, object target)
{
if (LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TUSERDATA)
{
object obj = translator.SafeGetCSObj(L, idx);
return (obj != null && obj is LuaTable) ? obj : null;
}
if (!LuaAPI.lua_istable(L, idx))
{
return null;
}
LuaAPI.lua_pushvalue(L, idx);
return new LuaTable(LuaAPI.luaL_ref(L), translator.luaEnv);
}
private object getLuaFunction(RealStatePtr L, int idx, object target)
{
if (LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TUSERDATA)
{
object obj = translator.SafeGetCSObj(L, idx);
return (obj != null && obj is LuaFunction) ? obj : null;
}
if (!LuaAPI.lua_isfunction(L, idx))
{
return null;
}
LuaAPI.lua_pushvalue(L, idx);
return new LuaFunction(LuaAPI.luaL_ref(L), translator.luaEnv);
}
public void AddCaster(Type type, ObjectCast oc)
{
castersMap[type] = oc;
}
private ObjectCast genCaster(Type type)
{
ObjectCast fixTypeGetter = (RealStatePtr L, int idx, object target) =>
{
if (LuaAPI.lua_type(L, idx) == LuaTypes.LUA_TUSERDATA)
{
object obj = translator.SafeGetCSObj(L, idx);
return (obj != null && type.IsAssignableFrom(obj.GetType())) ? obj : null;
}
return null;
};
if (typeof(Delegate).IsAssignableFrom(type))
{
return (RealStatePtr L, int idx, object target) =>
{
object obj = fixTypeGetter(L, idx, target);
if (obj != null) return obj;
if (!LuaAPI.lua_isfunction(L, idx))
{
return null;
}
return translator.CreateDelegateBridge(L, type, idx);
};
}
else if (typeof(DelegateBridgeBase).IsAssignableFrom(type))
{
return (RealStatePtr L, int idx, object target) =>
{
object obj = fixTypeGetter(L, idx, target);
if (obj != null) return obj;
if (!LuaAPI.lua_isfunction(L, idx))
{
return null;
}
return translator.CreateDelegateBridge(L, null, idx);
};
}
else if (type.IsInterface())
{
return (RealStatePtr L, int idx, object target) =>
{
object obj = fixTypeGetter(L, idx, target);
if (obj != null) return obj;
if (!LuaAPI.lua_istable(L, idx))
{
return null;
}
return translator.CreateInterfaceBridge(L, type, idx);
};
}
else if (type.IsEnum())
{
return (RealStatePtr L, int idx, object target) =>
{
object obj = fixTypeGetter(L, idx, target);
if (obj != null) return obj;
LuaTypes lua_type = LuaAPI.lua_type(L, idx);
if (lua_type == LuaTypes.LUA_TSTRING)
{
return Enum.Parse(type, LuaAPI.lua_tostring(L, idx));
}
else if (lua_type == LuaTypes.LUA_TNUMBER)
{
return Enum.ToObject(type, LuaAPI.xlua_tointeger(L, idx));
}
throw new InvalidCastException("invalid value for enum " + type);
};
}
else if (type.IsArray)
{
return (RealStatePtr L, int idx, object target) =>
{
object obj = fixTypeGetter(L, idx, target);
if (obj != null) return obj;
if (!LuaAPI.lua_istable(L, idx))
{
return null;
}
uint len = LuaAPI.xlua_objlen(L, idx);
int n = LuaAPI.lua_gettop(L);
idx = idx > 0 ? idx : LuaAPI.lua_gettop(L) + idx + 1;// abs of index
Type et = type.GetElementType();
ObjectCast elementCaster = GetCaster(et);
Array ary = target == null ? Array.CreateInstance(et, (int)len) : target as Array;
if (!LuaAPI.lua_checkstack(L, 1))
{
throw new Exception("stack overflow while cast to Array");
}
for (int i = 0; i < len; ++i)
{
LuaAPI.lua_pushnumber(L, i + 1);
LuaAPI.lua_rawget(L, idx);
if (et.IsPrimitive())
{
if (!StaticLuaCallbacks.TryPrimitiveArraySet(type, L, ary, i, n + 1))
{
ary.SetValue(elementCaster(L, n + 1, null), i);
}
}
else
{
if (InternalGlobals.genTryArraySetPtr == null
|| !InternalGlobals.genTryArraySetPtr(type, L, translator, ary, i, n + 1))
{
ary.SetValue(elementCaster(L, n + 1, null), i);
}
}
LuaAPI.lua_pop(L, 1);
}
return ary;
};
}
else if (typeof(IList).IsAssignableFrom(type) && type.IsGenericType())
{
Type elementType = type.GetGenericArguments()[0];
ObjectCast elementCaster = GetCaster(elementType);
return (RealStatePtr L, int idx, object target) =>
{
object obj = fixTypeGetter(L, idx, target);
if (obj != null) return obj;
if (!LuaAPI.lua_istable(L, idx))
{
return null;
}
obj = target == null ? Activator.CreateInstance(type) : target;
int n = LuaAPI.lua_gettop(L);
idx = idx > 0 ? idx : LuaAPI.lua_gettop(L) + idx + 1;// abs of index
IList list = obj as IList;
uint len = LuaAPI.xlua_objlen(L, idx);
if (!LuaAPI.lua_checkstack(L, 1))
{
throw new Exception("stack overflow while cast to IList");
}
for (int i = 0; i < len; ++i)
{
LuaAPI.lua_pushnumber(L, i + 1);
LuaAPI.lua_rawget(L, idx);
if (i < list.Count && target != null)
{
if (translator.Assignable(L, n + 1, elementType))
{
list[i] = elementCaster(L, n + 1, list[i]); ;
}
}
else
{
if (translator.Assignable(L, n + 1, elementType))
{
list.Add(elementCaster(L, n + 1, null));
}
}
LuaAPI.lua_pop(L, 1);
}
return obj;
};
}
else if (typeof(IDictionary).IsAssignableFrom(type) && type.IsGenericType())
{
Type keyType = type.GetGenericArguments()[0];
ObjectCast keyCaster = GetCaster(keyType);
Type valueType = type.GetGenericArguments()[1];
ObjectCast valueCaster = GetCaster(valueType);
return (RealStatePtr L, int idx, object target) =>
{
object obj = fixTypeGetter(L, idx, target);
if (obj != null) return obj;
if (!LuaAPI.lua_istable(L, idx))
{
return null;
}
IDictionary dic = (target == null ? Activator.CreateInstance(type) : target) as IDictionary;
int n = LuaAPI.lua_gettop(L);
idx = idx > 0 ? idx : LuaAPI.lua_gettop(L) + idx + 1;// abs of index
LuaAPI.lua_pushnil(L);
if (!LuaAPI.lua_checkstack(L, 1))
{
throw new Exception("stack overflow while cast to IDictionary");
}
while (LuaAPI.lua_next(L, idx) != 0)
{
if (translator.Assignable(L, n + 1, keyType) && translator.Assignable(L, n + 2, valueType))
{
object k = keyCaster(L, n + 1, null);
dic[k] = valueCaster(L, n + 2, !dic.Contains(k) ? null : dic[k]);
}
LuaAPI.lua_pop(L, 1); // removes value, keeps key for next iteration
}
return dic;
};
}
else if ((type.IsClass() && type.GetConstructor(System.Type.EmptyTypes) != null) || (type.IsValueType() && !type.IsEnum())) //class has default construtor
{
return (RealStatePtr L, int idx, object target) =>
{
object obj = fixTypeGetter(L, idx, target);
if (obj != null) return obj;
if (!LuaAPI.lua_istable(L, idx))
{
return null;
}
obj = target == null ? Activator.CreateInstance(type) : target;
int n = LuaAPI.lua_gettop(L);
idx = idx > 0 ? idx : LuaAPI.lua_gettop(L) + idx + 1;// abs of index
if (!LuaAPI.lua_checkstack(L, 1))
{
throw new Exception("stack overflow while cast to " + type);
}
/*foreach (PropertyInfo prop in type.GetProperties())
{
var _setMethod = prop.GetSetMethod();
if (_setMethod == null ||
_setMethod.IsPrivate)
{
continue;
}
LuaAPI.xlua_pushasciistring(L, prop.Name);
LuaAPI.lua_rawget(L, idx);
if (!LuaAPI.lua_isnil(L, -1))
{
try
{
prop.SetValue(obj, GetCaster(prop.PropertyType)(L, n + 1,
target == null || prop.PropertyType.IsPrimitive() || prop.PropertyType == typeof(string) ? null : prop.GetValue(obj, null)), null);
}
catch (Exception e)
{
throw new Exception("exception in tran " + prop.Name + ", msg=" + e.Message);
}
}
LuaAPI.lua_pop(L, 1);
}*/
foreach (FieldInfo field in type.GetFields())
{
LuaAPI.xlua_pushasciistring(L, field.Name);
LuaAPI.lua_rawget(L, idx);
if (!LuaAPI.lua_isnil(L, -1))
{
try
{
field.SetValue(obj, GetCaster(field.FieldType)(L, n + 1,
target == null || field.FieldType.IsPrimitive() || field.FieldType == typeof(string) ? null : field.GetValue(obj)));
}
catch (Exception e)
{
throw new Exception("exception in tran " + field.Name + ", msg=" + e.Message);
}
}
LuaAPI.lua_pop(L, 1);
}
return obj;
};
}
else
{
return fixTypeGetter;
}
}
ObjectCast genNullableCaster(ObjectCast oc)
{
return (RealStatePtr L, int idx, object target) =>
{
if (LuaAPI.lua_isnil(L, idx))
{
return null;
}
else
{
return oc(L, idx, target);
}
};
}
public ObjectCast GetCaster(Type type)
{
if (type.IsByRef) type = type.GetElementType();
Type underlyingType = Nullable.GetUnderlyingType(type);
if (underlyingType != null)
{
return genNullableCaster(GetCaster(underlyingType));
}
ObjectCast oc;
if (!castersMap.TryGetValue(type, out oc))
{
oc = genCaster(type);
castersMap.Add(type, oc);
}
return oc;
}
}
}

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 04cef766c4f15b341bcb4659831e6748
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

@ -0,0 +1,164 @@
/*
* Tencent is pleased to support the open source community by making xLua available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
namespace XLua
{
public class ObjectPool
{
const int LIST_END = -1;
const int ALLOCED = -2;
struct Slot
{
public int next;
public object obj;
public Slot(int next, object obj)
{
this.next = next;
this.obj = obj;
}
}
private Slot[] list = new Slot[512];
private int freelist = LIST_END;
private int count = 0;
public object this[int i]
{
get
{
if (i >= 0 && i < count)
{
return list[i].obj;
}
return null;
}
}
public void Clear()
{
freelist = LIST_END;
count = 0;
list = new Slot[512];
}
void extend_capacity()
{
Slot[] new_list = new Slot[list.Length * 2];
for (int i = 0; i < list.Length; i++)
{
new_list[i] = list[i];
}
list = new_list;
}
public int Add(object obj)
{
int index = LIST_END;
if (freelist != LIST_END)
{
index = freelist;
list[index].obj = obj;
freelist = list[index].next;
list[index].next = ALLOCED;
}
else
{
if (count == list.Length)
{
extend_capacity();
}
index = count;
list[index] = new Slot(ALLOCED, obj);
count = index + 1;
}
return index;
}
public bool TryGetValue(int index, out object obj)
{
if (index >= 0 && index < count && list[index].next == ALLOCED)
{
obj = list[index].obj;
return true;
}
obj = null;
return false;
}
public object Get(int index)
{
if (index >= 0 && index < count)
{
return list[index].obj;
}
return null;
}
public object Remove(int index)
{
if (index >= 0 && index < count && list[index].next == ALLOCED)
{
object o = list[index].obj;
list[index].obj = null;
list[index].next = freelist;
freelist = index;
return o;
}
return null;
}
public object Replace(int index, object o)
{
if (index >= 0 && index < count)
{
object obj = list[index].obj;
list[index].obj = o;
return obj;
}
return null;
}
public int Check(int check_pos, int max_check, Func<object, bool> checker, Dictionary<object, int> reverse_map)
{
if (count == 0)
{
return 0;
}
for (int i = 0; i < Math.Min(max_check, count); ++i)
{
check_pos %= count;
if (list[check_pos].next == ALLOCED && !Object.ReferenceEquals(list[check_pos].obj, null))
{
if (!checker(list[check_pos].obj))
{
object obj = Replace(check_pos, null);
int obj_index;
if (reverse_map.TryGetValue(obj, out obj_index) && obj_index == check_pos)
{
reverse_map.Remove(obj);
}
}
}
++check_pos;
}
return check_pos %= count;
}
}
}

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: acf2cec75841d9646900284e2ba1ca4f
timeCreated: 1480296949
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because it is too large Load Diff

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 41d53bdd4bbda0f41a6bd1eb35af4f99
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

@ -0,0 +1,114 @@
/*
* Tencent is pleased to support the open source community by making xLua available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using System.Collections.Generic;
using System;
namespace XLua
{
public class ObjectTranslatorPool
{
#if !SINGLE_ENV
private Dictionary<RealStatePtr, WeakReference> translators = new Dictionary<RealStatePtr, WeakReference>();
RealStatePtr lastPtr = default(RealStatePtr);
#endif
ObjectTranslator lastTranslator = default(ObjectTranslator);
public static ObjectTranslatorPool Instance
{
get
{
return InternalGlobals.objectTranslatorPool;
}
}
#if UNITY_EDITOR || XLUA_GENERAL
public static ObjectTranslator FindTranslator(RealStatePtr L)
{
return InternalGlobals.objectTranslatorPool.Find(L);
}
#endif
public ObjectTranslatorPool ()
{
}
public void Add (RealStatePtr L, ObjectTranslator translator)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (this)
#endif
{
lastTranslator = translator;
#if !SINGLE_ENV
var ptr = LuaAPI.xlua_gl(L);
lastPtr = ptr;
translators.Add(ptr , new WeakReference(translator));
#endif
}
}
public ObjectTranslator Find (RealStatePtr L)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (this)
#endif
{
#if SINGLE_ENV
return lastTranslator;
#else
var ptr = LuaAPI.xlua_gl(L);
if (lastPtr == ptr) return lastTranslator;
if (translators.ContainsKey(ptr))
{
lastPtr = ptr;
lastTranslator = translators[ptr].Target as ObjectTranslator;
return lastTranslator;
}
return null;
#endif
}
}
public void Remove (RealStatePtr L)
{
#if THREAD_SAFE || HOTFIX_ENABLE
lock (this)
#endif
{
#if SINGLE_ENV
lastTranslator = default(ObjectTranslator);
#else
var ptr = LuaAPI.xlua_gl(L);
if (!translators.ContainsKey (ptr))
return;
if (lastPtr == ptr)
{
lastPtr = default(RealStatePtr);
lastTranslator = default(ObjectTranslator);
}
translators.Remove(ptr);
#endif
}
}
}
}

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 069f15dde2065491db1e68ca5fb1279d
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

@ -0,0 +1,106 @@
/*
* Tencent is pleased to support the open source community by making xLua available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
namespace XLua
{
public interface RawObject
{
object Target { get; }
}
}
namespace XLua.Cast
{
public class Any<T> : RawObject
{
T mTarget;
public Any(T i)
{
mTarget = i;
}
public object Target
{
get
{
return mTarget;
}
}
}
public class Byte : Any<byte>
{
public Byte(byte i) : base(i)
{
}
}
public class SByte : Any<sbyte>
{
public SByte(sbyte i) : base(i)
{
}
}
public class Char : Any<char>
{
public Char(char i) : base(i)
{
}
}
public class Int16 : Any<short>
{
public Int16(short i) : base(i)
{
}
}
public class UInt16 : Any<ushort>
{
public UInt16(ushort i) : base(i)
{
}
}
public class Int32 : Any<int>
{
public Int32(int i) : base(i)
{
}
}
public class UInt32 : Any<uint>
{
public UInt32(uint i) : base(i)
{
}
}
public class Int64 : Any<long>
{
public Int64(long i) : base(i)
{
}
}
public class UInt64 : Any<ulong>
{
public UInt64(ulong i) : base(i)
{
}
}
public class Float : Any<float>
{
public Float(float i) : base(i)
{
}
}
}

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: f3f2b65020c56dc4985af0768b06c63c
timeCreated: 1498116130
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,73 @@
#if !UNITY_WSA || UNITY_EDITOR
using System.Security.Cryptography;
#else
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
#endif
using System;
namespace XLua
{
public class SignatureLoader
{
private LuaEnv.CustomLoader userLoader;
#if !UNITY_WSA || UNITY_EDITOR
RSACryptoServiceProvider rsa;
SHA1 sha;
#else
AsymmetricKeyAlgorithmProvider rsa;
CryptographicKey key;
#endif
public SignatureLoader(string publicKey, LuaEnv.CustomLoader loader)
{
#if !UNITY_WSA || UNITY_EDITOR
rsa = new RSACryptoServiceProvider();
rsa.ImportCspBlob(Convert.FromBase64String(publicKey));
sha = new SHA1CryptoServiceProvider();
#else
rsa = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(AsymmetricAlgorithmNames.RsaSignPkcs1Sha1);
key = rsa.ImportPublicKey(CryptographicBuffer.DecodeFromBase64String(publicKey), CryptographicPublicKeyBlobType.Capi1PublicKey);
#endif
userLoader = loader;
}
byte[] load_and_verify(ref string filepath)
{
byte[] data = userLoader(ref filepath);
if (data == null)
{
return null;
}
if (data.Length < 128)
{
throw new InvalidProgramException(filepath + " length less than 128!");
}
byte[] sig = new byte[128];
byte[] filecontent = new byte[data.Length - 128];
Array.Copy(data, sig, 128);
Array.Copy(data, 128, filecontent, 0, filecontent.Length);
#if !UNITY_WSA || UNITY_EDITOR
if (!rsa.VerifyData(filecontent, sha, sig))
{
throw new InvalidProgramException(filepath + " has invalid signature!");
}
#else
if (!CryptographicEngine.VerifySignature(key, CryptographicBuffer.CreateFromByteArray(filecontent), CryptographicBuffer.CreateFromByteArray(sig)))
{
throw new InvalidProgramException(filepath + " has invalid signature!");
}
#endif
return filecontent;
}
public static implicit operator LuaEnv.CustomLoader(SignatureLoader signatureLoader)
{
return signatureLoader.load_and_verify;
}
}
}

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 5dfa9c69dddc18849bd3c1dfc4ac42de
timeCreated: 1489222429
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because it is too large Load Diff

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 300ed412007935e45a1546a984b89059
timeCreated: 1469175028
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

@ -0,0 +1,5 @@
fileFormatVersion: 2
guid: 4f996f6400fcbdd4db02eeab46d9dd1e
folderAsset: yes
DefaultImporter:
userData:

@ -0,0 +1,258 @@
/*
* Tencent is pleased to support the open source community by making xLua available.
* Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
#if USE_UNI_LUA
using LuaAPI = UniLua.Lua;
using RealStatePtr = UniLua.ILuaState;
using LuaCSFunction = UniLua.CSharpFunctionDelegate;
#else
using LuaAPI = XLua.LuaDLL.Lua;
using RealStatePtr = System.IntPtr;
using LuaCSFunction = XLua.LuaDLL.lua_CSFunction;
#endif
using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using XLua;
namespace XLua.TemplateEngine
{
public enum TokenType
{
Code, Eval, Text
}
public class Chunk
{
public TokenType Type {get; private set;}
public string Text { get; private set; }
public Chunk(TokenType type, string text)
{
Type = type;
Text = text;
}
}
class TemplateFormatException : Exception
{
public TemplateFormatException(string message)
{
}
}
public class Parser
{
public static string RegexString
{
get;
private set;
}
static Parser()
{
RegexString = GetRegexString();
}
/// <summary>
/// Replaces special characters with their literal representation.
/// </summary>
/// <returns>Resulting string.</returns>
/// <param name="input">Input string.</param>
static string EscapeString(string input)
{
var output = input
.Replace("\\", @"\\")
.Replace("\'", @"\'")
.Replace("\"", @"\""")
.Replace("\n", @"\n")
.Replace("\t", @"\t")
.Replace("\r", @"\r")
.Replace("\b", @"\b")
.Replace("\f", @"\f")
.Replace("\a", @"\a")
.Replace("\v", @"\v")
.Replace("\0", @"\0");
/* var surrogateMin = (char)0xD800;
var surrogateMax = (char)0xDFFF;
for (char sur = surrogateMin; sur <= surrogateMax; sur++)
output.Replace(sur, '\uFFFD');*/
return output;
}
static string GetRegexString()
{
string regexBadUnopened = @"(?<error>((?!<%).)*%>)";
string regexText = @"(?<text>((?!<%).)+)";
string regexNoCode = @"(?<nocode><%=?%>)";
string regexCode = @"<%(?<code>[^=]((?!<%|%>).)*)%>";
string regexEval = @"<%=(?<eval>((?!<%|%>).)*)%>";
string regexBadUnclosed = @"(?<error><%.*)";
string regexBadEmpty = @"(?<error>^$)";
return '(' + regexBadUnopened
+ '|' + regexText
+ '|' + regexNoCode
+ '|' + regexCode
+ '|' + regexEval
+ '|' + regexBadUnclosed
+ '|' + regexBadEmpty
+ ")*";
}
/// <summary>
/// Parses the string into regex groups,
/// stores group:value pairs in List of Chunk
/// <returns>List of group:value pairs.</returns>;
/// </summary>
public static List<Chunk> Parse(string snippet)
{
Regex templateRegex = new Regex(
RegexString,
RegexOptions.ExplicitCapture | RegexOptions.Singleline
);
Match matches = templateRegex.Match(snippet);
if (matches.Groups["error"].Length > 0)
{
throw new TemplateFormatException("Messed up brackets");
}
List<Chunk> Chunks = matches.Groups["code"].Captures
.Cast<Capture>()
.Select(p => new { Type = TokenType.Code, p.Value, p.Index })
.Concat(matches.Groups["text"].Captures
.Cast<Capture>()
.Select(p => new { Type = TokenType.Text, Value = EscapeString(p.Value), p.Index }))
.Concat(matches.Groups["eval"].Captures
.Cast<Capture>()
.Select(p => new { Type = TokenType.Eval, p.Value, p.Index }))
.OrderBy(p => p.Index)
.Select(m => new Chunk(m.Type, m.Value))
.ToList();
if (Chunks.Count == 0)
{
throw new TemplateFormatException("Empty template");
}
return Chunks;
}
}
public class LuaTemplate
{
public static string ComposeCode(List<Chunk> chunks)
{
StringBuilder code = new StringBuilder();
code.Append("local __text_gen = {}\r\n");
foreach (var chunk in chunks)
{
switch (chunk.Type)
{
case TokenType.Text:
code.Append("table.insert(__text_gen, \"" + chunk.Text + "\")\r\n");
break;
case TokenType.Eval:
code.Append("table.insert(__text_gen, tostring(" + chunk.Text + "))\r\n");
break;
case TokenType.Code:
code.Append(chunk.Text + "\r\n");
break;
}
}
code.Append("return table.concat(__text_gen)\r\n");
//UnityEngine.Debug.Log("code compose:"+code.ToString());
return code.ToString();
}
public static LuaFunction Compile(LuaEnv luaenv, string snippet)
{
return luaenv.LoadString(ComposeCode(Parser.Parse(snippet)), "luatemplate");
}
public static string Execute(LuaFunction compiledTemplate, LuaTable parameters)
{
compiledTemplate.SetEnv(parameters);
object[] result = compiledTemplate.Call();
System.Diagnostics.Debug.Assert(result.Length == 1);
return result[0].ToString();
}
public static string Execute(LuaFunction compiledTemplate)
{
object[] result = compiledTemplate.Call();
System.Diagnostics.Debug.Assert(result.Length == 1);
return result[0].ToString();
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
public static int Compile(RealStatePtr L)
{
string snippet = LuaAPI.lua_tostring(L, 1);
string code;
try
{
code = ComposeCode(Parser.Parse(snippet));
}
catch (Exception e)
{
return LuaAPI.luaL_error(L, String.Format("template compile error:{0}\r\n", e.Message));
}
//UnityEngine.Debug.Log("code=" + code);
if (LuaAPI.luaL_loadbuffer(L, code, "luatemplate") != 0)
{
return LuaAPI.lua_error(L);
}
return 1;
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
public static int Execute(RealStatePtr L)
{
if (!LuaAPI.lua_isfunction(L, 1))
{
return LuaAPI.luaL_error(L, "invalid compiled template, function needed!\r\n");
}
if (LuaAPI.lua_istable(L, 2))
{
LuaAPI.lua_setfenv(L, 1);
}
LuaAPI.lua_pcall(L, 0, 1, 0);
return 1;
}
static LuaCSFunction templateCompileFunction = Compile;
static LuaCSFunction templateExecuteFunction = Execute;
public static void OpenLib(RealStatePtr L)
{
LuaAPI.lua_newtable(L);
LuaAPI.xlua_pushasciistring(L, "compile");
LuaAPI.lua_pushstdcallcfunction(L, templateCompileFunction);
LuaAPI.lua_rawset(L, -3);
LuaAPI.xlua_pushasciistring(L, "execute");
LuaAPI.lua_pushstdcallcfunction(L, templateExecuteFunction);
LuaAPI.lua_rawset(L, -3);
if (0 != LuaAPI.xlua_setglobal(L, "template"))
{
throw new Exception("call xlua_setglobal fail!");
}
}
}
}

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d416b4da0b828854c8e997f0c1ae4072
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:

@ -0,0 +1,162 @@
using System;
using System.Linq;
using System.Reflection;
namespace XLua
{
internal static class TypeExtensions
{
public static bool IsValueType(this Type type)
{
#if !UNITY_WSA || UNITY_EDITOR
return type.IsValueType;
#else
return type.GetTypeInfo().IsValueType;
#endif
}
public static bool IsEnum(this Type type)
{
#if !UNITY_WSA || UNITY_EDITOR
return type.IsEnum;
#else
return type.GetTypeInfo().IsEnum;
#endif
}
public static bool IsPrimitive(this Type type)
{
#if !UNITY_WSA || UNITY_EDITOR
return type.IsPrimitive;
#else
return type.GetTypeInfo().IsPrimitive;
#endif
}
public static bool IsAbstract(this Type type)
{
#if !UNITY_WSA || UNITY_EDITOR
return type.IsAbstract;
#else
return type.GetTypeInfo().IsAbstract;
#endif
}
public static bool IsSealed(this Type type)
{
#if !UNITY_WSA || UNITY_EDITOR
return type.IsSealed;
#else
return type.GetTypeInfo().IsSealed;
#endif
}
public static bool IsInterface(this Type type)
{
#if !UNITY_WSA || UNITY_EDITOR
return type.IsInterface;
#else
return type.GetTypeInfo().IsInterface;
#endif
}
public static bool IsClass(this Type type)
{
#if !UNITY_WSA || UNITY_EDITOR
return type.IsClass;
#else
return type.GetTypeInfo().IsClass;
#endif
}
public static Type BaseType(this Type type)
{
#if !UNITY_WSA || UNITY_EDITOR
return type.BaseType;
#else
return type.GetTypeInfo().BaseType;
#endif
}
public static bool IsGenericType(this Type type)
{
#if !UNITY_WSA || UNITY_EDITOR
return type.IsGenericType;
#else
return type.GetTypeInfo().IsGenericType;
#endif
}
public static bool IsGenericTypeDefinition(this Type type)
{
#if !UNITY_WSA || UNITY_EDITOR
return type.IsGenericTypeDefinition;
#else
return type.GetTypeInfo().IsGenericTypeDefinition;
#endif
}
#if UNITY_WSA && !UNITY_EDITOR
public static bool IsSubclassOf(this Type type, Type c)
{
return type.GetTypeInfo().IsSubclassOf(c);
}
public static bool IsDefined(this Type type, Type attributeType, bool inherit)
{
return type.GetTypeInfo().IsDefined(attributeType, inherit);
}
public static Type[] GetGenericParameterConstraints(this Type type)
{
return type.GetTypeInfo().GetGenericParameterConstraints();
}
#endif
public static bool IsNestedPublic(this Type type)
{
#if !UNITY_WSA || UNITY_EDITOR
return type.IsNestedPublic;
#else
return type.GetTypeInfo().IsNestedPublic;
#endif
}
public static bool IsPublic(this Type type)
{
#if !UNITY_WSA || UNITY_EDITOR
return type.IsPublic;
#else
return type.GetTypeInfo().IsPublic;
#endif
}
public static string GetFriendlyName(this Type type)
{
if (type == typeof(int))
return "int";
else if (type == typeof(short))
return "short";
else if (type == typeof(byte))
return "byte";
else if (type == typeof(bool))
return "bool";
else if (type == typeof(long))
return "long";
else if (type == typeof(float))
return "float";
else if (type == typeof(double))
return "double";
else if (type == typeof(decimal))
return "decimal";
else if (type == typeof(string))
return "string";
else if (type.IsGenericType())
return type.FullName.Split('`')[0] + "<" + string.Join(", ", type.GetGenericArguments()
.Select(x => GetFriendlyName(x)).ToArray()) + ">";
else
return type.FullName;
}
}
}

@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 0099a231859d6da43932d0c36714e17f
timeCreated: 1489998065
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

1539
Assets/XLua/Src/Utils.cs Normal file

File diff suppressed because it is too large Load Diff

@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d9c14a5b76adb7d41926526af904beda
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData: