/* * Calls the function casting return values to the types * in returnTypes */ internal object[] call(object[] args, Type[] returnTypes) { int nArgs = 0; LuaScriptMgr.PushTraceBack(L); int oldTop = LuaAPI.lua_gettop(L); if (!LuaAPI.lua_checkstack(L, args.Length + 6)) { LuaAPI.lua_pop(L, 1); throw new LuaException("Lua stack overflow"); } push(L); if (args != null) { nArgs = args.Length; for (int i = 0; i < args.Length; i++) { PushArgs(L, args[i]); } } int error = LuaAPI.lua_pcall(L, nArgs, -1, -nArgs - 2); if (error != 0) { string err = LuaAPI.lua_tostring(L, -1); LuaAPI.lua_settop(L, oldTop - 1); if (err == null) { err = "Unknown Lua Error"; } throw new LuaScriptException(err, ""); } object[] ret = returnTypes != null?translator.popValues(L, oldTop, returnTypes) : translator.popValues(L, oldTop); LuaAPI.lua_settop(L, oldTop - 1); return(ret); }
public static int enumFromInt(IntPtr luaState) { ObjectTranslator translator = ObjectTranslator.FromState(luaState); Type t = translator.typeOf(luaState, 1); if (t == null || !t.IsEnum) { return(translator.pushError(luaState, "not an enum")); } object res = null; LuaTypes lt = LuaAPI.lua_type(luaState, 2); if (lt == LuaTypes.LUA_TNUMBER) { int ival = (int)LuaAPI.lua_tonumber(luaState, 2); res = Enum.ToObject(t, ival); } else if (lt == LuaTypes.LUA_TSTRING) { string sflags = LuaAPI.lua_tostring(luaState, 2); string err = null; try { res = Enum.Parse(t, sflags); } catch (ArgumentException e) { err = e.Message; } if (err != null) { return(translator.pushError(luaState, err)); } } else { return(translator.pushError(luaState, "second argument must be a integer or a string")); } translator.pushObject(luaState, res, "luaNet_metatable"); return(1); }
private void createClassMetatable(IntPtr luaState) { LuaAPI.luaL_newmetatable(luaState, "luaNet_class"); LuaAPI.lua_pushstring(luaState, "__gc"); LuaAPI.lua_pushstdcallcfunction(luaState, metaFunctions.gcFunction); LuaAPI.lua_settable(luaState, -3); LuaAPI.lua_pushstring(luaState, "__tostring"); LuaAPI.lua_pushstdcallcfunction(luaState, metaFunctions.toStringFunction); LuaAPI.lua_settable(luaState, -3); LuaAPI.lua_pushstring(luaState, "__index"); LuaAPI.lua_pushstdcallcfunction(luaState, metaFunctions.classIndexFunction); LuaAPI.lua_settable(luaState, -3); LuaAPI.lua_pushstring(luaState, "__newindex"); LuaAPI.lua_pushstdcallcfunction(luaState, metaFunctions.classNewindexFunction); LuaAPI.lua_settable(luaState, -3); LuaAPI.lua_pushstring(luaState, "__call"); LuaAPI.lua_pushstdcallcfunction(luaState, metaFunctions.callConstructorFunction); LuaAPI.lua_settable(luaState, -3); LuaAPI.lua_settop(luaState, -2); }
static void PushMetaTable(IntPtr L, Type t) { int reference = -1; if (!typeMetaMap.TryGetValue(t, out reference)) { LuaAPI.luaL_getmetatable(L, t.AssemblyQualifiedName); if (!LuaAPI.lua_isnil(L, -1)) { LuaAPI.lua_pushvalue(L, -1); reference = LuaAPI.luaL_ref(L, LuaAPI.LUA_REGISTRYINDEX); typeMetaMap.Add(t, reference); } } else { LuaAPI.ulua_rawgeti(L, LuaAPI.LUA_REGISTRYINDEX, reference); } }
private void setGlobalFunctions(IntPtr luaState) { LuaAPI.lua_pushstdcallcfunction(luaState, metaFunctions.indexFunction); LuaAPI.lua_setglobal(luaState, "get_object_member"); LuaAPI.lua_getglobal(luaState, "luanet"); LuaAPI.lua_pushstring(luaState, "import_type"); LuaAPI.lua_pushstdcallcfunction(luaState, importTypeFunction); LuaAPI.lua_settable(luaState, -3); LuaAPI.lua_pushstring(luaState, "load_assembly"); LuaAPI.lua_pushstdcallcfunction(luaState, loadAssemblyFunction); LuaAPI.lua_settable(luaState, -3); LuaAPI.lua_pushstring(luaState, "make_object"); LuaAPI.lua_pushstdcallcfunction(luaState, unregisterTableFunction); LuaAPI.lua_settable(luaState, -3); LuaAPI.lua_pushstring(luaState, "ctype"); LuaAPI.lua_pushstdcallcfunction(luaState, ctypeFunction); LuaAPI.lua_settable(luaState, -3); LuaAPI.lua_pushstring(luaState, "enum"); LuaAPI.lua_pushstdcallcfunction(luaState, enumFromIntFunction); LuaAPI.lua_settable(luaState, -3); }
internal object[] popValues(IntPtr luaState, int oldTop) { int newTop = LuaAPI.lua_gettop(luaState); if (oldTop == newTop) { return(null); } else { List <object> returnValues = new List <object>(); for (int i = oldTop + 1; i <= newTop; i++) { returnValues.Add(getObject(luaState, i)); } LuaAPI.lua_settop(luaState, oldTop); return(returnValues.ToArray()); } }
public object getAsObject(IntPtr luaState, int stackPos) { if (LuaAPI.lua_type(luaState, stackPos) == LuaTypes.LUA_TTABLE) { if (LuaTypes.LUA_TNIL != LuaAPI.luaL_getmetafield(luaState, stackPos, "__index")) { if (LuaAPI.luaL_checkmetatable(luaState, -1)) { LuaAPI.lua_insert(luaState, stackPos); LuaAPI.lua_remove(luaState, stackPos + 1); } else { LuaAPI.lua_settop(luaState, -2); } } } object obj = translator.getObject(luaState, stackPos); return(obj); }
/// <summary> /// Debug tool to dump the lua stack /// </summary> public static void dumpStack(ObjectTranslator translator, IntPtr luaState) { int depth = LuaAPI.lua_gettop(luaState); Debug.WriteLine("lua stack depth: " + depth); for (int i = 1; i <= depth; i++) { LuaTypes type = LuaAPI.lua_type(luaState, i); // we dump stacks when deep in calls, calling typename while the stack is in flux can fail sometimes, so manually check for key types string typestr = (type == LuaTypes.LUA_TTABLE) ? "table" : LuaAPI.lua_typename(luaState, type); string strrep = LuaAPI.lua_tostring(luaState, i); if (type == LuaTypes.LUA_TUSERDATA) { object obj = translator.getRawNetObject(luaState, i); strrep = obj.ToString(); } Debug.WriteLine(String.Format("{0}: ({1}) {2}", i, typestr, strrep)); } }
public static int unregisterTable(IntPtr luaState) { ObjectTranslator translator = ObjectTranslator.FromState(luaState); try { if (LuaAPI.lua_getmetatable(luaState, 1) != 0) { LuaAPI.lua_pushstring(luaState, "__index"); LuaAPI.lua_gettable(luaState, -2); object obj = translator.getRawNetObject(luaState, -1); if (obj == null) { translator.throwError(luaState, "unregister_table: arg is not valid table"); } FieldInfo luaTableField = obj.GetType().GetField("__luaInterface_luaTable"); if (luaTableField == null) { translator.throwError(luaState, "unregister_table: arg is not valid table"); } luaTableField.SetValue(obj, null); LuaAPI.lua_pushnil(luaState); LuaAPI.lua_setmetatable(luaState, 1); LuaAPI.lua_pushstring(luaState, "base"); LuaAPI.lua_pushnil(luaState); LuaAPI.lua_settable(luaState, 1); } else { translator.throwError(luaState, "unregister_table: arg is not valid table"); } } catch (Exception e) { translator.throwError(luaState, e.Message); } return(0); }
public LuaState() { L = LuaAPI.luaL_newstate(); LuaAPI.luaL_openlibs(L); LuaAPI.lua_newtable(L); LuaAPI.lua_pushstring(L, "getmetatable"); LuaAPI.lua_getglobal(L, "getmetatable"); LuaAPI.lua_settable(L, -3); LuaAPI.lua_pushstring(L, "rawget"); LuaAPI.lua_getglobal(L, "rawget"); LuaAPI.lua_settable(L, -3); LuaAPI.lua_pushstring(L, "rawset"); LuaAPI.lua_getglobal(L, "rawset"); LuaAPI.lua_settable(L, -3); LuaAPI.lua_setglobal(L, "luanet"); LuaAPI.lua_getglobal(L, "luanet"); translator = new ObjectTranslator(this, L); translator.PushTranslator(L); LuaAPI.lua_atpanic(L, LuaStatic.panic); LuaAPI.lua_pushstdcallcfunction(L, LuaStatic.print); LuaAPI.lua_setglobal(L, "print"); LuaAPI.lua_pushstdcallcfunction(L, LuaStatic.loadfile); LuaAPI.lua_setglobal(L, "loadfile"); LuaAPI.lua_pushstdcallcfunction(L, LuaStatic.dofile); LuaAPI.lua_setglobal(L, "dofile"); LuaAPI.lua_pushstdcallcfunction(L, LuaStatic.importWrap); LuaAPI.lua_setglobal(L, "import"); AddLoader(LuaStatic.loader, 2); AddLoader(LuaStatic.LoadBuiltinLib, 3); errorFuncRef = LuaAPI.get_error_func_ref(L); LuaAPI.lua_settop(L, 0); //clear stack }
public static int getClassMethod(IntPtr luaState) { ObjectTranslator translator = ObjectTranslator.FromState(luaState); IReflect klass; object obj = translator.getRawNetObject(luaState, 1); if (obj == null || !(obj is IReflect)) { translator.throwError(luaState, "trying to index an invalid type reference"); LuaAPI.lua_pushnil(luaState); return(1); } else { klass = (IReflect)obj; } if (LuaAPI.lua_isnumber(luaState, 2)) { int size = (int)LuaAPI.lua_tonumber(luaState, 2); translator.push(luaState, Array.CreateInstance(klass.UnderlyingSystemType, size)); return(1); } else { string methodName = LuaAPI.lua_tostring(luaState, 2); if (methodName == null) { LuaAPI.lua_pushnil(luaState); return(1); } //CP: Ignore case else { return(translator.metaFunctions.getMember(luaState, klass, null, methodName, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.IgnoreCase)); } } }
public object[] DoString(string chunk) { int oldTop = LuaAPI.lua_gettop(L); int errFunc = LuaAPI.load_error_func(L, errorFuncRef); byte[] bt = Encoding.UTF8.GetBytes(chunk); if (LuaAPI.luaL_loadbuffer(L, bt, bt.Length, "chunk") == 0) { if (LuaAPI.lua_pcall(L, 0, LuaAPI.LUA_MULTRET, errFunc) == 0) { LuaAPI.lua_remove(L, errFunc); return(translator.popValues(L, oldTop)); } else { ThrowExceptionFromError(oldTop); } } else { ThrowExceptionFromError(oldTop); } return(null); }
internal static int LoadBuiltinLib(IntPtr L) { LuaAPI.lua_pushstdcallcfunction(L, LoadLuaProfobuf); return(1); }
public static int LoadLuaProfobuf(IntPtr L) { return(LuaAPI.luaopen_pb(L)); }
/* * Pushes the value of a member or a delegate to call it, depending on the type of * the member. Works with static or instance members. * Uses reflection to find members, and stores the reflected MemberInfo object in * a cache (indexed by the type of the object and the name of the member). */ private int getMember(IntPtr luaState, IReflect objType, object obj, string methodName, BindingFlags bindingType) { bool implicitStatic = false; MemberInfo member = null; object cachedMember = checkMemberCache(memberCache, objType, methodName); if (cachedMember is LuaCSFunction) { translator.pushFunction(luaState, (LuaCSFunction)cachedMember); translator.push(luaState, true); return(2); } else if (cachedMember != null) { member = (MemberInfo)cachedMember; } else { //CP: Removed NonPublic binding search MemberInfo[] members = objType.GetMember(methodName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase /*| BindingFlags.NonPublic*/); if (members.Length > 0) { member = members[0]; } else { members = objType.GetMember(methodName, bindingType | BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase /*| BindingFlags.NonPublic*/); if (members.Length > 0) { member = members[0]; implicitStatic = true; } } } if (member != null) { if (member.MemberType == MemberTypes.Field) { FieldInfo field = (FieldInfo)member; if (cachedMember == null) { setMemberCache(memberCache, objType, methodName, member); } try { translator.push(luaState, field.GetValue(obj)); } catch { LuaAPI.lua_pushnil(luaState); } } else if (member.MemberType == MemberTypes.Property) { PropertyInfo property = (PropertyInfo)member; if (cachedMember == null) { setMemberCache(memberCache, objType, methodName, member); } try { object val = property.GetGetMethod().Invoke(obj, null); translator.push(luaState, val); } catch (ArgumentException) { if (objType is Type && !(((Type)objType) == typeof(object))) { return(getMember(luaState, ((Type)objType).BaseType, obj, methodName, bindingType)); } else { LuaAPI.lua_pushnil(luaState); } } catch (TargetInvocationException e) // Convert this exception into a Lua error { ThrowError(luaState, e); LuaAPI.lua_pushnil(luaState); } } else if (!implicitStatic) { if (member.MemberType == MemberTypes.NestedType) { // cache us if (cachedMember == null) { setMemberCache(memberCache, objType, methodName, member); } // Find the name of our class string name = member.Name; Type dectype = member.DeclaringType; // Build a new long name and try to find the type by name string longname = dectype.FullName + "+" + name; Type nestedType = translator.FindType(longname); translator.pushType(luaState, nestedType); } else { // Member type must be 'method' LuaCSFunction wrapper = new LuaCSFunction((new LuaMethodWrapper(translator, objType, methodName, bindingType)).call); if (cachedMember == null) { setMemberCache(memberCache, objType, methodName, wrapper); } translator.pushFunction(luaState, wrapper); translator.push(luaState, true); return(2); } } else { // If we reach this point we found a static method, but can't use it in this context because the user passed in an instance translator.throwError(luaState, "can't pass instance to static method " + methodName); LuaAPI.lua_pushnil(luaState); } } else { // kevinh - we want to throw an exception because meerly returning 'nil' in this case // is not sufficient. valid data members may return nil and therefore there must be some // way to know the member just doesn't exist. translator.throwError(luaState, "unknown member name " + methodName); LuaAPI.lua_pushnil(luaState); } // push false because we are NOT returning a function (see luaIndexFunction) translator.push(luaState, false); return(2); }
public void EndPCall(int oldTop) { LuaAPI.lua_settop(L, oldTop - 1); }
public int call(IntPtr luaState) { object targetObject; bool failedCall = true; int nReturnValues = 0; if (!LuaAPI.lua_checkstack(luaState, 5)) { throw new LuaException("Lua stack overflow"); } bool isStatic = (_BindingType & BindingFlags.Static) == BindingFlags.Static; SetPendingException(null); if (isStatic) { targetObject = null; } else { targetObject = _ExtractTarget(luaState, 1); } if (_LastCalledMethod.cachedMethod != null) // Cached? { int numStackToSkip = isStatic ? 0 : 1; // If this is an instance invoe we will have an extra arg on the stack for the targetObject int numArgsPassed = LuaAPI.lua_gettop(luaState) - numStackToSkip; MethodBase method = _LastCalledMethod.cachedMethod; if (numArgsPassed == _LastCalledMethod.argTypes.Length) // No. of args match? { if (!LuaAPI.lua_checkstack(luaState, _LastCalledMethod.outList.Length + 6)) { throw new LuaException("Lua stack overflow"); } //这里 args 只是将 _LastCalledMethod.args 拿来做缓冲区用,避免内存再分配, 里面的值是可以干掉的 object[] args = _LastCalledMethod.args; try { for (int i = 0; i < _LastCalledMethod.argTypes.Length; i++) { MethodArgs type = _LastCalledMethod.argTypes[i]; object luaParamValue = type.extractValue(luaState, i + 1 + numStackToSkip); if (_LastCalledMethod.argTypes[i].isParamsArray) { args[type.index] = _Translator.tableToArray(luaParamValue, type.paramsArrayType); } else { args[type.index] = luaParamValue; } if (args[type.index] == null && !LuaAPI.lua_isnil(luaState, i + 1 + numStackToSkip)) { throw new LuaException("argument number " + (i + 1) + " is invalid"); } } if ((_BindingType & BindingFlags.Static) == BindingFlags.Static) { _Translator.push(luaState, method.Invoke(null, args)); } else { if (_LastCalledMethod.cachedMethod.IsConstructor) { _Translator.push(luaState, ((ConstructorInfo)method).Invoke(args)); } else { _Translator.push(luaState, method.Invoke(targetObject, args)); } } failedCall = false; } catch (TargetInvocationException e) { return(SetPendingException(e.GetBaseException())); } catch (Exception e) { if (_Members.Length == 1) { return(SetPendingException(e)); } } } } // Cache miss if (failedCall) { if (!isStatic) { if (targetObject == null) { _Translator.throwError(luaState, String.Format("instance method '{0}' requires a non null target object", _MethodName)); LuaAPI.lua_pushnil(luaState); return(1); } LuaAPI.lua_remove(luaState, 1); // Pops the receiver } bool hasMatch = false; string candidateName = null; foreach (MemberInfo member in _Members) { candidateName = member.ReflectedType.Name + "." + member.Name; MethodBase m = (MethodInfo)member; bool isMethod = _Translator.matchParameters(luaState, m, ref _LastCalledMethod); if (isMethod) { hasMatch = true; break; } } if (!hasMatch) { string msg = (candidateName == null) ? "invalid arguments to method call" : ("invalid arguments to method: " + candidateName); LuaAPI.luaL_error(luaState, msg); LuaAPI.lua_pushnil(luaState); ClearCachedArgs(); return(1); } } if (failedCall) { if (!LuaAPI.lua_checkstack(luaState, _LastCalledMethod.outList.Length + 6)) { ClearCachedArgs(); throw new LuaException("Lua stack overflow"); } try { if (isStatic) { _Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(null, _LastCalledMethod.args)); } else { if (_LastCalledMethod.cachedMethod.IsConstructor) { _Translator.push(luaState, ((ConstructorInfo)_LastCalledMethod.cachedMethod).Invoke(_LastCalledMethod.args)); } else { _Translator.push(luaState, _LastCalledMethod.cachedMethod.Invoke(targetObject, _LastCalledMethod.args)); } } } catch (TargetInvocationException e) { ClearCachedArgs(); return(SetPendingException(e.GetBaseException())); } catch (Exception e) { ClearCachedArgs(); return(SetPendingException(e)); } } // Pushes out and ref return values for (int index = 0; index < _LastCalledMethod.outList.Length; index++) { nReturnValues++; _Translator.push(luaState, _LastCalledMethod.args[_LastCalledMethod.outList[index]]); } //Desc: // if not return void,we need add 1, // or we will lost the function's return value // when call dotnet function like "int foo(arg1,out arg2,out arg3)" in lua code if (!_LastCalledMethod.IsReturnVoid && nReturnValues > 0) { nReturnValues++; } ClearCachedArgs(); return(nReturnValues < 1 ? 1 : nReturnValues); }
public static int setFieldOrProperty(IntPtr luaState) { ObjectTranslator translator = ObjectTranslator.FromState(luaState); object target = translator.getRawNetObject(luaState, 1); if (target == null) { translator.throwError(luaState, "trying to index and invalid object reference"); return(0); } Type type = target.GetType(); // First try to look up the parameter as a property name string detailMessage; bool didMember = translator.metaFunctions.trySetMember(luaState, type, target, BindingFlags.Instance | BindingFlags.IgnoreCase, out detailMessage); if (didMember) { return(0); // Must have found the property name } // We didn't find a property name, now see if we can use a [] style this accessor to set array contents try { if (type.IsArray && LuaAPI.lua_isnumber(luaState, 2)) { int index = (int)LuaAPI.lua_tonumber(luaState, 2); Array arr = (Array)target; object val = translator.getAsType(luaState, 3, arr.GetType().GetElementType()); arr.SetValue(val, index); } else { // Try to see if we have a this[] accessor MethodInfo setter = type.GetMethod("set_Item"); if (setter != null) { ParameterInfo[] args = setter.GetParameters(); Type valueType = args[1].ParameterType; // The new val ue the user specified object val = translator.getAsType(luaState, 3, valueType); Type indexType = args[0].ParameterType; object index = translator.getAsType(luaState, 2, indexType); object[] methodArgs = new object[2]; // Just call the indexer - if out of bounds an exception will happen methodArgs[0] = index; methodArgs[1] = val; setter.Invoke(target, methodArgs); } else { translator.throwError(luaState, detailMessage); // Pass the original message from trySetMember because it is probably best } } } catch (SEHException) { // If we are seeing a C++ exception - this must actually be for Lua's private use. Let it handle it throw; } catch (Exception e) { translator.metaFunctions.ThrowError(luaState, e); } return(0); }
private object getAsBoolean(IntPtr luaState, int stackPos) { return(LuaAPI.lua_toboolean(luaState, stackPos)); }
/* * Gets the table in the index positon of the Lua stack. */ internal LuaTable getTable(IntPtr luaState, int index) { LuaAPI.lua_pushvalue(luaState, index); return(new LuaTable(LuaAPI.luaL_ref(luaState, LuaAPI.LUA_REGISTRYINDEX), interpreter)); }
/// <summary> /// Tries to set a named property or field /// </summary> /// <returns>false if unable to find the named member, true for success</returns> private bool trySetMember(IntPtr luaState, IReflect targetType, object target, BindingFlags bindingType, out string detailMessage) { detailMessage = null; if (LuaAPI.lua_type(luaState, 2) != LuaTypes.LUA_TSTRING) { detailMessage = "property names must be strings"; return(false); } // We only look up property names by string string fieldName = LuaAPI.lua_tostring(luaState, 2); if (fieldName == null || fieldName.Length < 1 || !(char.IsLetter(fieldName[0]) || fieldName[0] == '_')) { detailMessage = "invalid property name"; return(false); } // Find our member via reflection or the cache MemberInfo member = (MemberInfo)checkMemberCache(memberCache, targetType, fieldName); if (member == null) { //CP: Removed NonPublic binding search and made case insensitive MemberInfo[] members = targetType.GetMember(fieldName, bindingType | BindingFlags.Public | BindingFlags.IgnoreCase /*| BindingFlags.NonPublic*/); if (members.Length > 0) { member = members[0]; setMemberCache(memberCache, targetType, fieldName, member); } else { detailMessage = "field or property '" + fieldName + "' does not exist"; return(false); } } if (member.MemberType == MemberTypes.Field) { FieldInfo field = (FieldInfo)member; object val = translator.getAsType(luaState, 3, field.FieldType); try { field.SetValue(target, val); } catch (Exception e) { ThrowError(luaState, e); } // We did a call return(true); } else if (member.MemberType == MemberTypes.Property) { PropertyInfo property = (PropertyInfo)member; object val = translator.getAsType(luaState, 3, property.PropertyType); try { property.SetValue(target, val, null); } catch (Exception e) { ThrowError(luaState, e); } return(true); } detailMessage = "'" + fieldName + "' is not a .net field or property"; return(false); }
public static int getMethod(IntPtr luaState) { ObjectTranslator translator = ObjectTranslator.FromState(luaState); object obj = translator.getRawNetObject(luaState, 1); if (obj == null) { translator.throwError(luaState, "trying to index an invalid object reference"); LuaAPI.lua_pushnil(luaState); return(1); } object index = translator.getObject(luaState, 2); string methodName = index as string; Type objType = obj.GetType(); try { if (methodName != null && translator.metaFunctions.isMemberPresent(objType, methodName)) { return(translator.metaFunctions.getMember(luaState, objType, obj, methodName, BindingFlags.Instance | BindingFlags.IgnoreCase)); } } catch { } bool failed = true; // Try to access by array if the type is right and index is an int (lua numbers always come across as double) if (objType.IsArray && index is double) { int intIndex = (int)((double)index); Array aa = obj as Array; if (intIndex >= aa.Length) { return(translator.pushError(luaState, "array index out of bounds: " + intIndex + " " + aa.Length)); } object val = aa.GetValue(intIndex); translator.push(luaState, val); failed = false; } else { // Try to use get_Item to index into this .net object //MethodInfo getter = objType.GetMethod("get_Item"); // issue here is that there may be multiple indexers.. MethodInfo[] methods = objType.GetMethods(); foreach (MethodInfo mInfo in methods) { if (mInfo.Name == "get_Item") { //check if the signature matches the input if (mInfo.GetParameters().Length == 1) { MethodInfo getter = mInfo; ParameterInfo[] actualParms = (getter != null) ? getter.GetParameters() : null; if (actualParms == null || actualParms.Length != 1) { return(translator.pushError(luaState, "method not found (or no indexer): " + index)); } else { // Get the index in a form acceptable to the getter index = translator.getAsType(luaState, 2, actualParms[0].ParameterType); // Just call the indexer - if out of bounds an exception will happen try { object result = getter.Invoke(obj, new object[] { index }); translator.push(luaState, result); failed = false; } catch (TargetInvocationException e) { // Provide a more readable description for the common case of key not found if (e.InnerException is KeyNotFoundException) { return(translator.pushError(luaState, "key '" + index + "' not found ")); } else { return(translator.pushError(luaState, "exception indexing '" + index + "' " + e.Message)); } } } } } } } if (failed) { return(translator.pushError(luaState, "cannot find " + index)); } LuaAPI.lua_pushboolean(luaState, false); return(2); }
internal void throwError(IntPtr luaState, string message) { LuaAPI.luaL_error(luaState, message); }
/* * Matches a method against its arguments in the Lua stack. Returns * if the match was succesful. It it was also returns the information * necessary to invoke the method. */ internal bool matchParameters(IntPtr luaState, MethodBase method, ref MethodCache methodCache) { ExtractValue extractValue; bool isMethod = true; ParameterInfo[] paramInfo = method.GetParameters(); int currentLuaParam = 1; int nLuaParams = LuaAPI.lua_gettop(luaState); ArrayList paramList = new ArrayList(); List <int> outList = new List <int>(); List <MethodArgs> argTypes = new List <MethodArgs>(); foreach (ParameterInfo currentNetParam in paramInfo) { if (!currentNetParam.IsIn && currentNetParam.IsOut) // Skips out params { outList.Add(paramList.Add(null)); } else if (currentLuaParam > nLuaParams) // Adds optional parameters { if (currentNetParam.IsOptional) { paramList.Add(currentNetParam.DefaultValue); } else { isMethod = false; break; } } else if (_IsTypeCorrect(luaState, currentLuaParam, currentNetParam, out extractValue)) // Type checking { int index = paramList.Add(extractValue(luaState, currentLuaParam)); MethodArgs methodArg = new MethodArgs(); methodArg.index = index; methodArg.extractValue = extractValue; argTypes.Add(methodArg); if (currentNetParam.ParameterType.IsByRef) { outList.Add(index); } currentLuaParam++; } // Type does not match, ignore if the parameter is optional else if (_IsParamsArray(luaState, currentLuaParam, currentNetParam, out extractValue)) { object luaParamValue = extractValue(luaState, currentLuaParam); Type paramArrayType = currentNetParam.ParameterType.GetElementType(); Array paramArray = TableToArray(luaParamValue, paramArrayType); int index = paramList.Add(paramArray); MethodArgs methodArg = new MethodArgs(); methodArg.index = index; methodArg.extractValue = extractValue; methodArg.isParamsArray = true; methodArg.paramsArrayType = paramArrayType; argTypes.Add(methodArg); currentLuaParam++; } else if (currentNetParam.IsOptional) { paramList.Add(currentNetParam.DefaultValue); } else // No match { isMethod = false; break; } } if (currentLuaParam != nLuaParams + 1) // Number of parameters does not match { isMethod = false; } if (isMethod) { methodCache.args = paramList.ToArray(); methodCache.cachedMethod = method; methodCache.outList = outList.ToArray(); methodCache.argTypes = argTypes.ToArray(); } return(isMethod); }
public static int panic(IntPtr L) { string reason = String.Format("unprotected error in call to Lua API ({0})", LuaAPI.lua_tostring(L, -1)); LuaAPI.lua_pop(L, 1); throw new LuaException(reason); }
/* * Gets the function in the index positon of the Lua stack. */ internal LuaFunction getFunction(IntPtr luaState, int index) { LuaAPI.lua_pushvalue(luaState, index); return(new LuaFunction(LuaAPI.luaL_ref(luaState, LuaAPI.LUA_REGISTRYINDEX), interpreter)); }
internal ExtractValue checkType(IntPtr luaState, int stackPos, Type paramType) { LuaTypes luatype = LuaAPI.lua_type(luaState, stackPos); if (paramType.IsByRef) { paramType = paramType.GetElementType(); } Type underlyingType = Nullable.GetUnderlyingType(paramType); if (underlyingType != null) { paramType = underlyingType; // Silently convert nullable types to their non null requics } long runtimeHandleValue = paramType.TypeHandle.Value.ToInt64(); if (paramType.Equals(typeof(object))) { return(extractValues[runtimeHandleValue]); } //CP: Added support for generic parameters if (paramType.IsGenericParameter) { if (luatype == LuaTypes.LUA_TBOOLEAN) { return(extractValues[typeof(bool).TypeHandle.Value.ToInt64()]); } else if (luatype == LuaTypes.LUA_TSTRING) { return(extractValues[typeof(string).TypeHandle.Value.ToInt64()]); } else if (luatype == LuaTypes.LUA_TTABLE) { return(extractValues[typeof(LuaTable).TypeHandle.Value.ToInt64()]); } else if (luatype == LuaTypes.LUA_TUSERDATA) { return(extractValues[typeof(object).TypeHandle.Value.ToInt64()]); } else if (luatype == LuaTypes.LUA_TFUNCTION) { return(extractValues[typeof(LuaFunction).TypeHandle.Value.ToInt64()]); } else if (luatype == LuaTypes.LUA_TNUMBER) { return(extractValues[typeof(double).TypeHandle.Value.ToInt64()]); } } if (paramType.IsValueType && luatype == LuaTypes.LUA_TTABLE) { int oldTop = LuaAPI.lua_gettop(luaState); ExtractValue ret = null; LuaAPI.lua_pushvalue(luaState, stackPos); LuaAPI.lua_pushstring(luaState, "class"); LuaAPI.lua_gettable(luaState, -2); if (!LuaAPI.lua_isnil(luaState, -1)) { string cls = LuaAPI.lua_tostring(luaState, -1); if (cls == "Vector3" && paramType == typeof(Vector3)) { ret = extractValues[typeof(Vector3).TypeHandle.Value.ToInt64()]; } else if (cls == "Vector2" && paramType == typeof(Vector2)) { ret = extractValues[typeof(Vector2).TypeHandle.Value.ToInt64()]; } else if (cls == "Quaternion" && paramType == typeof(Quaternion)) { ret = extractValues[typeof(Quaternion).TypeHandle.Value.ToInt64()]; } else if (cls == "Color" && paramType == typeof(Color)) { ret = extractValues[typeof(Color).TypeHandle.Value.ToInt64()]; } else if (cls == "Vector4" && paramType == typeof(Vector4)) { ret = extractValues[typeof(Vector4).TypeHandle.Value.ToInt64()]; } else if (cls == "Ray" && paramType == typeof(Ray)) { ret = extractValues[typeof(Ray).TypeHandle.Value.ToInt64()]; } else { ret = null; } } LuaAPI.lua_settop(luaState, oldTop); if (ret != null) { return(ret); } } if (LuaAPI.lua_isnumber(luaState, stackPos)) { return(extractValues[runtimeHandleValue]); } if (paramType == typeof(bool)) { if (LuaAPI.lua_isboolean(luaState, stackPos)) { return(extractValues[runtimeHandleValue]); } } else if (paramType == typeof(string)) { if (LuaAPI.lua_isstring(luaState, stackPos)) { return(extractValues[runtimeHandleValue]); } else if (luatype == LuaTypes.LUA_TNIL) { return(extractNetObject); // kevinh - silently convert nil to a null string pointer } } else if (paramType == typeof(LuaTable)) { if (luatype == LuaTypes.LUA_TTABLE) { return(extractValues[runtimeHandleValue]); } } else if (paramType == typeof(LuaFunction)) { if (luatype == LuaTypes.LUA_TFUNCTION) { return(extractValues[runtimeHandleValue]); } } else if (typeof(Delegate).IsAssignableFrom(paramType) && luatype == LuaTypes.LUA_TFUNCTION) { translator.throwError(luaState, "Delegates not implemnented"); } else if (paramType.IsInterface && luatype == LuaTypes.LUA_TTABLE) { translator.throwError(luaState, "Interfaces not implemnented"); } else if ((paramType.IsInterface || paramType.IsClass) && luatype == LuaTypes.LUA_TNIL) { // kevinh - allow nil to be silently converted to null - extractNetObject will return null when the item ain't found return(extractNetObject); } else if (LuaAPI.lua_type(luaState, stackPos) == LuaTypes.LUA_TTABLE) { if (LuaTypes.LUA_TNIL != LuaAPI.luaL_getmetafield(luaState, stackPos, "__index")) { object obj = translator.getNetObject(luaState, -1); LuaAPI.lua_settop(luaState, -2); if (obj != null && paramType.IsAssignableFrom(obj.GetType())) { return(extractNetObject); } } } else { //object obj = translator.getNetObject(luaState, stackPos); //topameng 修改这里使支持注册到c#的lua类 object obj = translator.getRawNetObject(luaState, stackPos); if (obj != null && paramType.IsAssignableFrom(obj.GetType())) { return(extractNetObject); } } return(null); }
internal void push(IntPtr luaState) { LuaAPI.ulua_rawgeti(luaState, LuaAPI.LUA_REGISTRYINDEX, _Reference); }
public int pushError(IntPtr luaState, string msg) { LuaAPI.lua_pushnil(luaState); LuaAPI.lua_pushstring(luaState, msg); return(2); }