public static void SetPath(string v_path) { Lua.LuaFunction fun = lua_instence.GetFunction("setPath"); if (fun != null) { fun.Call(v_path); } }
public static void DoMain() { Lua.LuaFunction fun = lua_instence.GetFunction("main"); try { fun.Call(); } catch (Exception ex) { Debug.Exception("执行main报错,信息是" + ex.ToString()); } }
/// <summary> /// 执行Lua方法 /// </summary> protected object[] CallMethod(string func, GameObject go) { if (nluaMgr == null) { return(null); } string funcName = name + "." + func; funcName = funcName.Replace("(Clone)", ""); NLua.LuaFunction luafunc = nmgr.GetFunction(funcName); if (luafunc == null) { return(null); } else { return(luafunc.Call(funcName)); } }
public static void DoMain() { Lua.LuaFunction fun = lua_instence.GetFunction("main"); fun.Call(); }
private bool lua_PostWebRequest(string url, string postdata, LuaFunction func) { AsyncWebRequest req = new AsyncWebRequest(url, postdata); webrequestQueue.Enqueue(req); Plugin callerplugin = Plugin.CurrentPlugin; req.OnResponse += (r) => { try { func.Call(r.ResponseCode, r.Response); } catch (Exception ex) { //Debug.LogError(string.Format("Error in webrequest callback: {0}", ex)); Logger.Error(string.Format("Error in webrequest callback ({0})", callerplugin), ex); } }; return true; }
public Decision CreateDecision( string desc, LuaFunction func, int cost ) { var d = new Decision( desc, () => { func.Call(); }, cost ); return d; }
public static Action Action(LuaFunction func) { Action action = () => { func.Call(); }; return action; }
private Timer lua_NewTimer(float delay, int numiterations, LuaFunction func) { Plugin callerplugin = Plugin.CurrentPlugin; Action callback = new Action(() => { try { func.Call(); } catch (Exception ex) { //Logger.Error(string.Format("Error in timer ({1}): {0}", ex)); Logger.Error(string.Format("Error in timer ({0})", callerplugin), ex); } }); Timer tmr = Timer.Create(delay, numiterations, callback); timers.Add(tmr); tmr.OnFinished += (t) => timers.Remove(t); return tmr; }
// CP: Fix provided by Ben Bryant for delegates with one param // link: http://luaforge.net/forum/message.php?msg_id=9318 public void handleEvent(object[] args) { handler.Call(args); }
private Main() { try { // Determine the absolute path of the server instance serverpath = Path.GetDirectoryName(Path.GetFullPath(Application.dataPath)); string[] cmdline = Environment.GetCommandLineArgs(); for (int i = 0; i < cmdline.Length - 1; i++) { string arg = cmdline[i].ToLower(); if (arg == "-serverinstancedir" || arg == "-oxidedir") { try { serverpath = Path.GetFullPath(cmdline[++i]); } catch (Exception ex) { Logger.Error("Failed to read server instance directory from command line!", ex); } } } // Ensure directories exist if (!Directory.Exists(serverpath)) Directory.CreateDirectory(serverpath); if (!Directory.Exists(GetPath("plugins"))) Directory.CreateDirectory(GetPath("plugins")); if (!Directory.Exists(GetPath("data"))) Directory.CreateDirectory(GetPath("data")); if (!Directory.Exists(GetPath("logs"))) Directory.CreateDirectory(GetPath("logs")); Logger.Message(string.Format("Loading at {0}...", serverpath)); // Initialise the Unity component oxideobject = new GameObject("Oxide"); oxidecomponent = oxideobject.AddComponent<OxideComponent>(); oxidecomponent.Oxide = this; // Hook things that we can't hook using the IL injector var serverinit = UnityEngine.Object.FindObjectOfType(Type.GetType("ServerInit, Assembly-CSharp")) as MonoBehaviour; serverinit.gameObject.AddComponent<ServerInitHook>(); // Initialise needed maps and collections datafiles = new Dictionary<string, Datafile>(); plugins = new Dictionary<string, LuaTable>(); timers = new HashSet<Timer>(); webrequests = new HashSet<AsyncWebRequest>(); // Initialise the lua state lua = new Lua(); lua["os"] = null; lua["io"] = null; lua["require"] = null; lua["dofile"] = null; lua["package"] = null; lua["luanet"] = null; lua["load"] = null; // Register functions lua.NewTable("cs"); RegisterFunction("cs.print", "lua_Print"); RegisterFunction("cs.error", "lua_Error"); RegisterFunction("cs.callplugins", "lua_CallPlugins"); RegisterFunction("cs.findplugin", "lua_FindPlugin"); RegisterFunction("cs.requeststatic", "lua_RequestStatic"); RegisterFunction("cs.registerstaticmethod", "lua_RegisterStaticMethod"); RegisterFunction("cs.requeststaticproperty", "lua_RequestStaticProperty"); RegisterFunction("cs.requestproperty", "lua_RequestProperty"); RegisterFunction("cs.requeststaticfield", "lua_RequestStaticField"); RegisterFunction("cs.requestfield", "lua_RequestField"); RegisterFunction("cs.requestenum", "lua_RequestEnum"); RegisterFunction("cs.readproperty", "lua_ReadProperty"); RegisterFunction("cs.readfield", "lua_ReadField"); RegisterFunction("cs.castreadproperty", "lua_CastReadProperty"); RegisterFunction("cs.castreadfield", "lua_CastReadField"); RegisterFunction("cs.readulongpropertyasuint", "lua_ReadULongPropertyAsUInt"); RegisterFunction("cs.readulongpropertyasstring", "lua_ReadULongPropertyAsString"); RegisterFunction("cs.readulongfieldasuint", "lua_ReadULongFieldAsUInt"); RegisterFunction("cs.readulongfieldasstring", "lua_ReadULongFieldAsString"); RegisterFunction("cs.reloadplugin", "lua_ReloadPlugin"); RegisterFunction("cs.getdatafile", "lua_GetDatafile"); RegisterFunction("cs.dump", "lua_Dump"); RegisterFunction("cs.createarrayfromtable", "lua_CreateArrayFromTable"); RegisterFunction("cs.createtablefromarray", "lua_CreateTableFromArray"); RegisterFunction("cs.gettype", "lua_GetType"); RegisterFunction("cs.makegenerictype", "lua_MakeGenericType"); RegisterFunction("cs.new", "lua_New"); RegisterFunction("cs.newarray", "lua_NewArray"); RegisterFunction("cs.convertandsetonarray", "lua_ConvertAndSetOnArray"); RegisterFunction("cs.getelementtype", "lua_GetElementType"); RegisterFunction("cs.newtimer", "lua_NewTimer"); RegisterFunction("cs.sendwebrequest", "lua_SendWebRequest"); RegisterFunction("cs.throwexception", "lua_ThrowException"); RegisterFunction("cs.gettimestamp", "lua_GetTimestamp"); RegisterFunction("cs.loadstring", "lua_LoadString"); // Register constants lua.NewTable("bf"); lua["bf.public_instance"] = BindingFlags.Public | BindingFlags.Instance; lua["bf.private_instance"] = BindingFlags.NonPublic | BindingFlags.Instance; lua["bf.public_static"] = BindingFlags.Public | BindingFlags.Static; lua["bf.private_static"] = BindingFlags.NonPublic | BindingFlags.Static; // Load the standard library Logger.Message("Loading standard library..."); lua.LoadString(LuaOxideSTL.csfunc, "csfunc.stl").Call(); lua.LoadString(LuaOxideSTL.json, "json.stl").Call(); lua.LoadString(LuaOxideSTL.util, "util.stl").Call(); lua.LoadString(LuaOxideSTL.type, "type.stl").Call(); lua.LoadString(LuaOxideSTL.baseplugin, "baseplugin.stl").Call(); lua.LoadString(LuaOxideSTL.rust, "rust.stl").Call(); lua.LoadString(LuaOxideSTL.config, "config.stl").Call(); lua.LoadString(LuaOxideSTL.plugins, "plugins.stl").Call(); lua.LoadString(LuaOxideSTL.timer, "timer.stl").Call(); lua.LoadString(LuaOxideSTL.webrequest, "webrequest.stl").Call(); lua.LoadString(LuaOxideSTL.validate, "validate.stl").Call(); // Read back required functions callunpacked = lua["callunpacked"] as LuaFunction; createplugin = lua["createplugin"] as LuaFunction; // Load all plugins Logger.Message("Loading plugins..."); string[] files = Directory.GetFiles(GetPath("plugins"), "*.lua"); foreach (string file in files) { string pluginname = Path.GetFileNameWithoutExtension(file); LuaTable plugininstance = createplugin.Call()[0] as LuaTable; lua["PLUGIN"] = plugininstance; plugininstance["Filename"] = file; plugininstance["Name"] = pluginname; try { currentplugin = pluginname; string code = File.ReadAllText(GetPath(file)); lua.LoadString(code, file).Call(); plugins.Add(pluginname, plugininstance); lua["PLUGIN"] = null; } catch (NLua.Exceptions.LuaScriptException luaex) { Logger.Error(string.Format("Failed to load plugin '{0}'!", file), luaex); } } // Check plugin dependencies HashSet<string> toremove = new HashSet<string>(); int numits = 0; while (numits == 0 || toremove.Count > 0) { toremove.Clear(); foreach (var pair in plugins) { LuaTable dependencies = pair.Value["Depends"] as LuaTable; if (dependencies != null) { foreach (var key in dependencies.Keys) { object value = dependencies[key]; if (value is string) { if (!plugins.ContainsKey((string)value) || toremove.Contains((string)value)) { Logger.Error(string.Format("The plugin '{0}' depends on missing or unloaded plugin '{1}' and won't be loaded!", pair.Key, value)); toremove.Add(pair.Key); break; } } } } } foreach (string name in toremove) plugins.Remove(name); numits++; } // Call Init and PostInit on all plugins CallPlugin("Init", null); CallPlugin("PostInit", null); } catch (Exception ex) { Logger.Error(string.Format("Error loading oxide!"), ex); } }
static IEnumerator onDownLoadCompleted(LuaFunction completeHander, object complete_param,HTTPRequest req,HTTPResponse resp) { yield return new WaitForEndOfFrame(); if (complete_param != null) { completeHander.Call(req, resp, complete_param); } else { completeHander.Call(req, resp); } }
//异步HTTP public static void SendRequest(string url, string data, LuaFunction completeHandler) { //如果web页面是静态返回数据,请用HTTPMethods.Get var request = new HTTPRequest(new Uri(url), HTTPMethods.Get, (req, resp) => { if (completeHandler != null) { completeHandler.Call(req, resp); //req, resp 需要暴露给slua导出 } }); request.RawData = Encoding.UTF8.GetBytes(data); request.ConnectTimeout = TimeSpan.FromSeconds(3);//3秒超时 request.Send(); }
//异步下载,参数 complete_param 是完成回调的执行参数 public static void DownLoad(string SrcFilePath, string SaveFilePath, object complete_param, LuaFunction progressHander, LuaFunction completeHander) { var request = new HTTPRequest(new Uri(SrcFilePath), (req, resp) => { List<byte[]> fragments = resp.GetStreamedFragments(); // Write out the downloaded data to a file: using (FileStream fs = new FileStream(SaveFilePath, FileMode.Append)) foreach (byte[] data in fragments) fs.Write(data, 0, data.Length); if (resp.IsStreamingFinished) { if (completeHander != null) { API.StartCoroutine(onDownLoadCompleted(completeHander,complete_param, req,resp)); Debug.Log("Download finished!"); } } }); request.OnProgress = (req, downloaded, length) => { if (progressHander != null) { double pg = Math.Round((float)downloaded / (float)length, 2); progressHander.Call(pg); } }; request.UseStreaming = true; request.StreamFragmentSize = 1 * 1024 * 1024; // 1 megabyte request.DisableCache = true; // already saving to a file, so turn off caching request.Send(); }
public static UIEventListener.VoidDelegate VoidDelegate(LuaFunction func) { UIEventListener.VoidDelegate action = (go) => { func.Call(go); }; return action; }
private IEnumerator doCoroutine(YieldInstruction ins, LuaFunction func, params object[] args) { yield return ins; if (args != null) { func.Call(args); } else { func.Call(); } }
private IEnumerator doInvoke(float delaytime, LuaFunction func, params object[] args) { yield return new WaitForSeconds(delaytime); if (args != null) { func.Call(args); } else { func.Call(); } }
private void HandleCommandCallback(LuaFunction func, string cmd, CommandType type, IPlayer caller, string[] args) { LuaEnvironment.NewTable("tmp"); LuaTable argsTable = LuaEnvironment["tmp"] as LuaTable; LuaEnvironment["tmp"] = null; for (int i = 0; i < args.Length; i++) { argsTable[i + 1] = args[i]; } try { func.Call(Table, caller, argsTable); } catch (Exception) { // TODO: Error handling and stuff throw; } }
private bool lua_SendWebRequest(string url, LuaFunction func) { if (webrequests.Count > 3) { return false; } AsyncWebRequest req = new AsyncWebRequest(url); webrequests.Add(req); Plugin callerplugin = Plugin.CurrentPlugin; req.OnResponse += (r) => { try { func.Call(r.ResponseCode, r.Response); } catch (Exception ex) { //Debug.LogError(string.Format("Error in webrequest callback: {0}", ex)); Logger.Error(string.Format("Error in webrequest callback ({0})", callerplugin), ex); } }; return true; }
public static ClientChatLineDelegate MakeDelegate(LuaFunction lua) { return((int groupId, ref string message, ref EnumHandling handled) => { lua.Call(groupId, message, handled); }); }