public ChatChannelLua(LuaScript script) { Script = script; Script.ReloadFile(); Name = (string) Script["Name"]; Description = (string) (Script["Description"] ?? string.Empty); Alias = (string) (Script["Alias"] ?? string.Empty); }
public CommandLua(Server server, LuaScript script) : base(server) { Script = script; Script["World"] = World; Script.ReloadFile(); Name = (string) Script["Name"]; Description = (string) (Script["Description"] ?? string.Empty); Aliases = Lua.ToLuaTable(Script["Aliases"]).ToList().Select(obj => obj.ToString().Replace("\"", "")); Permissions = ParsePermissionFlags((string) (Script["Permission"] ?? string.Empty)); }
public void loadLua(LuaScript script) { //F**k LUA /*std::string scriptloc = "../../lua/champions/" + owner->getType() + "/" + getStringForSlot() + ".lua"; //lua/championname/(q/w/e/r), example: /lua/Ezreal/q, also for stuff like nidalee cougar they will have diff folders! CORE_INFO("Spell script loc is: %s", scriptloc.c_str()); script.lua.script("package.path = '../../lua/lib/?.lua;' .. package.path"); //automatically load vector lib so scripters dont have to worry about path script.lua.set_function("getOwnerX", [this]() { return owner->getX(); }); script.lua.set_function("getOwnerY", [this]() { return owner->getY(); }); script.lua.set_function("getSpellLevel", [this]() { return getLevel(); }); script.lua.set_function("getOwnerLevel", [this]() { return owner->getStats().getLevel(); }); script.lua.set_function("getChampionModel", [this]() { return owner->getModel(); }); script.lua.set_function("getCastTarget", [this]() { return this->target; }); script.lua.set_function("setChampionModel", [this](const std::string&newModel) { owner->setModel(newModel); return; }); script.lua.set_function("getSpellToX", [this]() { return x; }); script.lua.set_function("getSpellToY", [this]() { return y; }); script.lua.set_function("getRange", [this]() { return castRange; }); script.lua.set_function("teleportTo", [this](float _x, float _y) { // expose teleport to lua owner->getMap()->getGame()->notifyTeleport(owner, _x, _y); return; }); script.lua.set_function("isWalkable", [this](float _x, float _y) { return owner->getMap()->isWalkable(_x, _y); }); /*script.lua.set_function("addMovementSpeedBuff", [this](Unit* u, float amount, float duration) { // expose teleport to lua Buff* b = new Buff(duration); b->setMovementSpeedPercentModifier(amount); u->addBuff(b); u->getStats().addMovementSpeedPercentageModifier(b->getMovementSpeedPercentModifier()); return; });*/ //F**k LUA /* script.lua.set_function("addBuff", [this](Buff b, Unit * u){ u->addBuff(new Buff(b)); return; }); script.lua.set_function("getEffectValue", [this](uint32 effectNo) { if (effectNo >= effects.size() || level >= effects[effectNo].size()) { return 0.f; } return effects[effectNo][level]; }); script.lua.set_function("getOwner", [this]() { return owner; }); script.lua.set_function("getTeam", [this](Object * o) { return o->getTeam(); }); script.lua.set_function("isDead", [this](Unit * u) { return u->isDead(); }); script.lua.set_function("getProjectileSpeed", [this]() { return projectileSpeed; }); script.lua.set_function("getCoefficient", [this]() { return coefficient; }); script.lua.set_function("addProjectile", [this](float toX, float toY) { Projectile* p = new Projectile(owner->getMap(), GetNewNetID(), owner->getX(), owner->getY(), lineWidth, owner, new Target(toX, toY), this, projectileSpeed, RAFFile::getHash(spellName + "Missile"), projectileFlags ? projectileFlags : flags); owner->getMap()->addObject(p); owner->getMap()->getGame()->notifyProjectileSpawn(p); return; }); script.lua.set_function("addProjectileTarget", [this](Target * t) { Projectile* p = new Projectile(owner->getMap(), GetNewNetID(), owner->getX(), owner->getY(), lineWidth, owner, t, this, projectileSpeed, RAFFile::getHash(spellName + "Missile"), projectileFlags ? projectileFlags : flags); owner->getMap()->addObject(p); owner->getMap()->getGame()->notifyProjectileSpawn(p); return; }); script.lua.set_function("addProjectileCustom", [this](const std::string&name, float projSpeed, float toX, float toY) { Projectile* p = new Projectile(owner->getMap(), GetNewNetID(), owner->getX(), owner->getY(), lineWidth, owner, new Target(toX, toY), this, projectileSpeed, RAFFile::getHash(name), projectileFlags ? projectileFlags : flags); owner->getMap()->addObject(p); owner->getMap()->getGame()->notifyProjectileSpawn(p); return; }); script.lua.set_function("addProjectileTargetCustom", [this](const std::string&name, float projSpeed, Target *t) { Projectile* p = new Projectile(owner->getMap(), GetNewNetID(), owner->getX(), owner->getY(), lineWidth, owner, t, this, projectileSpeed, RAFFile::getHash(name), projectileFlags ? projectileFlags : flags); owner->getMap()->addObject(p); owner->getMap()->getGame()->notifyProjectileSpawn(p); return; }); //For spells that don't require SpawnProjectile, but for which we still need to track the projectile server-side script.lua.set_function("addServerProjectile", [this](float toX, float toY) { Projectile* p = new Projectile(owner->getMap(), futureProjNetId, owner->getX(), owner->getY(), lineWidth, owner, new Target(toX, toY), this, projectileSpeed, 0, projectileFlags ? projectileFlags : flags); owner->getMap()->addObject(p); return; }); script.lua.set_function("addParticle", [this](const std::string&particle, float toX, float toY) { Target* t = new Target(toX, toY); owner->getMap()->getGame()->notifyParticleSpawn(owner, t, particle); delete t; return; }); script.lua.set_function("addParticleTarget", [this](const std::string&particle, Target* u) { owner->getMap()->getGame()->notifyParticleSpawn(owner, u, particle); return; }); script.lua.set_function("spellAnimation", [this](const std::string&animation, Unit* u) { owner->getMap()->getGame()->notifySpellAnimation(u, animation); return; }); // TODO: Set multiple animations script.lua.set_function("setAnimation", [this](const std::string&animation1, const std::string&animation2, Unit* u) { std::vector < std::pair < std::string, std::string>> animationPairs; animationPairs.push_back(std::make_pair(animation1, animation2)); owner->getMap()->getGame()->notifySetAnimation(u, animationPairs); return; }); script.lua.set_function("resetAnimations", [this](Unit * u) { std::vector < std::pair < std::string, std::string>> animationPairs; owner->getMap()->getGame()->notifySetAnimation(u, animationPairs); return; }); script.lua.set_function("dashTo", [this](Unit * u, float x, float y, float dashSpeed) { u->dashTo(x, y, dashSpeed); u->setTargetUnit(0); owner->getMap()->getGame()->notifyDash(u, x, y, dashSpeed); return; }); script.lua.set_function("getUnitsInRange", [this](Target * t, float range, bool isAlive) { return owner->getMap()->getUnitsInRange(t, range, isAlive); }); script.lua.set_function("getChampionsInRange", [this](Target * t, float range, bool isAlive) { return owner->getMap()->getChampionsInRange(t, range, isAlive); }); try { script.loadScript(scriptloc); //todo: abstract class that loads a lua file for any lua } catch (sol::error e) {//lua error? don't crash the whole server CORE_ERROR("Error in spell script: %s", e.what()); } */ }
public RedisResult ScriptEvaluate(LuaScript script, object parameters = null, CommandFlags flags = CommandFlags.None) { // TODO: The return value could contain prefixed keys. It might make sense to 'unprefix' those? return(script.Evaluate(Inner, parameters, Prefix, flags)); }
public static LoadedLuaScript ScriptLoad(LuaScript script, CommandFlags flags = CommandFlags.None) { return(Server.ScriptLoad(script, flags)); }
static void Main(string[] args) { Console.WriteLine("Asayo Discord Bot [NX]"); if (args.Length != 0) { if (args[0] == "clear") { int count = 0; var current_dir = Directory.GetCurrentDirectory(); foreach (var item in Directory.GetFiles(current_dir, "*.log")) { try { File.Delete(item); count++; } catch (Exception) { } } Console.WriteLine(count + " File Cleared"); Console.ReadKey(); return; } } Asayo asayo = new Asayo(); MoonSharp.Interpreter.UserData.RegisterAssembly(); foreach (var item in Directory.GetFiles(Directory.GetCurrentDirectory(), "*.lua")) { new Lua.LuaScript(item).Execute(); } if (!File.Exists("conf.json")) { Console.WriteLine("Welcome to Asayo Discord Bot Configuration !!"); Console.WriteLine("Press any key to start configure the bot..."); Console.ReadKey(true); Console.Write("Bot Token : "); var token = Console.ReadLine(); Console.WriteLine(); /*Console.Write("");*/ asayo.Configuration = new ConfigurationJson() { Token = token }; ConfigurationJson.Save(asayo.Configuration, "conf.json"); Console.Clear(); } if (asayo.Configuration == null) { asayo.Configuration = ConfigurationJson.Read("conf.json"); } asayo.Start(); bool exit = false; while (!exit) { var command = Console.ReadLine(); if (command.ToLower() == "exit") { exit = true; } if (command.ToLower() == "test") { Console.WriteLine("Application is Up"); } if (command.ToLower() == "save") { asayo.Save(); } if (command.ToLower() == "reload") { asayo.Reload(); } if (command.ToLower() == "commands") { Console.WriteLine("Command Count : " + Asayo.Instance.CommandManager.Count); foreach (var item in Asayo.Instance.CommandManager.GetCommands()) { Console.WriteLine(item.Name); } } if (command.ToLower() == "stats") { Console.WriteLine("LuaScript Instance : " + Lua.LuaScript.ScriptsInstances.Count); Console.WriteLine("Command Count : " + asayo.CommandManager.Count); Console.WriteLine("Guild in GuildVars Count: " + asayo.GuildVars.FullCount); Console.WriteLine("Guild Variables Count : " + asayo.GuildVars.FullCount); } if (command.ToLower() == "luas") { Console.WriteLine(LuaScript.ScriptsInstances.Count + " LuaScript Instance"); foreach (var item in LuaScript.ScriptsInstances) { Console.WriteLine(item.ID + " | " + item.Filename); } } if (command.ToLower() == "lua") { MoonSharp.Interpreter.Script s = LuaScript.CreateScriptWithLuaScript(); LuaConsole(s); } if (command.StartsWith("load ")) { var fn = command.Replace("load ", "").TrimStart(' '); new LuaScript(fn).Execute(); } if (command.StartsWith("lua ")) { var id = int.Parse(command.Replace("lua ", "").Trim(' ')); var script = LuaScript.ScriptsInstances[id]; LuaConsole(script.Script); } if (command.StartsWith("ban ")) { var id = ulong.Parse(command.Replace("ban ", "").Trim(' ')); Asayo.Instance.BannedUser.Add(id); Console.WriteLine(id + "is now banned"); } if (command.StartsWith("unban ")) { var id = ulong.Parse(command.Replace("unban ", "").Trim(' ')); Asayo.Instance.BannedUser.Remove(id); Console.WriteLine(id + "is now unbanned"); } if (command.ToLower() == "help") { Console.WriteLine(Version + " [Console-Help]"); Console.WriteLine("\thelp : Show console help"); Console.WriteLine("\tload <file> : Load lua script"); Console.WriteLine("\tlua [id] : Open lua interpreter (id can be not exit)"); Console.WriteLine("\tluas : Show loaded script with id"); Console.WriteLine("\tcommands : Show a list of reg commands"); Console.WriteLine("\tstats : Show Asayo Statistic"); Console.WriteLine("\tban <id> : Ban user to use your bot"); Console.WriteLine("\tunban <id> : Un-Ban user to use your bot"); Console.WriteLine("\treload : Reload the bot"); Console.WriteLine("\tsave : Save the bot"); Console.WriteLine("\texit : Quit the bot"); } } }
/// <summary> /// 获取商户的第三方订单通知 /// </summary> /// <param name="id"></param> /// <returns></returns> private async Task <List <RedisValue> > GetThirdOrdersAsync(int id) { var result = await database.ScriptEvaluateAsync(LuaScript.Prepare(@" local res = redis.call('KEYS', @keypattern) return res"), new { keypattern = $"Jiandanmao:Notify:ThirdOrder:{id}:*" }); if (result.IsNull) { return(null); } var keys = (RedisKey[])result; var vals = await database.StringGetAsync(keys); if (vals.Length == 0) { return(null); } var now = DateTime.Now; var ids = new List <RedisKey>(); //DateTime? time; //var list = vals.Where(a => //{ // var obj = JObject.Parse(a); // // 如果存在预约时间,且预约时间大于当前时间一小时,则暂不发出通知 // if (obj["deliveryTime"] != null // && (time = obj["deliveryTime"].Value<DateTime?>()) != null // && time > now.AddHours(1)) // { // return false; // } // ids.Add($"Jiandanmao:Notify:ThirdOrder:{id}:{obj["id"].Value<int>()}"); // return true; //}).ToList(); //await database.KeyDeleteAsync(ids.ToArray()); //return list; #region 包含预订单逻辑 var results = new List <RedisValue>(); vals.ForEach(a => { var obj = JObject.Parse(a); // 订单对象 var time = obj["deliveryTime"].Value <DateTime?>(); // 预约时间 var key = $"Jiandanmao:Notify:ThirdOrder:{id}:{obj["id"].Value<int>()}"; // 订单key if (time == null || time < now.AddMinutes(50)) // 如果预约时间为空或者距离当前时间小于50分钟,则直接输出 { results.Add(a); ids.Add(key); return; } // 预订单则需要判断前台打印与后台打印逻辑 var mode = obj["printType"].Value <int>(); if (mode == 3) // 仅考虑整单打印的情况 { obj["printType"] = 1; // 将订单打印方式改为打印前台小票 results.Add(JsonConvert.SerializeObject(obj)); // 添加到输出结果 obj["printType"] = 2; // 然后将打印方式改为打印后台小票 // 重新设置打印任务 var timespan = time.Value.AddHours(2) - now; database.StringSetAsync(key, JsonConvert.SerializeObject(obj), timespan); } }); await database.KeyDeleteAsync(ids.ToArray()); return(results); #endregion //var results = new List<RedisValue>(); //vals.ForEach(a => //{ // var obj = JObject.Parse(a); // 订单对象 // var key = $"Jiandanmao:Notify:ThirdOrder:{id}:{obj["id"].Value<int>()}"; // 订单key // results.Add(a); // ids.Add(key); //}); //await database.KeyDeleteAsync(ids.ToArray()); //return results; }
public RedisCacheProvider(ConfigurationOptions options, MessagePack.MessagePackSerializerOptions mspOptions = null) : this() { Option = mspOptions ?? MessagePack.Resolvers.ContractlessStandardResolver.Options; Connection = ConnectionMultiplexer.Connect(options); var server = Connection.GetServer(Connection.GetEndPoints()[0]); _LuaCache = LuaScript.Prepare(@"redis.call('hset',@timerkey,'mode',@mode); redis.call('hset',@timerkey,'counter',@timer); redis.call('hset',@timerkey,'creation',@creation); redis.call('set',@key,@value);"); _LuaDel = LuaScript.Prepare(@"redis.call('del',@timerkey); redis.call('del',@key); return nil;"); _LuaGet = LuaScript.Prepare($@"local mode = tonumber(redis.call('hget',@timerkey,'mode')); if mode == nil then return nil; end if mode == {(byte)TimeOutMode.Never} then return redis.call('get',@key); elseif mode == {(byte)TimeOutMode.AccessCount} then local cnt = tonumber(redis.call('hincrby',@timerkey,'counter',-1)); if cnt > 0 then return redis.call('get',@key); elseif cnt == 0 then local tmp = redis.call('get',@key); redis.call('del',@timerkey); redis.call('del',@key); return tmp; else redis.call('del',@timerkey); redis.call('del',@key); return nil; end elseif mode == {(byte)TimeOutMode.FromCreate} then local crt = tonumber(redis.call('hget',@timerkey,'creation')); if @now - crt < tonumber(redis.call('hget',@timerkey,'counter')) then return redis.call('get',@key); else redis.call('del',@timerkey); redis.call('del',@key); return nil; end else local crt = tonumber(redis.call('hget',@timerkey,'creation')); if @now - crt < tonumber(redis.call('hget',@timerkey,'counter')) then redis.call('hset',@timerkey,'creation',@now); return redis.call('get',@key); else redis.call('del',@timerkey); redis.call('del',@key); return nil; end end "); _LuaExists = LuaScript.Prepare($@"local mode = tonumber(redis.call('hget',@timerkey,'mode')); if mode == nil then return 0; end if mode == {(byte)TimeOutMode.Never} then return 1 elseif mode == {(byte)TimeOutMode.AccessCount} then return 1 elseif mode == {(byte)TimeOutMode.FromCreate} then local crt = tonumber(redis.call('hget',@timerkey,'creation')); if @now - crt < tonumber(redis.call('hget',@timerkey,'counter')) then return 1 else redis.call('del',@timerkey); redis.call('del',@key); return 0; end else local crt = tonumber(redis.call('hget',@timerkey,'creation')); if @now - crt < tonumber(redis.call('hget',@timerkey,'counter')) then return 1 else redis.call('del',@timerkey); redis.call('del',@key); return 0; end end"); _LuaCacheSub = LuaScript.Prepare(@"redis.call('hset',@timerkey,'mode',@mode); redis.call('hset',@timerkey,'counter',@timer); redis.call('hset',@timerkey,'creation',@creation); redis.call('hset',@key,@subkey,@value);"); _LuaDelSub = LuaScript.Prepare(@"redis.call('del',@timerkey); redis.call('hdel',@key,@subkey); return nil;"); _LuaGetSub = LuaScript.Prepare($@"local mode = tonumber(redis.call('hget',@timerkey,'mode')); if mode == nil then return nil; end if mode == {(byte)TimeOutMode.Never} then return redis.call('hget',@key,@subkey); elseif mode == {(byte)TimeOutMode.AccessCount} then local cnt = tonumber(redis.call('hincrby',@timerkey,'counter',-1)); if cnt > 0 then return redis.call('hget',@key,@subkey); elseif cnt == 0 then local tmp = redis.call('hget',@key,@subkey); redis.call('del',@timerkey); redis.call('hdel',@key,@subkey); return tmp; else redis.call('del',@timerkey); redis.call('hdel',@key,@subkey); return nil; end elseif mode == {(byte)TimeOutMode.FromCreate} then local crt = tonumber(redis.call('hget',@timerkey,'creation')); if @now - crt < tonumber(redis.call('hget',@timerkey,'counter')) then return redis.call('hget',@key,@subkey); else redis.call('del',@timerkey); redis.call('hdel',@key,@subkey); return nil; end else local crt = tonumber(redis.call('hget',@timerkey,'creation')); if @now - crt < tonumber(redis.call('hget',@timerkey,'counter')) then redis.call('hset',@timerkey,'creation',@now); return redis.call('hget',@key,@subkey); else redis.call('del',@timerkey); redis.call('hdel',@key,@subkey); return nil; end end"); _LuaExistsSub = LuaScript.Prepare($@"local mode = tonumber(redis.call('hget',@timerkey,'mode')); if mode == nil then return 0; end if mode == {(byte)TimeOutMode.Never} then return 1 elseif mode == {(byte)TimeOutMode.AccessCount} then return 1 elseif mode == {(byte)TimeOutMode.FromCreate} then local crt = tonumber(redis.call('hget',@timerkey,'creation')); if @now - crt < tonumber(redis.call('hget',@timerkey,'counter')) then return 1 else redis.call('del',@timerkey); redis.call('hdel',@key,@subkey); return 0; end else local crt = tonumber(redis.call('hget',@timerkey,'creation')); if @now - crt < tonumber(redis.call('hget',@timerkey,'counter')) then return 1; else redis.call('del',@timerkey); redis.call('hdel',@key,@subkey); return 0; end end"); }
/// <summary> /// 初期化。 /// 呼ばれるLuaの関数は<example>Start_<シーン名>(<所属するシーン>)</example> /// </summary> public override void Start(Scene prev) { LuaScript.GetFunction("Start_" + ID).Call(this); base.Start(prev); }
private static void Init() { if (s_animMachine == null) { s_animMachine = new LuaMachine(); s_animMachine.AllowByteCodeLoading = false; s_animMachine.EnforceTimeLimits = true; s_animMachine.RemoveUnsafeGlobals(); s_animMachine.SetGlobal("print", (LuaCFunction) delegate(LuaArgs args) { var output = new StringBuilder(); for (int i = 0; i < args.Length; ++i) { output.Append(args.ToString(i)); if (i < args.Length - 1) { output.Append(", "); } } App.UserLog(output.ToString()); return(LuaArgs.Empty); }); s_animMachine.SetGlobal("dofile", (LuaCFunction) delegate(LuaArgs args) { var path = args.GetString(0); if (Assets.Assets.Exists <LuaScript>(path)) { var script = LuaScript.Get(path); return(s_animMachine.DoString(script.Code, "@" + AssetPath.GetFileName(path))); } throw new LuaError("Script not found: " + path); }); s_animMachine.DoString( @"do function expect( value, sExpectedType, nArg ) local sFoundType = type( value ) if sFoundType ~= sExpectedType then error( ""Expected "" .. sExpectedType .. "" at argument "" .. nArg .. "", got "" .. sFoundType, 3 ) end end local tResults = {} function require( s ) expect( s, ""string"", 1 ) if tResults[s] == nil then local ok, result = pcall( dofile, ""scripts/"" .. s .. "".lua"" ) if not ok then error( result, 0 ) elseif result == nil then tResults[s] = true else tResults[s] = result end end return tResults[s] end abs = math.abs floor = math.floor ceil = math.ceil min = math.min max = math.max pow = math.pow sqrt = math.sqrt pi = math.pi function clamp( x, low, hi ) expect( x, ""number"", 1 ) expect( low, ""number"", 2 ) expect( hi, ""number"", 3 ) if x < low then return low elseif x > hi then return hi else return x end end local math_rad, math_deg = math.rad, math.deg local math_sin, math_cos, math_tan = math.sin, math.cos, math.tan local math_asin, math_acos, math_atan = math.asin, math.acos, math.atan function sin( x ) expect( x, ""number"", 1 ) return math_sin( math_rad( x ) ) end function cos( x ) expect( x, ""number"", 1 ) return math_cos( math_rad( x ) ) end function tan( x ) expect( x, ""number"", 1 ) return math_tan( math_rad( x ) ) end function asin( x ) expect( x, ""number"", 1 ) return math_deg( math_asin( x ) ) end function acos( x ) expect( x, ""number"", 1 ) return math_deg( math_acos( x ) ) end function atan( x ) expect( x, ""number"", 1 ) return math_deg( math_atan( x ) ) end function atan2( y, x ) expect( y, ""number"", 1 ) expect( x, ""number"", 2 ) return math_deg( math_atan( y, x ) ) end function ease( f ) expect( f, ""number"", 1 ) f = clamp( f, 0.0, 1.0 ) return (3 - 2*f) * f * f end function lerp( a, b, f ) expect( a, ""number"", 1 ) expect( b, ""number"", 2 ) expect( f, ""number"", 3 ) return a + (b-a) * f end function lerp3( x0, y0, z0, x1, y1, z1, f ) expect( x0, ""number"", 1 ) expect( y0, ""number"", 2 ) expect( z0, ""number"", 3 ) expect( x1, ""number"", 4 ) expect( y1, ""number"", 5 ) expect( z1, ""number"", 6 ) expect( f, ""number"", 7 ) return lerp(x0, x1, f), lerp(y0, y1, f), lerp(z0, z1, f) end function step( a, x ) expect( a, ""number"", 1 ) expect( x, ""number"", 2 ) return (x >= a) and 1 or 0 end function smoothstep( a, b, x ) expect( a, ""number"", 1 ) expect( b, ""number"", 2 ) expect( x, ""number"", 3 ) local f = clamp( (x - a) / (b - a), 0, 1 ) return ease(f) end function rot2D( x, y, a, xo, yo ) expect( x, ""number"", 1 ) expect( y, ""number"", 2 ) expect( a, ""number"", 3 ) if xo then expect( xo, ""number"", 4 ) end if yo then expect( yo, ""number"", 5 ) end xo = xo or 0 yo = yo or 0 local ar = -math_rad(a) local ca, sa = math_cos(ar), math_sin(ar) return xo + (x - xo) * ca - (y - yo) * sa, yo + (x - xo) * sa + (y - yo) * ca end function setpos( part, x, y, z ) expect( part, ""table"", 1 ) expect( x, ""number"", 2 ) expect( y, ""number"", 3 ) expect( z, ""number"", 4 ) part.x = x part.y = y part.z = z end function lookat( part, x, y, z ) expect( part, ""table"", 1 ) expect( x, ""number"", 2 ) expect( y, ""number"", 3 ) expect( z, ""number"", 4 ) local dx = x - part.x local dy = y - part.y local dz = z - part.z local dxz = sqrt( dx*dx + dz*dz ) part.ry = -atan2( dx, -dz ) part.rx = atan2( dy, dxz ) part.rz = 0 end local tAnimations = {} function install_animation( sAnimName, sAnimCode, sChunkName ) local tAnimEnv = {} setmetatable( tAnimEnv, { __index = _ENV } ) local fnAnim, sError = load( sAnimCode, sChunkName, ""t"", tAnimEnv ) if fnAnim then local ok, sError = pcall( fnAnim ) if ok then tAnimations[ sAnimName ] = tAnimEnv.animate else tAnimations[ sAnimName ] = nil error( sError, 0 ) end else tAnimations[ sAnimName ] = nil error( sError, 0 ) end end local tPart = {} function call_animation( sAnimName, sPartName, nTime ) tPart.name = sPartName tPart.hide = false tPart.x, tPart.y, tPart.z = 0,0,0 tPart.rx, tPart.ry, tPart.rz = 0,0,0 tPart.sx, tPart.sy, tPart.sz = 1,1,1 tPart.u, tPart.v = 0,0 tPart.su, tPart.sv = 1,1 tPart.r, tPart.g, tPart.b, tPart.a = 1,1,1,1 tPart.fov = nil local fnAnimate = tAnimations[sAnimName] if fnAnimate then fnAnimate( tPart, nTime ) end return tPart.hide, tPart.x, tPart.y, tPart.z, tPart.rx, tPart.ry, tPart.rz, tPart.sx, tPart.sy, tPart.sz, tPart.u, tPart.v, tPart.su, tPart.sv, tPart.r, tPart.g, tPart.b, tPart.a, tPart.fov end end", "=LuaAnimation.Init" ); s_install_animation = s_animMachine.GetGlobal("install_animation").GetFunction(); s_call_animation = s_animMachine.GetGlobal("call_animation").GetFunction(); } }
void Execute(string cmd) { LuaScript.Execute(cmd); inputField.text = ""; }
// Methods public static void Load(string dataDir, string stageID, GameEntry game) { Data.Clear(); // Throw exceptions if necessary if (!Directory.Exists(dataDir)) { throw new DirectoryNotFoundException( $"Cannot load stage from \"{dataDir}\". Data Directory not found!"); } if (string.IsNullOrEmpty(stageID)) { throw new ArgumentNullException("stageID", "Cannot load stage. Invalid Stage ID!"); } GameType = game; ID = stageID; DataDir = dataDir; var resDir = new AssetDirectory(game.ResourcesDir); Data.ModelDirectories.Add(resDir); Data.ResourceDirectories.Add(resDir); // Make cache directory CacheDir = Path.Combine(Program.StartupPath, Program.CachePath, stageID); string editorCachePath = Path.Combine( CacheDir, EditorCache.FileName); Directory.CreateDirectory(CacheDir); // Load Editor Cache bool cacheExists = File.Exists(editorCachePath); EditorCache = new EditorCache() { GameType = game.Name, }; if (cacheExists) { var editorCache = new EditorCache(); editorCache.Load(editorCachePath); if (editorCache.GameType == game.Name) { EditorCache = editorCache; } } // Lua Script string pth = Path.Combine(Program.StartupPath, Program.ScriptsPath, LuaScript.GamesDir, $"{game.ShortName}{LuaScript.Extension}"); if (script == null || scriptPath != pth) { script = new LuaScript(); scriptPath = pth; try { script.DoScript(scriptPath); var canAddSetLayer = script.GetValue("CanAddSetLayer"); SceneView.CanAddLayer = (canAddSetLayer != null && canAddSetLayer.GetType() == typeof(bool)) ? (bool)canAddSetLayer : false; } catch (Exception ex) { LuaTerminal.LogError($"ERROR: {ex.Message}"); } } // Unpack/Load var unpackStopWatch = System.Diagnostics.Stopwatch.StartNew(); try { script.Call("Load", dataDir, CacheDir, stageID); } catch (Exception ex) { LuaTerminal.LogError($"ERROR: {ex.Message}, {ex.StackTrace}"); } unpackStopWatch.Stop(); Console.WriteLine("Done unpacking! Time: {0}(ms).", unpackStopWatch.ElapsedMilliseconds); // Generate new Editor Cache if (cacheExists) { File.Delete(editorCachePath); } EditorCache.Save(editorCachePath, true); // TODO: Remove this line //CurrentSetLayer = Sets[0]; }
internal Producer(RingBuffer queue) { Queue = queue; _script = LuaScript.Prepare(ScriptPreprocessor(File.ReadAllText("Scripts/publish.lua"))).Load(Queue.Server); }
internal LoadedLuaScript(LuaScript original, byte[] hash) { Original = original; Hash = hash; }
private Task <LoadedLuaScript> LoadScript(string script) => LuaScript.Prepare(script).LoadAsync(_connectionMultiplexer.GetServer(_connectionMultiplexer.GetEndPoints()[0]));
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) { if (tabControl1.SelectedIndex == 2) { Task.Run(() => { string[] files1 = Directory.GetFiles("Scripts\\", "*.lua"); string[] files2 = Directory.GetFiles("Scripts\\libs", "*.lua"); int num = Enumerable.Aggregate<string, int>(Enumerable.Select<string, string>(files1, new Func<string, string>(Path.GetFileNameWithoutExtension)), 0, (current, scriptName) => current ^ scriptName.GetHashCode()) ^ Enumerable.Aggregate<string, int>(Enumerable.Select<string, string>(files2, new Func<string, string>(Path.GetFileNameWithoutExtension)), 0, (current, scriptName) => current ^ scriptName.GetHashCode()); if (num == _scriptListChecksum) return; _scriptListChecksum = num; Dictionary<string, bool> dictionary = new Dictionary<string, bool>(); foreach (LuaScript luaScript in listBinding) dictionary[luaScript.ScriptName] = luaScript.LoadScript; Invoke(new Action(ClearBindingSource)); foreach (string name in Enumerable.Select<string, string>(files1, new Func<string, string>(Path.GetFileNameWithoutExtension))) { LuaScript luaScript = new LuaScript(name); if (dictionary.ContainsKey(luaScript.ScriptName)) luaScript.LoadScript = dictionary[luaScript.ScriptName]; Invoke(new Action<LuaScript>(AddListBindingEntry), luaScript); } }); } else { if (tabControl1.SelectedIndex != 3) return; _scriptConfigClass.Clear(); foreach (string category in Enumerable.Select<string, string>(Directory.GetFiles("Scripts\\Config\\", "*.txt"), new Func<string, string>(Path.GetFileNameWithoutExtension))) { string[] strArray = File.ReadAllLines(Path.Combine("Scripts\\Config\\", category + ".txt")); Regex regex = new Regex("([\\w|-]*)[\\W]*=[\\W]*([\\w|-]*)", RegexOptions.Compiled); foreach (string input in strArray) { if (regex.IsMatch(input)) { Match match = regex.Match(input); object obj = string.Compare(match.Groups[2].Value, "true", StringComparison.OrdinalIgnoreCase) != 0 ? (string.Compare(match.Groups[2].Value, "false", StringComparison.OrdinalIgnoreCase) != 0 ? match.Groups[2].Value : (object)false) : true; _scriptConfigClass.Add(new CustomProperty(category, match.Groups[1].Value, obj, false, true)); } } } scriptConfigGrid.Refresh(); } }
private void AddListBindingEntry(LuaScript entry) { listBinding.Add(entry); }
/// <summary> /// 終末処理。 /// 呼ばれるLuaの関数は<example>Exit_<SceneName>()</example> /// </summary> public override void Exit() { LuaScript.GetFunction("Exit_" + ID).Call(); LuaScript.Dispose(); base.Exit(); }
public void onInput(InputHandler input) { bool interactingWithUi = ui.onInput(input); if (interactingWithUi) { return; } cursor.onInput(input); if (input.isKeyPressed(Keys.F2)) // Save { UiElement filename = new UiTextInput("Save Filename: ").addCallback(element => { UiTextInput input = (UiTextInput)element; if (input.text != "") { SerializableMap.Save(Content, map, input.text); } }); ui.pushElement(filename, Vector2.One); } else if (input.isKeyPressed(Keys.F3)) // Load { UiElement filename = new UiTextInput("Load Filename: ").addCallback(element => { UiTextInput input = (UiTextInput)element; if (input.text != "") { TileMap newMap = SerializableMap.Load(Content, input.text); if (newMap != null) { this.world.setMap(newMap); cursor.setLocation(Vector2.Zero); } } }); ui.pushElement(filename, Vector2.One); } else if (input.isKeyPressed(Keys.E)) // Edit tile properties { Tile selected = map.getTile(cursor.getTileLocation()); NPC npc = map.getNPC(cursor.getTileLocation()); LuaScript script = map.getScript(cursor.getTileLocation()); if (selected != null) { ui.pushElement(new UiTileEditor(Content, selected, npc, script).addCallback(element => { UiTileEditor editor = (UiTileEditor)element; map.setTile(cursor.getTileLocation(), editor.tile); map.setNPC(cursor.getTileLocation(), editor.npc); map.setScript(cursor.getTileLocation(), editor.script); lastEditedTile = editor.tile; lastEditedScript = editor.script; }), new Vector2(160, 0)); } } else if (input.isKeyHeld(Keys.P)) // Tile painter { if (lastEditedTile != null) { map.setTile(cursor.getTileLocation(), new Tile(lastEditedTile)); if (lastEditedScript != null) { map.setScript(cursor.getTileLocation(), new LuaScript(lastEditedScript.filename)); } } } else if (input.isKeyPressed(Keys.M)) // Edit map meta info { ui.pushElement(new UiMapMetaEditor(Content, map), new Vector2(160, 0)); } }
/// <summary> /// 制御を1F進める。 /// 呼ばれるLuaの関数は<example>Tick_<SceneName>()</example> /// </summary> public override void Tick() { LuaScript.GetFunction("Tick_" + ID).Call(); base.Tick(); }
public void Simple() { using (var conn = Create()) { var server = conn.GetServer(TestConfig.Current.PrimaryServerAndPort); var script = LuaScript.Prepare("return redis.call('get', @key)"); var loaded = script.Load(server); var key = Me(); var session = new ProfilingSession(); conn.RegisterProfiler(() => session); var dbId = TestConfig.GetDedicatedDB(); var db = conn.GetDatabase(dbId); db.StringSet(key, "world"); var result = db.ScriptEvaluate(script, new { key = (RedisKey)key }); Assert.Equal("world", result.AsString()); var loadedResult = db.ScriptEvaluate(loaded, new { key = (RedisKey)key }); Assert.Equal("world", loadedResult.AsString()); var val = db.StringGet(key); Assert.Equal("world", val); var s = (string)db.Execute("ECHO", "fii"); Assert.Equal("fii", s); var cmds = session.FinishProfiling(); var i = 0; foreach (var cmd in cmds) { Log("Command {0} (DB: {1}): {2}", i++, cmd.Db, cmd?.ToString()?.Replace("\n", ", ")); } var all = string.Join(",", cmds.Select(x => x.Command)); Assert.Equal("SET,EVAL,EVALSHA,GET,ECHO", all); Log("Checking for SET"); var set = cmds.SingleOrDefault(cmd => cmd.Command == "SET"); Assert.NotNull(set); Log("Checking for GET"); var get = cmds.SingleOrDefault(cmd => cmd.Command == "GET"); Assert.NotNull(get); Log("Checking for EVAL"); var eval = cmds.SingleOrDefault(cmd => cmd.Command == "EVAL"); Assert.NotNull(eval); Log("Checking for EVALSHA"); var evalSha = cmds.SingleOrDefault(cmd => cmd.Command == "EVALSHA"); Assert.NotNull(evalSha); Log("Checking for ECHO"); var echo = cmds.SingleOrDefault(cmd => cmd.Command == "ECHO"); Assert.NotNull(echo); Assert.Equal(5, cmds.Count()); Assert.True(set.CommandCreated <= eval.CommandCreated); Assert.True(eval.CommandCreated <= evalSha.CommandCreated); Assert.True(evalSha.CommandCreated <= get.CommandCreated); AssertProfiledCommandValues(set, conn, dbId); AssertProfiledCommandValues(get, conn, dbId); AssertProfiledCommandValues(eval, conn, dbId); AssertProfiledCommandValues(evalSha, conn, dbId); AssertProfiledCommandValues(echo, conn, dbId); } }
/// <summary> /// 描画処理。 /// 呼ばれるLuaの関数は<example>Tick_<SceneName>()</example> /// </summary> public override void Draw() { LuaScript.GetFunction("Draw_" + ID).Call(); base.Draw(); }
public async Task <RedisResult> ScriptEvaluateAsync(LuaScript script, object parameters = null, CommandFlags flags = CommandFlags.None) { return(await _db.ScriptEvaluateAsync(script, parameters, flags)); }
//使用Keys *模糊匹配Key public static List <string> GetKeys(string key) { var result = (string[])Cache.ScriptEvaluate(LuaScript.Prepare("return redis.call('KEYS',@keypattern)"), new { keypattern = key }); return(result.ToList()); }
public static Task <LoadedLuaScript> ScriptLoadAsync(LuaScript script, CommandFlags flags = CommandFlags.None) { return(Server.ScriptLoadAsync(script, flags)); }
public ScriptController(LevelState state) { m_state = state; m_machine = new LuaMachine(); m_machine.AllowByteCodeLoading = false; m_machine.EnforceTimeLimits = true; m_machine.RemoveUnsafeGlobals(); m_activeCoroutines = new List <LuaCoroutine>(); // Install APIs and Globals m_machine.SetGlobal("io", new IOAPI(m_state).ToTable()); m_machine.SetGlobal("level", new LevelAPI(m_state).ToTable()); if (m_state is InGameState) { m_machine.SetGlobal("game", new GameAPI((InGameState)m_state).ToTable()); m_machine.SetGlobal("campaign", new CampaignAPI(m_state).ToTable()); m_machine.DoString(@"do local game_showDialogue = game.showDialogue function game.showDialogue( character, text, modal, returnImmediately ) -- Create dialog game_showDialogue( character, text, modal ) if modal ~= false and returnImmediately ~= true then while not game.isDialogueReadyToContinue() do yield() end end end local game_hideDialogue = game.hideDialogue function game.hideDialogue() -- Create dialog game_hideDialogue() while game.isDialogueVisible() do yield() end end end", "=ScriptController.ctor"); } else if (m_state is CutsceneState) { m_machine.SetGlobal("cutscene", new CutsceneAPI((CutsceneState)m_state).ToTable()); m_machine.SetGlobal("campaign", new CampaignAPI(m_state).ToTable()); } m_machine.SetGlobal("dofile", (LuaCFunction)DoFile); m_machine.DoString(@"do function expect( value, sExpectedType, nArg ) local sFoundType = type( value ) if sFoundType ~= sExpectedType then error( ""Expected "" .. sExpectedType .. "" at argument "" .. nArg .. "", got "" .. sFoundType, 3 ) end end local tResults = {} function require( s ) expect( s, ""string"", 1 ) if tResults[s] == nil then local ok, result = pcall( dofile, ""scripts/"" .. s .. "".lua"" ) if not ok then error( result, 0 ) elseif result == nil then tResults[s] = true else tResults[s] = result end end return tResults[s] end print = io.print yield = coroutine.yield function sleep( t ) expect( t, ""number"", 1 ) local l = io.getTime() + t repeat yield() until io.getTime() >= l end end", "=ScriptController.ctor"); // Start the main script m_scriptPath = m_state.Level.Info.ScriptPath; if (m_scriptPath != null) { if (Assets.Exists <LuaScript>(m_scriptPath)) { try { var script = LuaScript.Get(m_scriptPath); m_machine.DoString(script.Code, "@" + AssetPath.GetFileName(m_scriptPath)); } catch (LuaError e) { App.Log("Lua Error: {0}", e.Message); } } else { App.Log("Error: Script {0} not found", m_scriptPath); } } }
/// <summary> /// lua脚本 /// obj :new {key=key} /// </summary> /// <param name="script"></param> /// <param name="obj"></param> public object GetByLuaScript(string script, object obj) { var prepared = LuaScript.Prepare(script); return(_database.ScriptEvaluate(prepared, obj)); }
public static RedisResult ExecScript(string script, object param, int db = -1) { var prepared = LuaScript.Prepare(script); return(Instance?.GetDatabase(db).ScriptEvaluate(prepared, param)); }