repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
BlockMen/minetest_next
mods/default/mapgenv57.lua
1
14501
-- -- Register biomes -- minetest.clear_registered_biomes() -- Permanent ice minetest.register_biome({ name = "glacier", node_dust = "default:snowblock", node_top = "default:snowblock", depth_top = 1, node_filler = "default:snowblock", depth_filler = 3, node_stone = "default:ice", node_water_top = "default:ice", depth_water_top = 10, --node_water = "", node_river_water = "default:ice", y_min = -8, y_max = 31000, heat_point = -5, humidity_point = 50, }) minetest.register_biome({ name = "glacier_ocean", node_dust = "default:snowblock", node_top = "default:gravel", depth_top = 1, node_filler = "default:gravel", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -112, y_max = -9, heat_point = -5, humidity_point = 50, }) -- Cold minetest.register_biome({ name = "tundra", node_dust = "default:snow", node_top = "default:dirt_with_snow", depth_top = 1, node_filler = "default:dirt", depth_filler = 0, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 2, y_max = 31000, heat_point = 20, humidity_point = 25, }) minetest.register_biome({ name = "tundra_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -112, y_max = 1, heat_point = 20, humidity_point = 25, }) minetest.register_biome({ name = "taiga", node_dust = "default:snow", node_top = "default:snowblock", depth_top = 1, node_filler = "default:dirt", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 2, y_max = 31000, heat_point = 20, humidity_point = 75, }) minetest.register_biome({ name = "taiga_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -112, y_max = 1, heat_point = 20, humidity_point = 75, }) -- Temperate minetest.register_biome({ name = "stone_grassland", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 0, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 5, y_max = 31000, heat_point = 45, humidity_point = 25, }) minetest.register_biome({ name = "stone_grassland_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -112, y_max = 4, heat_point = 45, humidity_point = 25, }) minetest.register_biome({ name = "coniferous_forest", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 9, y_max = 31000, heat_point = 45, humidity_point = 75, }) minetest.register_biome({ name = "coniferous_forest_dunes", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 5, y_max = 8, heat_point = 45, humidity_point = 75, }) minetest.register_biome({ name = "coniferous_forest_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -112, y_max = 4, heat_point = 45, humidity_point = 75, }) minetest.register_biome({ name = "sandstone_grassland", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 0, node_stone = "default:sandstone", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 5, y_max = 31000, heat_point = 70, humidity_point = 25, }) minetest.register_biome({ name = "sandstone_grassland_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 2, node_stone = "default:sandstone", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -112, y_max = 4, heat_point = 70, humidity_point = 25, }) minetest.register_biome({ name = "deciduous_forest", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 1, y_max = 31000, heat_point = 70, humidity_point = 75, }) minetest.register_biome({ name = "deciduous_forest_swamp", --node_dust = "", node_top = "default:dirt", depth_top = 1, node_filler = "default:dirt", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -3, y_max = 0, heat_point = 70, humidity_point = 75, }) minetest.register_biome({ name = "deciduous_forest_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -112, y_max = -4, heat_point = 70, humidity_point = 75, }) -- Hot minetest.register_biome({ name = "desert", --node_dust = "", node_top = "default:desert_sand", depth_top = 1, node_filler = "default:desert_sand", depth_filler = 1, node_stone = "default:desert_stone", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 5, y_max = 31000, heat_point = 95, humidity_point = 10, }) minetest.register_biome({ name = "desert_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 2, node_stone = "default:desert_stone", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -112, y_max = 4, heat_point = 95, humidity_point = 10, }) minetest.register_biome({ name = "savanna", --node_dust = "", node_top = "default:dirt_with_dry_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 1, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 1, y_max = 31000, heat_point = 95, humidity_point = 50, }) minetest.register_biome({ name = "savanna_swamp", --node_dust = "", node_top = "default:dirt", depth_top = 1, node_filler = "default:dirt", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -3, y_max = 0, heat_point = 95, humidity_point = 50, }) minetest.register_biome({ name = "savanna_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -112, y_max = -4, heat_point = 95, humidity_point = 50, }) minetest.register_biome({ name = "rainforest", --node_dust = "", node_top = "default:dirt_with_grass", depth_top = 1, node_filler = "default:dirt", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = 1, y_max = 31000, heat_point = 95, humidity_point = 90, }) minetest.register_biome({ name = "rainforest_swamp", --node_dust = "", node_top = "default:dirt", depth_top = 1, node_filler = "default:dirt", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -3, y_max = 0, heat_point = 95, humidity_point = 90, }) minetest.register_biome({ name = "rainforest_ocean", --node_dust = "", node_top = "default:sand", depth_top = 1, node_filler = "default:sand", depth_filler = 2, --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -112, y_max = -4, heat_point = 95, humidity_point = 90, }) -- Underground minetest.register_biome({ name = "underground", --node_dust = "", --node_top = "", --depth_top = , --node_filler = "", --depth_filler = , --node_stone = "", --node_water_top = "", --depth_water_top = , --node_water = "", --node_river_water = "", y_min = -31000, y_max = -113, heat_point = 50, humidity_point = 50, }) -- -- Register decorations -- local function register_grass_decoration(offset, scale, length, dry) local name = "default:grass_" local biome = {"stone_grassland", "sandstone_grassland", "deciduous_forest", "coniferous_forest", "coniferous_forest_dunes"} if dry then name = "default:dry_grass_" biome = {"savanna"} end minetest.register_decoration({ deco_type = "simple", place_on = {"default:dirt_with_grass", "default:sand"}, sidelen = 16, noise_params = { offset = offset, scale = scale, spread = {x = 200, y = 200, z = 200}, seed = 329, octaves = 3, persist = 0.6 }, biomes = biome, y_min = 1, y_max = 31000, decoration = name .. length, }) end minetest.clear_registered_decorations() -- Apple tree minetest.register_decoration({ deco_type = "schematic", place_on = {"default:dirt_with_grass"}, sidelen = 16, noise_params = { offset = 0.04, scale = 0.02, spread = {x = 250, y = 250, z = 250}, seed = 2, octaves = 3, persist = 0.66 }, biomes = {"deciduous_forest"}, y_min = 1, y_max = 31000, schematic = minetest.get_modpath("default").."/schematics/apple_tree.mts", flags = "place_center_x, place_center_z", }) -- Jungle tree minetest.register_decoration({ deco_type = "schematic", place_on = {"default:dirt_with_grass", "default:dirt"}, sidelen = 80, fill_ratio = 0.09, biomes = {"rainforest", "rainforest_swamp"}, y_min = 0, y_max = 31000, schematic = minetest.get_modpath("default").."/schematics/jungle_tree.mts", flags = "place_center_x, place_center_z", rotation = "random", }) -- Taiga and temperate forest pine tree minetest.register_decoration({ deco_type = "schematic", place_on = {"default:snowblock", "default:dirt_with_grass"}, sidelen = 16, noise_params = { offset = 0.04, scale = 0.02, spread = {x = 250, y = 250, z = 250}, seed = 2, octaves = 3, persist = 0.66 }, biomes = {"taiga", "coniferous_forest"}, y_min = 2, y_max = 31000, schematic = minetest.get_modpath("default").."/schematics/pine_tree.mts", flags = "place_center_x, place_center_z", }) -- Acacia tree minetest.register_decoration({ deco_type = "schematic", place_on = {"default:dirt_with_dry_grass"}, sidelen = 80, noise_params = { offset = 0, scale = 0.003, spread = {x = 250, y = 250, z = 250}, seed = 2, octaves = 3, persist = 0.66 }, biomes = {"savanna"}, y_min = 1, y_max = 31000, schematic = minetest.get_modpath("default").."/schematics/acacia_tree.mts", flags = "place_center_x, place_center_z", rotation = "random", }) -- Birch tree minetest.register_decoration({ deco_type = "schematic", place_on = {"default:dirt_with_grass"}, sidelen = 16, noise_params = { offset = 0.01, scale = -0.02, spread = {x = 250, y = 250, z = 250}, seed = 2, octaves = 3, persist = 0.66 }, biomes = {"deciduous_forest"}, y_min = 1, y_max = 31000, schematic = minetest.get_modpath("default").."/schematics/birch_tree.mts", flags = "place_center_x, place_center_z", rotation = "random", }) -- Large cactus minetest.register_decoration({ deco_type = "schematic", place_on = {"default:desert_sand"}, sidelen = 80, noise_params = { offset = -0.0005, scale = 0.0015, spread = {x = 200, y = 200, z = 200}, seed = 230, octaves = 3, persist = 0.6 }, biomes = {"desert"}, y_min = 5, y_max = 31000, schematic = minetest.get_modpath("default").."/schematics/large_cactus.mts", flags = "place_center_x", rotation = "random", }) -- Cactus minetest.register_decoration({ deco_type = "simple", place_on = {"default:desert_sand"}, sidelen = 80, noise_params = { offset = -0.0005, scale = 0.0015, spread = {x = 200, y = 200, z = 200}, seed = 230, octaves = 3, persist = 0.6 }, biomes = {"desert"}, y_min = 5, y_max = 31000, decoration = "default:cactus", height = 2, height_max = 5, }) -- Papyrus minetest.register_decoration({ deco_type = "schematic", place_on = {"default:dirt"}, sidelen = 16, noise_params = { offset = -0.3, scale = 0.7, spread = {x = 200, y = 200, z = 200}, seed = 354, octaves = 3, persist = 0.7 }, biomes = {"savanna_swamp"}, y_min = 0, y_max = 0, schematic = minetest.get_modpath("default").."/schematics/papyrus.mts", }) -- Grasses register_grass_decoration(-0.03, 0.09, 5) register_grass_decoration(-0.015, 0.075, 4) register_grass_decoration(0, 0.06, 3) register_grass_decoration(0.015, 0.045, 2) register_grass_decoration(0.03, 0.03, 1) -- Dry grasses register_grass_decoration(0.01, 0.05, 5, true) register_grass_decoration(0.03, 0.03, 4, true) register_grass_decoration(0.05, 0.01, 3, true) register_grass_decoration(0.07, -0.01, 2, true) register_grass_decoration(0.09, -0.03, 1, true) -- Junglegrass minetest.register_decoration({ deco_type = "simple", place_on = {"default:dirt_with_grass"}, sidelen = 80, fill_ratio = 0.1, biomes = {"rainforest"}, y_min = 1, y_max = 31000, decoration = "default:junglegrass", }) -- Dry shrub minetest.register_decoration({ deco_type = "simple", place_on = {"default:desert_sand", "default:dirt_with_snow"}, sidelen = 16, noise_params = { offset = 0, scale = 0.02, spread = {x = 200, y = 200, z = 200}, seed = 329, octaves = 3, persist = 0.6 }, biomes = {"desert", "tundra"}, y_min = 2, y_max = 31000, decoration = "default:dry_shrub", }) minetest.register_on_generated(default.generate_nyancats)
gpl-3.0
Scavenge/darkstar
scripts/globals/items/boiled_crayfish.lua
12
1235
----------------------------------------- -- ID: 4535 -- Item: Boiled Crayfish -- Food Effect: 30Min, All Races ----------------------------------------- -- defense % 30 -- defense % 25 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4535); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_DEFP, 30); target:addMod(MOD_FOOD_DEF_CAP, 25); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_DEFP, 30); target:delMod(MOD_FOOD_DEF_CAP, 25); end;
gpl-3.0
Zero-K-Experiments/Zero-K-Experiments
effects/hovers.lua
17
3180
-- hovers_on_ground -- heavyhovers_on_ground -- transport_hovers_on_ground return { ["hovers_on_ground"] = { clouds0 = { air = false, class = [[CSimpleParticleSystem]], count = 1, ground = true, underwater = 0, water = false, properties = { airdrag = 0.99, colormap = [[0 0 0 0.001 0.04 0.04 0.04 0.18 0 0 0 0.001]], directional = false, emitrot = 90, emitrotspread = 0, emitvector = [[0, 1, 0]], gravity = [[0, -0.01, 0]], numparticles = 3, particlelife = 20, particlelifespread = 20, particlesize = 8, particlesizespread = 4, particlespeed = 0.45, particlespeedspread = 0.9, pos = [[0, 1.75, 0]], sizegrowth = -0.005, sizemod = 1.0, texture = [[kfoam]], useAirLos = false, }, }, }, ["heavyhovers_on_ground"] = { clouds0 = { air = false, class = [[CSimpleParticleSystem]], count = 1, ground = true, underwater = 0, water = false, properties = { airdrag = 0.99, colormap = [[0 0 0 0.001 0.04 0.04 0.04 0.18 0 0 0 0.001]], directional = false, emitrot = 90, emitrotspread = 0, emitvector = [[0, 1, 0]], gravity = [[0, -0.01, 0]], numparticles = 5, particlelife = 20, particlelifespread = 20, particlesize = 8, particlesizespread = 4, particlespeed = 0.7, particlespeedspread = 1.1, pos = [[0, 1.75, 0]], sizegrowth = -0.005, sizemod = 1.0, texture = [[kfoam]], useAirLos = false, }, }, }, ["transport_hovers_on_ground"] = { clouds0 = { air = false, class = [[CSimpleParticleSystem]], count = 1, ground = true, useAirLos = false, underwater = 0, water = false, properties = { airdrag = 0.95, colormap = [[0 0 0 0.001 0.04 0.04 0.04 0.18 0 0 0 0.001]], directional = false, emitrot = 90, emitrotspread = 0, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 10, particlelife = 40, particlelifespread = 40, particlesize = 8, particlesizespread = 4, particlespeed = 1, particlespeedspread = 2, pos = [[0, 3, 0]], sizegrowth = 0.05, sizemod = 1.0, texture = [[kfoam]], useAirLos = false, }, }, }, }
gpl-2.0
Arczuch/ttt-scoreboard-colors
tttscoreboadcolors/lua/autorun/tttscoreboadcolors.lua
1
2470
/* AUTHOR: Arczi (STEAM_0:1:55136945) */ if SERVER then AddCSLuaFile("tttscoreboadcolors.lua") end if CLIENT then CreateConVar("ttt_scoreboardcolors_user_r", "255", FCVAR_REPLICATED + FCVAR_NOTIFY + FCVAR_ARCHIVE ) CreateConVar("ttt_scoreboardcolors_user_g", "255", FCVAR_REPLICATED + FCVAR_NOTIFY + FCVAR_ARCHIVE ) CreateConVar("ttt_scoreboardcolors_user_b", "255", FCVAR_REPLICATED + FCVAR_NOTIFY + FCVAR_ARCHIVE ) -- CreateConVar("ttt_scoreboardcolors_operator_r", "255", FCVAR_REPLICATED + FCVAR_NOTIFY + FCVAR_ARCHIVE ) CreateConVar("ttt_scoreboardcolors_operator_g", "255", FCVAR_REPLICATED + FCVAR_NOTIFY + FCVAR_ARCHIVE ) CreateConVar("ttt_scoreboardcolors_operator_b", "255", FCVAR_REPLICATED + FCVAR_NOTIFY + FCVAR_ARCHIVE ) -- CreateConVar("ttt_scoreboardcolors_admin_r", "255", FCVAR_REPLICATED + FCVAR_NOTIFY + FCVAR_ARCHIVE ) CreateConVar("ttt_scoreboardcolors_admin_g", "255", FCVAR_REPLICATED + FCVAR_NOTIFY + FCVAR_ARCHIVE ) CreateConVar("ttt_scoreboardcolors_admin_b", "255", FCVAR_REPLICATED + FCVAR_NOTIFY + FCVAR_ARCHIVE ) -- CreateConVar("ttt_scoreboardcolors_superadmin_r", "255", FCVAR_REPLICATED + FCVAR_NOTIFY + FCVAR_ARCHIVE ) CreateConVar("ttt_scoreboardcolors_superadmin_g", "255", FCVAR_REPLICATED + FCVAR_NOTIFY + FCVAR_ARCHIVE ) CreateConVar("ttt_scoreboardcolors_superadmin_b", "255", FCVAR_REPLICATED + FCVAR_NOTIFY + FCVAR_ARCHIVE ) local function colorName( ply ) if ply:IsUserGroup("user") then return Color(GetConVar("ttt_scoreboardcolors_user_r"):GetInt(), GetConVar("ttt_scoreboardcolors_user_g"):GetInt(), GetConVar("ttt_scoreboardcolors_user_b"):GetInt()) elseif ply:IsUserGroup("operator") then return Color(GetConVar("ttt_scoreboardcolors_operator_r"):GetInt(), GetConVar("ttt_scoreboardcolors_operator_g"):GetInt(), GetConVar("ttt_scoreboardcolors_operator_b"):GetInt()) elseif ply:IsUserGroup("admin") then return Color(GetConVar("ttt_scoreboardcolors_admin_r"):GetInt(), GetConVar("ttt_scoreboardcolors_admin_g"):GetInt(), GetConVar("ttt_scoreboardcolors_admin_b"):GetInt()) elseif ply:IsUserGroup("superadmin") then return Color(GetConVar("ttt_scoreboardcolors_superadmin_r"):GetInt(), GetConVar("ttt_scoreboardcolors_superadmin_g"):GetInt(), GetConVar("ttt_scoreboardcolors_superadmin_b"):GetInt()) end end hook.Add("TTTScoreboardColorForPlayer", "Color Scoreboard Names", colorName) end
mit
endlessm/chromium-browser
third_party/skia/tools/lua/classify_rrect_clips.lua
160
3346
function sk_scrape_startcanvas(c, fileName) end function sk_scrape_endcanvas(c, fileName) end function classify_rrect(rrect) if (rrect:type() == "simple") then local x, y = rrect:radii(0) if (x == y) then return "simple_circle" else return "simple_oval" end elseif (rrect:type() == "complex") then local numNotSquare = 0 local rx, ry local same = true; local first_not_square_corner local last_not_square_corner for i = 1, 4 do local x, y = rrect:radii(i-1) if (x ~= 0 and y ~= 0) then if (numNotSquare == 0) then rx = x ry = y first_not_square_corner = i else last_not_square_corner = i if (rx ~= x or ry ~=y) then same = false end end numNotSquare = numNotSquare + 1 end end local numSquare = 4 - numNotSquare if (numSquare > 0 and same) then local corners = "corners" if (numSquare == 2) then if ((last_not_square_corner - 1 == first_not_square_corner) or (1 == first_not_square_corner and 4 == last_not_square_corner )) then corners = "adjacent_" .. corners else corners = "opposite_" .. corners end elseif (1 == numSquare) then corners = "corner" end if (rx == ry) then return "circles_with_" .. numSquare .. "_square_" .. corners else return "ovals_with_" .. numSquare .. "_square_" .. corners end end return "complex_unclassified" elseif (rrect:type() == "rect") then return "rect" elseif (rrect:type() == "oval") then local x, y = rrect:radii(0) if (x == y) then return "circle" else return "oval" end elseif (rrect:type() == "empty") then return "empty" else return "unknown" end end function print_classes(class_table) function sort_classes(a, b) return a.count > b.count end array = {} for k, v in pairs(class_table) do if (type(v) == "number") then array[#array + 1] = {class = k, count = v}; end end table.sort(array, sort_classes) local i for i = 1, #array do io.write(array[i].class, ": ", array[i].count, " (", array[i].count/class_table["total"] * 100, "%)\n"); end end function sk_scrape_accumulate(t) if (t.verb == "clipRRect") then local rrect = t.rrect table["total"] = (table["total"] or 0) + 1 local class = classify_rrect(rrect) table[class] = (table[class] or 0) + 1 end end function sk_scrape_summarize() print_classes(table) --[[ To use the web scraper comment out the above call to print_classes, run the code below, and in the aggregator pass agg_table to print_classes. for k, v in pairs(table) do if (type(v) == "number") then local t = "agg_table[\"" .. k .. "\"]" io.write(t, " = (", t, " or 0) + ", table[k], "\n" ); end end --]] end
bsd-3-clause
k0nserv/dotfiles
files/nvim/lua/utils.lua
1
1682
-- Merge two tables, overwriting values in `t1` for keys that exists in `t2. -- Borrowed from https://stackoverflow.com/questions/1283388/how-to-merge-two-tables-overwriting-the-elements-which-are-in-both function merge_tables_inplace(t1, t2) for k,v in pairs(t2) do if type(v) == "table" then if type(t1[k] or false) == "table" then t1[k] = merge_tables_inplace(t1[k] or {}, v or {}) else t1[k] = v end else t1[k] = v end end return t1 end function merge_tables(t1, t2) local merged = copy_table(t1) merge_tables_inplace(merged, t2) return merged end function copy_table(obj) if type(obj) ~= 'table' then return obj end local res = {} for k, v in pairs(obj) do res[copy_table(k)] = copy_table(v) end return res end function os.capture(cmd, raw) local f = assert(io.popen(cmd, 'r')) local s = assert(f:read('*a')) f:close() if raw then return s end s = string.gsub(s, '^%s+', '') s = string.gsub(s, '%s+$', '') s = string.gsub(s, '[\n\r]+', ' ') return s end function set_dark_colors() vim.o.background = 'dark' vim.cmd('colorscheme rose-pine') end function set_light_colors() vim.o.background = 'light' vim.cmd('colorscheme rose-pine') end function update_colors() local is_dark = os.capture('defaults read -g AppleInterfaceStyle') == 'Dark' if is_dark then set_dark_colors() else set_light_colors() end end function file_exists(name) local f = io.open(name, "r") return f ~= nil and io.close(f) end function file_read(name) local f = io.open(name, "r") return f:read('*a') end
mit
Zero-K-Experiments/Zero-K-Experiments
lups/ParticleClasses/UnitPieceLight.lua
4
10310
-- $Id: UnitPieceLight.lua 3171 2008-11-06 09:06:29Z det $ ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- local UnitPieceLight = {} UnitPieceLight.__index = UnitPieceLight local depthtex, offscreentex, blurtex local offscreen4, offscreen8 local blur4, blur8 local depthShader local blurShader local uniformScreenXY, uniformPixelSize, uniformDirection local GL_DEPTH_BITS = 0x0D56 local GL_DEPTH_COMPONENT = 0x1902 local GL_DEPTH_COMPONENT16 = 0x81A5 local GL_DEPTH_COMPONENT24 = 0x81A6 local GL_DEPTH_COMPONENT32 = 0x81A7 ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function UnitPieceLight.GetInfo() return { name = "UnitPieceLight", backup = "", --// backup class, if this class doesn't work (old cards,ati's,etc.) desc = "", layer = 32, --// extreme simply z-ordering :x --// gfx requirement fbo = true, shader = true, rtt = true, ctt = true, ms = 0, } end UnitPieceLight.Default = { layer = 32, life = math.huge, worldspace = true, piecenum = 0, colormap = { {1,1,1,0} }, repeatEffect = true, --// internal color = {1,1,1,0}, } ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function UnitPieceLight:BeginDraw() gl.CopyToTexture(depthtex, 0, 0, 0, 0, vsx, vsy) gl.Texture(depthtex) gl.UseShader(depthShader) gl.Uniform(uniformScreenXY, math.ceil(vsx*0.5),math.ceil(vsy*0.5) ) gl.RenderToTexture(offscreentex, gl.Clear, GL.COLOR_BUFFER_BIT ,0,0,0,0) end function UnitPieceLight:EndDraw() gl.Color(1,1,1,1) gl.UseShader(0) gl.RenderToTexture(offscreen4, function() gl.Clear(GL.COLOR_BUFFER_BIT,0,0,0,0) gl.Texture(offscreentex) gl.TexRect(-1,1,1,-1) end) gl.Texture(offscreentex) gl.UseShader(blurShader) gl.RenderToTexture(blurtex, function() gl.Clear(GL.COLOR_BUFFER_BIT,0,0,0,0) gl.Uniform(uniformDirection, 1,0 ) gl.Uniform(uniformPixelSize, 1.0/math.ceil(vsx*0.5) ) gl.TexRect(-1-0.25/vsx,1+0.25/vsy,1+0.25/vsx,-1-0.25/vsy) end) gl.Texture(blurtex) gl.RenderToTexture(offscreentex, function() gl.Clear(GL.COLOR_BUFFER_BIT,0,0,0,0) gl.Uniform(uniformDirection, 0,1 ) gl.Uniform(uniformPixelSize, math.ceil(vsy*0.5) ) gl.TexRect(-1-0.25/vsx,1+0.25/vsy,1+0.25/vsx,-1-0.25/vsy) end) gl.Texture(offscreen4) gl.RenderToTexture(blur4, function() gl.Clear(GL.COLOR_BUFFER_BIT,0,0,0,0) gl.Uniform(uniformDirection, 1,0 ) gl.Uniform(uniformPixelSize, 1.0/math.ceil(vsx*0.25) ) gl.TexRect(-1-0.125/vsx,1+0.125/vsy,1+0.125/vsx,-1-0.125/vsy) end) gl.Texture(blur4) gl.RenderToTexture(offscreen4, function() gl.Clear(GL.COLOR_BUFFER_BIT,0,0,0,0) gl.Uniform(uniformDirection, 0,1 ) gl.Uniform(uniformPixelSize, 1.0/math.ceil(vsy*0.25) ) gl.TexRect(-1-0.125/vsx,1+0.125/vsy,1+0.125/vsx,-1-0.125/vsy) end) gl.UseShader(0) gl.Blending(GL.ONE,GL.ONE) gl.MatrixMode(GL.PROJECTION); gl.PushMatrix(); gl.LoadIdentity() gl.MatrixMode(GL.MODELVIEW); gl.PushMatrix(); gl.LoadIdentity() gl.Texture(offscreentex) gl.TexRect(-1-0.5/vsx,1+0.5/vsy,1+0.5/vsx,-1-0.5/vsy) gl.Texture(offscreen4) gl.TexRect(-1-0.5/vsx,1+0.5/vsy,1+0.5/vsx,-1-0.5/vsy) gl.MatrixMode(GL.PROJECTION); gl.PopMatrix() gl.MatrixMode(GL.MODELVIEW); gl.PopMatrix() gl.Blending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA) gl.Texture(false) gl.UseShader(0) end function UnitPieceLight:Draw() gl.Color(self.color) gl.RenderToTexture(offscreentex, function() gl.PushMatrix() gl.ResetMatrices() gl.UnitMultMatrix(self.unit) gl.UnitPieceMultMatrix(self.unit,self.piecenum) gl.UnitPiece(self.unit,self.piecenum) gl.PopMatrix() end) end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function UnitPieceLight:Update() self.life = self.life + self.life_incr self.color = {GetColor(self.colormap,self.life)} end -- used if repeatEffect=true; function UnitPieceLight:ReInitialize() self.life = 0 self.dieGameFrame = self.dieGameFrame + self.clife end function UnitPieceLight.Initialize() depthShader = gl.CreateShader({ fragment = [[ uniform sampler2D tex0; uniform vec2 screenXY; void main(void) { vec2 texCoord = vec2( gl_FragCoord.x/screenXY.x , gl_FragCoord.y/screenXY.y ); float depth = texture2D(tex0, texCoord ).z; if (depth <= gl_FragCoord.z-0.0005) { discard; } gl_FragColor = gl_Color; } ]], uniformInt = { tex0 = 0, }, uniform = { screenXY = {math.ceil(vsx*0.5),math.ceil(vsy*0.5)}, }, }) if (depthShader == nil) then print(PRIO_MAJOR,"LUPS->UnitPieceLights: Critical Shader Error: DepthShader: "..gl.GetShaderLog()) return false end blurShader = gl.CreateShader({ fragment = [[ float kernel[7]; uniform sampler2D tex0; uniform float pixelsize; uniform vec2 dir; void InitKernel(void) { kernel[0] = 0.013; kernel[1] = 0.054; kernel[2] = 0.069; kernel[3] = 0.129; kernel[4] = 0.212; kernel[5] = 0.301; kernel[6] = 0.372; } void main(void) { InitKernel(); vec2 texCoord = vec2(gl_TextureMatrix[0] * gl_TexCoord[0]); gl_FragColor = vec4(0.0); int n,i; i=1; for(n=6; n >= 0; --n){ gl_FragColor += kernel[n] * texture2D(tex0, texCoord.st + dir * float(i)*pixelsize ); ++i; } gl_FragColor += 0.4 * texture2D(tex0, texCoord ); i = -7; for(n=0; n <= 6; ++n){ gl_FragColor += kernel[n] * texture2D(tex0, texCoord.st + dir * float(i)*pixelsize ); ++i; } } ]], uniformInt = { tex0 = 0, uniform = { pixelsize = 1.0/math.ceil(vsx*0.5), } }, }) if (blurShader == nil) then print(PRIO_MAJOR,"LUPS->UnitPieceLights: Critical Shader Error: BlurShader: "..gl.GetShaderLog()) return false end uniformScreenXY = gl.GetUniformLocation(depthShader, 'screenXY') uniformPixelSize = gl.GetUniformLocation(blurShader, 'pixelsize') uniformDirection = gl.GetUniformLocation(blurShader, 'dir') UnitPieceLight.ViewResize(vsx, vsy) end function UnitPieceLight.Finalize() gl.DeleteTexture(depthtex) if (gl.DeleteTextureFBO) then gl.DeleteTextureFBO(offscreentex) gl.DeleteTextureFBO(blurtex) end if (gl.DeleteShader) then gl.DeleteShader(depthShader or 0) gl.DeleteShader(blurShader or 0) end end function UnitPieceLight.ViewResize(vsx, vsy) gl.DeleteTexture(depthtex or 0) gl.DeleteTextureFBO(offscreentex or 0) gl.DeleteTextureFBO(blurtex or 0) gl.DeleteTextureFBO(offscreen4 or 0) gl.DeleteTextureFBO(blur4 or 0) depthtex = gl.CreateTexture(vsx,vsy, { border = false, format = GL_DEPTH_COMPONENT24, min_filter = GL.NEAREST, mag_filter = GL.NEAREST, }) offscreentex = gl.CreateTexture(math.ceil(vsx*0.5),math.ceil(vsy*0.5), { border = false, min_filter = GL.LINEAR, mag_filter = GL.LINEAR, wrap_s = GL.CLAMP_TO_BORDER, wrap_t = GL.CLAMP_TO_BORDER, fbo = true, }) offscreen4 = gl.CreateTexture(math.ceil(vsx*0.25),math.ceil(vsy*0.25), { border = false, min_filter = GL.LINEAR, mag_filter = GL.LINEAR, wrap_s = GL.CLAMP_TO_BORDER, wrap_t = GL.CLAMP_TO_BORDER, fbo = true, }) blurtex = gl.CreateTexture(math.ceil(vsx*0.5),math.ceil(vsy*0.5), { border = false, min_filter = GL.LINEAR, mag_filter = GL.LINEAR, wrap_s = GL.CLAMP_TO_BORDER, wrap_t = GL.CLAMP_TO_BORDER, fbo = true, }) blur4 = gl.CreateTexture(math.ceil(vsx*0.25),math.ceil(vsy*0.25), { border = false, min_filter = GL.LINEAR, mag_filter = GL.LINEAR, wrap_s = GL.CLAMP_TO_BORDER, wrap_t = GL.CLAMP_TO_BORDER, fbo = true, }) end function UnitPieceLight:Visible() local ux,uy,uz = Spring.GetUnitViewPosition(self.unit) if not ux then return false end local pos = {0,0,0} pos[1],pos[2],pos[3] = pos[1]+ux,pos[2]+uy,pos[3]+uz local radius = 300 + Spring.GetUnitRadius(self.unit) local losState = Spring.GetUnitLosState(self.unit, LocalAllyTeamID) return (losState and losState.los)and(Spring.IsSphereInView(pos[1],pos[2],pos[3],radius)) end function UnitPieceLight:Valid() local ux = Spring.GetUnitViewPosition(self.unit) if (ux) then return true else return false end end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function UnitPieceLight:CreateParticle() self.clife = self.life self.life_incr = 1/self.life self.life = 0 self.dieGameFrame = Spring.GetGameFrame() + self.clife end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function UnitPieceLight.Create(Options) local newObject = MergeTable(Options, UnitPieceLight.Default) setmetatable(newObject,UnitPieceLight) -- make handle lookup newObject:CreateParticle() return newObject end function UnitPieceLight:Destroy() end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- return UnitPieceLight
gpl-2.0
Scavenge/darkstar
scripts/globals/spells/kurayami_san.lua
27
1145
----------------------------------------- -- Spell: Kurayami: San ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) -- Base Stats local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT)); --Duration Calculation local duration = 420 * applyResistance(caster,spell,target,dINT,NINJUTSU_SKILL,0); --Kurayami base power is 30 and is not affected by resistaces. local power = 30; --Calculates resist chanve from Reist Blind if (math.random(0,100) >= target:getMod(MOD_BLINDRES)) then if (duration >= 210) then if (target:addStatusEffect(EFFECT_BLINDNESS,power,0,duration)) then spell:setMsg(236); else spell:setMsg(75); end else spell:setMsg(85); end else spell:setMsg(284); end return EFFECT_BLINDNESS; end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Caedarva_Mire/npcs/Runic_Portal.lua
25
2671
----------------------------------- -- Area: Caedarva Mire -- NPC: Runic Portal -- Caedarva Mire Teleporter Back to Aht Urhgan Whitegate -- @pos -264 -6 -28 79 (Dvucca) -- @pos 524 -28 -503 79 (Azouph) ----------------------------------- package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Caedarva_Mire/TextIDs"); require("scripts/globals/teleports"); require("scripts/globals/missions"); require("scripts/globals/besieged"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local X = player:getXPos(); local Z = player:getZPos(); if ((X < -258.512 and X > -270.512) and (Z < -22.285 and Z > -34.285)) then -- Dvucca Staging Point if (player:getCurrentMission(TOAU) == IMMORTAL_SENTRIES and player:getVar("AhtUrganStatus") == 1) then player:startEvent(125); elseif (player:getCurrentMission(TOAU) > IMMORTAL_SENTRIES) then if (hasRunicPortal(player,2) == 1) then player:startEvent(134); else player:startEvent(125); end else player:messageSpecial(RESPONSE); end else -- Azouph Staging Point if (player:getCurrentMission(TOAU) == IMMORTAL_SENTRIES and player:getVar("AhtUrganStatus") == 1) then player:startEvent(124); elseif (player:getCurrentMission(TOAU) > IMMORTAL_SENTRIES) then if (hasRunicPortal(player,1) == 1) then player:startEvent(134); else player:startEvent(124); end else player:messageSpecial(RESPONSE); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 124 and option == 1) then player:addNationTeleport(AHTURHGAN,2); toChamberOfPassage(player); elseif (csid == 125 and option == 1) then player:addNationTeleport(AHTURHGAN,4); toChamberOfPassage(player); elseif ((csid == 134 or 131) and option == 1) then toChamberOfPassage(player); end end;
gpl-3.0
Scavenge/darkstar
scripts/globals/items/coeurl_sub.lua
12
1928
----------------------------------------- -- ID: 5166 -- Item: coeurl_sub -- Food Effect: 30Min, All Races ----------------------------------------- -- Magic 10 -- Strength 5 -- Agility 1 -- Intelligence -2 -- Health Regen While Healing 1 -- Attack % 20 -- Attack Cap 75 -- Ranged ATT % 20 -- Ranged ATT Cap 75 -- Resist Stun +4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5166); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 10); target:addMod(MOD_STR, 5); target:addMod(MOD_AGI, 1); target:addMod(MOD_INT, -2); target:addMod(MOD_HPHEAL, 1); target:addMod(MOD_FOOD_ATTP, 20); target:addMod(MOD_FOOD_ATT_CAP, 75); target:addMod(MOD_FOOD_RATTP, 20); target:addMod(MOD_FOOD_RATT_CAP, 75); target:addMod(MOD_STUNRES, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 10); target:delMod(MOD_STR, 5); target:delMod(MOD_AGI, 1); target:delMod(MOD_INT, -2); target:delMod(MOD_HPHEAL, 1); target:delMod(MOD_FOOD_ATTP, 20); target:delMod(MOD_FOOD_ATT_CAP, 75); target:delMod(MOD_FOOD_RATTP, 20); target:delMod(MOD_FOOD_RATT_CAP, 75); target:delMod(MOD_STUNRES, 4); end;
gpl-3.0
phi-gamma/lualibs
lualibs-io.lua
3
10014
if not modules then modules = { } end modules ['l-io'] = { version = 1.001, comment = "companion to luat-lib.mkiv", author = "Hans Hagen, PRAGMA-ADE, Hasselt NL", copyright = "PRAGMA ADE / ConTeXt Development Team", license = "see context related readme files" } local io = io local open, flush, write, read = io.open, io.flush, io.write, io.read local byte, find, gsub, format = string.byte, string.find, string.gsub, string.format local concat = table.concat local floor = math.floor local type = type if string.find(os.getenv("PATH"),";",1,true) then io.fileseparator, io.pathseparator = "\\", ";" else io.fileseparator, io.pathseparator = "/" , ":" end local function readall(f) return f:read("*all") end -- The next one is upto 50% faster on large files and less memory consumption due -- to less intermediate large allocations. This phenomena was discussed on the -- luatex dev list. local function readall(f) local size = f:seek("end") if size == 0 then return "" end f:seek("set",0) if size < 1024*1024 then return f:read('*all') else local step if size > 16*1024*1024 then step = 16*1024*1024 else step = floor(size/(1024*1024)) * 1024 * 1024 / 8 end local data = { } while true do local r = f:read(step) if not r then return concat(data) else data[#data+1] = r end end end end io.readall = readall function io.loaddata(filename,textmode) -- return nil if empty local f = open(filename,(textmode and 'r') or 'rb') if f then local data = readall(f) f:close() if #data > 0 then return data end end end function io.copydata(source,target,action) local f = open(source,"rb") if f then local g = open(target,"wb") if g then local size = f:seek("end") if size == 0 then -- empty else f:seek("set",0) if size < 1024*1024 then local data = f:read('*all') if action then data = action(data) end if data then g:write(data) end else local step if size > 16*1024*1024 then step = 16*1024*1024 else step = floor(size/(1024*1024)) * 1024 * 1024 / 8 end while true do local data = f:read(step) if data then if action then data = action(data) end if data then g:write(data) end else break end end end end g:close() end f:close() flush() end end function io.savedata(filename,data,joiner) local f = open(filename,"wb") if f then if type(data) == "table" then f:write(concat(data,joiner or "")) elseif type(data) == "function" then data(f) else f:write(data or "") end f:close() flush() return true else return false end end -- we can also chunk this one if needed: io.lines(filename,chunksize,"*l") function io.loadlines(filename,n) -- return nil if empty local f = open(filename,'r') if not f then -- no file elseif n then local lines = { } for i=1,n do local line = f:read("*lines") if line then lines[#lines+1] = line else break end end f:close() lines = concat(lines,"\n") if #lines > 0 then return lines end else local line = f:read("*line") or "" f:close() if #line > 0 then return line end end end function io.loadchunk(filename,n) local f = open(filename,'rb') if f then local data = f:read(n or 1024) f:close() if #data > 0 then return data end end end function io.exists(filename) local f = open(filename) if f == nil then return false else f:close() return true end end function io.size(filename) local f = open(filename) if f == nil then return 0 else local s = f:seek("end") f:close() return s end end local function noflines(f) if type(f) == "string" then local f = open(filename) if f then local n = f and noflines(f) or 0 f:close() return n else return 0 end else local n = 0 for _ in f:lines() do n = n + 1 end f:seek('set',0) return n end end io.noflines = noflines -- inlined is faster local nextchar = { [ 4] = function(f) return f:read(1,1,1,1) end, [ 2] = function(f) return f:read(1,1) end, [ 1] = function(f) return f:read(1) end, [-2] = function(f) local a, b = f:read(1,1) return b, a end, [-4] = function(f) local a, b, c, d = f:read(1,1,1,1) return d, c, b, a end } function io.characters(f,n) if f then return nextchar[n or 1], f end end local nextbyte = { [4] = function(f) local a, b, c, d = f:read(1,1,1,1) if d then return byte(a), byte(b), byte(c), byte(d) end end, [3] = function(f) local a, b, c = f:read(1,1,1) if b then return byte(a), byte(b), byte(c) end end, [2] = function(f) local a, b = f:read(1,1) if b then return byte(a), byte(b) end end, [1] = function (f) local a = f:read(1) if a then return byte(a) end end, [-2] = function (f) local a, b = f:read(1,1) if b then return byte(b), byte(a) end end, [-3] = function(f) local a, b, c = f:read(1,1,1) if b then return byte(c), byte(b), byte(a) end end, [-4] = function(f) local a, b, c, d = f:read(1,1,1,1) if d then return byte(d), byte(c), byte(b), byte(a) end end } function io.bytes(f,n) if f then return nextbyte[n or 1], f else return nil, nil end end function io.ask(question,default,options) while true do write(question) if options then write(format(" [%s]",concat(options,"|"))) end if default then write(format(" [%s]",default)) end write(format(" ")) flush() local answer = read() answer = gsub(answer,"^%s*(.*)%s*$","%1") if answer == "" and default then return default elseif not options then return answer else for k=1,#options do if options[k] == answer then return answer end end local pattern = "^" .. answer for k=1,#options do local v = options[k] if find(v,pattern) then return v end end end end end local function readnumber(f,n,m) if m then f:seek("set",n) n = m end if n == 1 then return byte(f:read(1)) elseif n == 2 then local a, b = byte(f:read(2),1,2) return 256 * a + b elseif n == 3 then local a, b, c = byte(f:read(3),1,3) return 256*256 * a + 256 * b + c elseif n == 4 then local a, b, c, d = byte(f:read(4),1,4) return 256*256*256 * a + 256*256 * b + 256 * c + d elseif n == 8 then local a, b = readnumber(f,4), readnumber(f,4) return 256 * a + b elseif n == 12 then local a, b, c = readnumber(f,4), readnumber(f,4), readnumber(f,4) return 256*256 * a + 256 * b + c elseif n == -2 then local b, a = byte(f:read(2),1,2) return 256*a + b elseif n == -3 then local c, b, a = byte(f:read(3),1,3) return 256*256 * a + 256 * b + c elseif n == -4 then local d, c, b, a = byte(f:read(4),1,4) return 256*256*256 * a + 256*256 * b + 256*c + d elseif n == -8 then local h, g, f, e, d, c, b, a = byte(f:read(8),1,8) return 256*256*256*256*256*256*256 * a + 256*256*256*256*256*256 * b + 256*256*256*256*256 * c + 256*256*256*256 * d + 256*256*256 * e + 256*256 * f + 256 * g + h else return 0 end end io.readnumber = readnumber function io.readstring(f,n,m) if m then f:seek("set",n) n = m end local str = gsub(f:read(n),"\000","") return str end -- This works quite ok: -- -- function io.piped(command,writer) -- local pipe = io.popen(command) -- -- for line in pipe:lines() do -- -- print(line) -- -- end -- while true do -- local line = pipe:read(1) -- if not line then -- break -- elseif line ~= "\n" then -- writer(line) -- end -- end -- return pipe:close() -- ok, status, (error)code -- end
gpl-2.0
flux-framework/flux-core
src/bindings/lua/Test/Builder/Tester/File.lua
8
1245
-- -- lua-TestMore : <http://fperrad.github.com/lua-TestMore/> -- local tconcat = require 'table'.concat local setmetatable = setmetatable local tb = require 'Test.Builder'.new() _ENV = nil local m = {} function m.new (_type) local o = setmetatable({ type = _type }, { __index = m }) o:reset() return o end function m:write (...) self.got = self.got .. tconcat({...}) end function m:reset () self.got = '' self.wanted = {} end function m:expect (...) local arg = {...} local wanted = self.wanted for i = 1, #arg do wanted[#wanted+1] = arg[i] end end function m:check () local got = self.got local wanted = tconcat(self.wanted, "\n") if wanted ~= '' then wanted = wanted .. "\n" end return got == wanted end function m:complaint () local type = self.type local got = self.got local wanted = tconcat(self.wanted, "\n") if wanted ~= '' then wanted = wanted .. "\n" end return type .. " is:" .. "\n" .. got .. "\nnot:" .. "\n" .. wanted .. "\nhas expected" end return m -- -- Copyright (c) 2009-2012 Francois Perrad -- -- This library is licensed under the terms of the MIT/X11 license, -- like Lua itself. --
lgpl-3.0
DebugClub/slua
build/luajit-2.0.4/src/jit/bc.lua
88
5606
---------------------------------------------------------------------------- -- LuaJIT bytecode listing module. -- -- Copyright (C) 2005-2015 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module lists the bytecode of a Lua function. If it's loaded by -jbc -- it hooks into the parser and lists all functions of a chunk as they -- are parsed. -- -- Example usage: -- -- luajit -jbc -e 'local x=0; for i=1,1e6 do x=x+i end; print(x)' -- luajit -jbc=- foo.lua -- luajit -jbc=foo.list foo.lua -- -- Default output is to stderr. To redirect the output to a file, pass a -- filename as an argument (use '-' for stdout) or set the environment -- variable LUAJIT_LISTFILE. The file is overwritten every time the module -- is started. -- -- This module can also be used programmatically: -- -- local bc = require("jit.bc") -- -- local function foo() print("hello") end -- -- bc.dump(foo) --> -- BYTECODE -- [...] -- print(bc.line(foo, 2)) --> 0002 KSTR 1 1 ; "hello" -- -- local out = { -- -- Do something with each line: -- write = function(t, ...) io.write(...) end, -- close = function(t) end, -- flush = function(t) end, -- } -- bc.dump(foo, out) -- ------------------------------------------------------------------------------ -- Cache some library functions and objects. local jit = require("jit") assert(jit.version_num == 20004, "LuaJIT core/library version mismatch") local jutil = require("jit.util") local vmdef = require("jit.vmdef") local bit = require("bit") local sub, gsub, format = string.sub, string.gsub, string.format local byte, band, shr = string.byte, bit.band, bit.rshift local funcinfo, funcbc, funck = jutil.funcinfo, jutil.funcbc, jutil.funck local funcuvname = jutil.funcuvname local bcnames = vmdef.bcnames local stdout, stderr = io.stdout, io.stderr ------------------------------------------------------------------------------ local function ctlsub(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" else return format("\\%03d", byte(c)) end end -- Return one bytecode line. local function bcline(func, pc, prefix) local ins, m = funcbc(func, pc) if not ins then return end local ma, mb, mc = band(m, 7), band(m, 15*8), band(m, 15*128) local a = band(shr(ins, 8), 0xff) local oidx = 6*band(ins, 0xff) local op = sub(bcnames, oidx+1, oidx+6) local s = format("%04d %s %-6s %3s ", pc, prefix or " ", op, ma == 0 and "" or a) local d = shr(ins, 16) if mc == 13*128 then -- BCMjump return format("%s=> %04d\n", s, pc+d-0x7fff) end if mb ~= 0 then d = band(d, 0xff) elseif mc == 0 then return s.."\n" end local kc if mc == 10*128 then -- BCMstr kc = funck(func, -d-1) kc = format(#kc > 40 and '"%.40s"~' or '"%s"', gsub(kc, "%c", ctlsub)) elseif mc == 9*128 then -- BCMnum kc = funck(func, d) if op == "TSETM " then kc = kc - 2^52 end elseif mc == 12*128 then -- BCMfunc local fi = funcinfo(funck(func, -d-1)) if fi.ffid then kc = vmdef.ffnames[fi.ffid] else kc = fi.loc end elseif mc == 5*128 then -- BCMuv kc = funcuvname(func, d) end if ma == 5 then -- BCMuv local ka = funcuvname(func, a) if kc then kc = ka.." ; "..kc else kc = ka end end if mb ~= 0 then local b = shr(ins, 24) if kc then return format("%s%3d %3d ; %s\n", s, b, d, kc) end return format("%s%3d %3d\n", s, b, d) end if kc then return format("%s%3d ; %s\n", s, d, kc) end if mc == 7*128 and d > 32767 then d = d - 65536 end -- BCMlits return format("%s%3d\n", s, d) end -- Collect branch targets of a function. local function bctargets(func) local target = {} for pc=1,1000000000 do local ins, m = funcbc(func, pc) if not ins then break end if band(m, 15*128) == 13*128 then target[pc+shr(ins, 16)-0x7fff] = true end end return target end -- Dump bytecode instructions of a function. local function bcdump(func, out, all) if not out then out = stdout end local fi = funcinfo(func) if all and fi.children then for n=-1,-1000000000,-1 do local k = funck(func, n) if not k then break end if type(k) == "proto" then bcdump(k, out, true) end end end out:write(format("-- BYTECODE -- %s-%d\n", fi.loc, fi.lastlinedefined)) local target = bctargets(func) for pc=1,1000000000 do local s = bcline(func, pc, target[pc] and "=>") if not s then break end out:write(s) end out:write("\n") out:flush() end ------------------------------------------------------------------------------ -- Active flag and output file handle. local active, out -- List handler. local function h_list(func) return bcdump(func, out) end -- Detach list handler. local function bclistoff() if active then active = false jit.attach(h_list) if out and out ~= stdout and out ~= stderr then out:close() end out = nil end end -- Open the output file and attach list handler. local function bcliston(outfile) if active then bclistoff() end if not outfile then outfile = os.getenv("LUAJIT_LISTFILE") end if outfile then out = outfile == "-" and stdout or assert(io.open(outfile, "w")) else out = stderr end jit.attach(h_list, "bc") active = true end -- Public module functions. module(...) line = bcline dump = bcdump targets = bctargets on = bcliston off = bclistoff start = bcliston -- For -j command line option.
mit
Scavenge/darkstar
scripts/zones/Promyvion-Dem/Zone.lua
15
7732
----------------------------------- -- -- Zone: Promyvion-Dem (18) -- ----------------------------------- package.loaded["scripts/zones/Promyvion-Dem/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Promyvion-Dem/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/missions"); require("scripts/globals/keyitems"); require("scripts/globals/status"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) -- zone:registerRegion(11,157,-4,-82,161,4,-77); -- Level 1 Return zone:registerRegion(12,117,-4,-283,122,4,-277); -- Level 1 MR -- zone:registerRegion(21,-383,-4,-2,-278,4,2); -- Level Two Return zone:registerRegion(22,-82,-4,76,-77,4,80); -- Level Two MR1 zone:registerRegion(23,-361,-4,36,-356,4,42); -- Level Two MR2 zone:registerRegion(24,-83,-4,-83,-77,4,-76); -- Level Two MR3 zone:registerRegion(25,-282,-4,-202,-277,4,-196); -- Level Two MR4 -- zone:registerRegion(31,-160,-4,437,-157,4,441); -- Level Three West Return zone:registerRegion(32,-42,-4,317,-37,4,322); -- Level Three West MR1 zone:registerRegion(33,-322,-4,156,-316,4,162); -- Level Three West MR2 zone:registerRegion(34,-122,-4,157,-118,4,163); -- Level Three West MR3 -- zone:registerRegion(35,-2,-4,-322,2,4,-317); -- Level Three East Return zone:registerRegion(36,37,-4,-203,43,4,-198); -- Level Three East MR1 zone:registerRegion(37,-122,-4,-242,-116,4,-237); -- Level Three East MR2 zone:registerRegion(38,-122,-4,-402,-116,4,-396); -- Level Three East MR3 -- zone:registerRegion(41,357,-4,237,361,4,242); -- Level Four Return end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(185.891, 0, -52.331, 128, 18); -- {R} end if (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") == 2) then player:completeMission(COP,BELOW_THE_ARKS); player:addMission(COP,THE_MOTHERCRYSTALS); -- start mission 1.3 player:setVar("PromathiaStatus",0); elseif (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS) then if (player:hasKeyItem(LIGHT_OF_HOLLA) and player:hasKeyItem(LIGHT_OF_MEA)) then if (player:getVar("cslastpromy") == 1) then player:setVar("cslastpromy",0) cs = 0x0034; end elseif (player:hasKeyItem(LIGHT_OF_HOLLA) or player:hasKeyItem(LIGHT_OF_MEA)) then if (player:getVar("cs2ndpromy") == 1) then player:setVar("cs2ndpromy",0) cs = 0x0033; end end end if (player:getVar("FirstPromyvionDem") == 1) then cs = 0x0032; elseif (ENABLE_COP_ZONE_CAP == 1) then player:addStatusEffect(EFFECT_LEVEL_RESTRICTION,30,0,0);-- ZONE LEVEL RESTRICTION end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) -- regionID =region:GetRegionID(); -- printf("regionID: %u",regionID); if (player:getAnimation()==0) then switch (region:GetRegionID()): caseof { [11] = function (x) player:startEvent(0x002E); end, [12] = function (x) if (GetNPCByID(16851268):getAnimation() == 8) then player:startEvent(30); end end, [21] = function (x) player:startEvent(41); end, [22] = function (x) if (GetNPCByID(16851273):getAnimation() == 8) then if (player:getVar("MemoryReceptacle") == 2) then player:startEvent(35); else player:startEvent(34); end end end, [23] = function (x) if (GetNPCByID(16851275):getAnimation() == 8) then if (player:getVar("MemoryReceptacle") == 2) then player:startEvent(35); else player:startEvent(34); end end end, [24] = function (x) if (GetNPCByID(16851272):getAnimation() == 8) then if (player:getVar("MemoryReceptacle") == 2) then player:startEvent(35); else player:startEvent(34); end end end, [25] = function (x) if (GetNPCByID(16851274):getAnimation() == 8) then if (player:getVar("MemoryReceptacle") == 2) then player:startEvent(35); else player:startEvent(34); end end end, [31] = function (x) player:startEvent(30); end, [32] = function (x) if (GetNPCByID(16851277):getAnimation() == 8) then player:startEvent(32); end end, [33] = function (x) if (GetNPCByID(16851276):getAnimation() == 8) then player:startEvent(32); end end, [34] = function (x) if (GetNPCByID(16851278):getAnimation() == 8) then player:startEvent(32); end end, [35] = function (x) player:startEvent(30); end, [36] = function (x) if (GetNPCByID(16851269):getAnimation() == 8) then player:startEvent(32); end end, [37] = function (x) if (GetNPCByID(16851270):getAnimation() == 8) then player:startEvent(32); end end, [38] = function (x) if (GetNPCByID(16851271):getAnimation() == 8) then player:startEvent(32); end end, [41] = function (x) if (player:getVar("MemoryReceptacle") == 2) then player:startEvent(31); else player:startEvent(34); end end, } end end; ----------------------------------- -- onRegionLeave ----------------------------------- function onRegionLeave(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x002e and option == 1) then player:setPos(-226.193, -46.459, -280.046, 127, 14); -- To Hall of Transference {R} elseif (csid == 0x0032) then player:setVar("FirstPromyvionDem",0); if (ENABLE_COP_ZONE_CAP == 1) then player:addStatusEffect(EFFECT_LEVEL_RESTRICTION,30,0,0); -- ZONE LEVEL RESTRICTION end end if (option==1) then player:setVar("MemoryReceptacle",0); end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Yughott_Grotto/TextIDs.lua
7
1096
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6538; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6544; -- Obtained: <item>. GIL_OBTAINED = 6545; -- Obtained <number> gil. KEYITEM_OBTAINED = 6547; -- Obtained key item: <keyitem>. FISHING_MESSAGE_OFFSET = 7205; -- You can't fish here. HOMEPOINT_SET = 7438; -- Home point set! -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7330; -- You unlock the chest! CHEST_FAIL = 7331; -- Fails to open the chest. CHEST_TRAP = 7332; -- The chest was trapped! CHEST_WEAK = 7333; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7334; -- The chest was a mimic! CHEST_MOOGLE = 7335; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7336; -- The chest was but an illusion... CHEST_LOCKED = 7337; -- The chest appears to be locked. -- Mining MINING_IS_POSSIBLE_HERE = 7338; -- Mining is possible here if you have -- conquest Base CONQUEST_BASE = 0;
gpl-3.0
smanolache/kong
kong/plugins/response-transformer/body_transformer.lua
1
2808
local stringy = require "stringy" local cjson = require "cjson" local table_insert = table.insert local pcall = pcall local string_find = string.find local unpack = unpack local type = type local _M = {} local function read_json_body(body) if body then local status, res = pcall(cjson.decode, body) if status then return res end end end local function append_value(current_value, value) local current_value_type = type(current_value) if current_value_type == "string" then return {current_value, value} elseif current_value_type == "table" then table_insert(current_value, value) return current_value else return {value} end end local function iter(config_array) return function(config_array, i, previous_name, previous_value) i = i + 1 local current_pair = config_array[i] if current_pair == nil then -- n + 1 return nil end local current_name, current_value = unpack(stringy.split(current_pair, ":")) return i, current_name, current_value end, config_array, 0 end function _M.is_json_body(content_type) return content_type and string_find(content_type:lower(), "application/json", nil, true) end function _M.transform_json_body(conf, buffered_data) local json_body = read_json_body(buffered_data) if json_body == nil then return end -- remove key:value to body for _, name in iter(conf.remove.json) do json_body[name] = nil end -- replace key:value to body for _, name, value in iter(conf.replace.json) do local v = cjson.encode(value) if stringy.startswith(v, "\"") and stringy.endswith(v, "\"") then v = v:sub(2, v:len() - 1):gsub("\\\"", "\"") -- To prevent having double encoded quotes end v = v:gsub("\\/", "/") -- To prevent having double encoded slashes if json_body[name] then json_body[name] = v end end -- add new key:value to body for _, name, value in iter(conf.add.json) do local v = cjson.encode(value) if stringy.startswith(v, "\"") and stringy.endswith(v, "\"") then v = v:sub(2, v:len() - 1):gsub("\\\"", "\"") -- To prevent having double encoded quotes end v = v:gsub("\\/", "/") -- To prevent having double encoded slashes if not json_body[name] then json_body[name] = v end end -- append new key:value or value to existing key for _, name, value in iter(conf.append.json) do local v = cjson.encode(value) if stringy.startswith(v, "\"") and stringy.endswith(v, "\"") then v = v:sub(2, v:len() - 1):gsub("\\\"", "\"") -- To prevent having double encoded quotes end v = v:gsub("\\/", "/") -- To prevent having double encoded slashes json_body[name] = append_value(json_body[name],v) end return cjson.encode(json_body) end return _M
apache-2.0
Scavenge/darkstar
scripts/zones/Abyssea-La_Theine/mobs/Piasa.lua
12
1376
----------------------------------- -- Area: Abyssea - La Theine -- MOB: Piasa ----------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_ADD_EFFECT, 1); end; ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(mob,target,damage) -- Resistance calcs should cause the addEffect damage to fall below 50 to get that 30-50 range wiki speaks of.. -- But our resists don't appear to be fully retail, so we are still using randomness here instead. local basePower = math.random(40,50); -- Best guess off wiki and assumption of non lv/stat scaled dmg local params = {}; params.bonusmab = 0; params.includemab = false; local dmg = addBonusesAbility(mob, ELE_WIND, target, basePower, params); dmg = dmg * applyResistanceAddEffect(mob,target,ELE_WIND,0); dmg = adjustForTarget(target,dmg,ELE_WIND); dmg = finalMagicNonSpellAdjustments(mob,target,ELE_WIND,dmg); return SUBEFFECT_WIND_DAMAGE, MSGBASIC_ADD_EFFECT_DMG, dmg; end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,player,isKiller) end;
gpl-3.0
Kyklas/luci-proto-hso
applications/luci-asterisk/luasrc/model/cbi/asterisk.lua
80
5333
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- cbimap = Map("asterisk", "asterisk", "") asterisk = cbimap:section(TypedSection, "asterisk", "Asterisk General Options", "") asterisk.anonymous = true agidir = asterisk:option(Value, "agidir", "AGI directory", "") agidir.rmempty = true cache_record_files = asterisk:option(Flag, "cache_record_files", "Cache recorded sound files during recording", "") cache_record_files.rmempty = true debug = asterisk:option(Value, "debug", "Debug Level", "") debug.rmempty = true dontwarn = asterisk:option(Flag, "dontwarn", "Disable some warnings", "") dontwarn.rmempty = true dumpcore = asterisk:option(Flag, "dumpcore", "Dump core on crash", "") dumpcore.rmempty = true highpriority = asterisk:option(Flag, "highpriority", "High Priority", "") highpriority.rmempty = true initcrypto = asterisk:option(Flag, "initcrypto", "Initialise Crypto", "") initcrypto.rmempty = true internal_timing = asterisk:option(Flag, "internal_timing", "Use Internal Timing", "") internal_timing.rmempty = true logdir = asterisk:option(Value, "logdir", "Log directory", "") logdir.rmempty = true maxcalls = asterisk:option(Value, "maxcalls", "Maximum number of calls allowed", "") maxcalls.rmempty = true maxload = asterisk:option(Value, "maxload", "Maximum load to stop accepting new calls", "") maxload.rmempty = true nocolor = asterisk:option(Flag, "nocolor", "Disable console colors", "") nocolor.rmempty = true record_cache_dir = asterisk:option(Value, "record_cache_dir", "Sound files Cache directory", "") record_cache_dir.rmempty = true record_cache_dir:depends({ ["cache_record_files"] = "true" }) rungroup = asterisk:option(Flag, "rungroup", "The Group to run as", "") rungroup.rmempty = true runuser = asterisk:option(Flag, "runuser", "The User to run as", "") runuser.rmempty = true spooldir = asterisk:option(Value, "spooldir", "Voicemail Spool directory", "") spooldir.rmempty = true systemname = asterisk:option(Value, "systemname", "Prefix UniquID with system name", "") systemname.rmempty = true transcode_via_sln = asterisk:option(Flag, "transcode_via_sln", "Build transcode paths via SLINEAR, not directly", "") transcode_via_sln.rmempty = true transmit_silence_during_record = asterisk:option(Flag, "transmit_silence_during_record", "Transmit SLINEAR silence while recording a channel", "") transmit_silence_during_record.rmempty = true verbose = asterisk:option(Value, "verbose", "Verbose Level", "") verbose.rmempty = true zone = asterisk:option(Value, "zone", "Time Zone", "") zone.rmempty = true hardwarereboot = cbimap:section(TypedSection, "hardwarereboot", "Reload Hardware Config", "") method = hardwarereboot:option(ListValue, "method", "Reboot Method", "") method:value("web", "Web URL (wget)") method:value("system", "program to run") method.rmempty = true param = hardwarereboot:option(Value, "param", "Parameter", "") param.rmempty = true iaxgeneral = cbimap:section(TypedSection, "iaxgeneral", "IAX General Options", "") iaxgeneral.anonymous = true iaxgeneral.addremove = true allow = iaxgeneral:option(MultiValue, "allow", "Allow Codecs", "") allow:value("alaw", "alaw") allow:value("gsm", "gsm") allow:value("g726", "g726") allow.rmempty = true canreinvite = iaxgeneral:option(ListValue, "canreinvite", "Reinvite/redirect media connections", "") canreinvite:value("yes", "Yes") canreinvite:value("nonat", "Yes when not behind NAT") canreinvite:value("update", "Use UPDATE rather than INVITE for path redirection") canreinvite:value("no", "No") canreinvite.rmempty = true static = iaxgeneral:option(Flag, "static", "Static", "") static.rmempty = true writeprotect = iaxgeneral:option(Flag, "writeprotect", "Write Protect", "") writeprotect.rmempty = true sipgeneral = cbimap:section(TypedSection, "sipgeneral", "Section sipgeneral", "") sipgeneral.anonymous = true sipgeneral.addremove = true allow = sipgeneral:option(MultiValue, "allow", "Allow codecs", "") allow:value("ulaw", "ulaw") allow:value("alaw", "alaw") allow:value("gsm", "gsm") allow:value("g726", "g726") allow.rmempty = true port = sipgeneral:option(Value, "port", "SIP Port", "") port.rmempty = true realm = sipgeneral:option(Value, "realm", "SIP realm", "") realm.rmempty = true moh = cbimap:section(TypedSection, "moh", "Music On Hold", "") application = moh:option(Value, "application", "Application", "") application.rmempty = true application:depends({ ["asterisk.moh.mode"] = "custom" }) directory = moh:option(Value, "directory", "Directory of Music", "") directory.rmempty = true mode = moh:option(ListValue, "mode", "Option mode", "") mode:value("system", "program to run") mode:value("files", "Read files from directory") mode:value("quietmp3", "Quite MP3") mode:value("mp3", "Loud MP3") mode:value("mp3nb", "unbuffered MP3") mode:value("quietmp3nb", "Quiet Unbuffered MP3") mode:value("custom", "Run a custom application") mode.rmempty = true random = moh:option(Flag, "random", "Random Play", "") random.rmempty = true return cbimap
apache-2.0
ArchonTeam/Soft_TG
plugins/azan.lua
7
3160
--[[ # # @GPMOD # @Dragon_Born # ]] do function run_bash(str) local cmd = io.popen(str) local result = cmd:read('*all') return result end local api_key = nil local base_api = "https://maps.googleapis.com/maps/api" function get_latlong(area) local api = base_api .. "/geocode/json?" local parameters = "address=".. (URL.escape(area) or "") if api_key ~= nil then parameters = parameters .. "&key="..api_key end local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then lat = data.results[1].geometry.location.lat lng = data.results[1].geometry.location.lng acc = data.results[1].geometry.location_type types= data.results[1].types return lat,lng,acc,types end end function get_staticmap(area) local api = base_api .. "/staticmap?" local lat,lng,acc,types = get_latlong(area) local scale = types[1] if scale=="locality" then zoom=8 elseif scale=="country" then zoom=4 else zoom = 13 end local parameters = "size=600x300" .. "&zoom=" .. zoom .. "&center=" .. URL.escape(area) .. "&markers=color:red"..URL.escape("|"..area) if api_key ~=nil and api_key ~= "" then parameters = parameters .. "&key="..api_key end return lat, lng, api..parameters end function run(msg, matches) local hash = 'usecommands:'..msg.from.id..':'..msg.to.id redis:incr(hash) local receiver = get_receiver(msg) local city = matches[1] if matches[1] == 'praytime' then city = 'Tehran' end local lat,lng,url = get_staticmap(city) local dumptime = run_bash('date +%s') local code = http.request('http://api.aladhan.com/timings/'..dumptime..'?latitude='..lat..'&longitude='..lng..'&timezonestring=Asia/Tehran&method=7') local jdat = json:decode(code) local data = jdat.data.timings local text = 'شهر: '..city text = text..'\nاذان صبح: '..data.Fajr text = text..'\nطلوع آفتاب: '..data.Sunrise text = text..'\nاذان ظهر: '..data.Dhuhr text = text..'\nغروب آفتاب: '..data.Sunset text = text..'\nاذان مغرب: '..data.Maghrib text = text..'\nعشاء : '..data.Isha text = text..'\n\n@GPMod Team' if string.match(text, '0') then text = string.gsub(text, '0', '۰') end if string.match(text, '1') then text = string.gsub(text, '1', '۱') end if string.match(text, '2') then text = string.gsub(text, '2', '۲') end if string.match(text, '3') then text = string.gsub(text, '3', '۳') end if string.match(text, '4') then text = string.gsub(text, '4', '۴') end if string.match(text, '5') then text = string.gsub(text, '5', '۵') end if string.match(text, '6') then text = string.gsub(text, '6', '۶') end if string.match(text, '7') then text = string.gsub(text, '7', '۷') end if string.match(text, '8') then text = string.gsub(text, '8', '۸') end if string.match(text, '9') then text = string.gsub(text, '9', '۹') end return text end return { patterns = {"^[/!][Pp]raytime (.*)$","^[/!](praytime)$"}, run = run } end
gpl-2.0
1yvT0s/luvit
deps/https.lua
6
2406
--[[ Copyright 2015 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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. --]] exports.name = "luvit/https" exports.version = "1.0.1-7" exports.dependencies = { "luvit/tls@1.3.0", "luvit/http@1.2.0", } exports.license = "Apache 2" exports.homepage = "https://github.com/luvit/luvit/blob/master/deps/https.lua" exports.description = "Node-style https client and server module for luvit" exports.tags = {"luvit", "https", "stream"} local tls = require('tls') local http = require('http') function exports.createServer(options, onRequest) return tls.createServer(options, function (socket) return http.handleConnection(socket, onRequest) end) end local function createConnection(...) local args = {...} local options = {} local callback if type(args[1]) == 'table' then options = args[1] elseif type(args[2]) == 'table' then options = args[2] options.port = args[1] elseif type(args[3]) == 'table' then options = args[3] options.port = args[2] options.host = args[1] else if type(args[1]) == 'number' then options.port = args[1] end if type(args[2]) == 'string' then options.host = args[2] end end if type(args[#args]) == 'function' then callback = args[#args] end return tls.connect(options, callback) end function exports.request(options, callback) options = http.parseUrl(options) if options.protocol and options.protocol ~= 'https' then error(string.format('Protocol %s not supported', options.protocol)) end options.port = options.port or 443 options.connect_emitter = 'secureConnection' options.socket = options.socket or createConnection(options) return http.request(options, callback) end function exports.get(options, onResponse) options = http.parseUrl(options) options.method = 'GET' local req = exports.request(options, onResponse) req:done() return req end
apache-2.0
Scavenge/darkstar
scripts/globals/items/dolphin_staff.lua
41
1077
----------------------------------------- -- ID: 17134 -- Item: Dolphin Staff -- Additional Effect: Water Damage ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 5; if (math.random(0,99) >= chance) then return 0,0,0; else local dmg = math.random(3,10); local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(player, ELE_WATER, target, dmg, params); dmg = dmg * applyResistanceAddEffect(player,target,ELE_WATER,0); dmg = adjustForTarget(target,dmg,ELE_WATER); dmg = finalMagicNonSpellAdjustments(player,target,ELE_WATER,dmg); local message = MSGBASIC_ADD_EFFECT_DMG; if (dmg < 0) then message = MSGBASIC_ADD_EFFECT_HEAL; end return SUBEFFECT_WATER_DAMAGE,message,dmg; end end;
gpl-3.0
smanolache/kong
kong/dao/dao.lua
1
11386
--- Operates over entities of a given type in a database table. -- An instance of this class is to be instanciated for each entity, and can interact -- with the table representing the entity in the database. -- -- Instanciations of this class are managed by the DAO Factory. -- -- This class provides an abstraction for various databases (PostgreSQL, Cassandra) -- and is responsible for propagating clustering events related to data invalidation, -- as well as foreign constraints when the underlying database does not support them -- (as with Cassandra). -- @module kong.dao local Object = require "classic" local Errors = require "kong.dao.errors" local schemas_validation = require "kong.dao.schemas_validation" local event_types = require("kong.core.events").TYPES local function check_arg(arg, arg_n, exp_type) if type(arg) ~= exp_type then local info = debug.getinfo(2) local err = string.format("bad argument #%d to '%s' (%s expected, got %s)", arg_n, info.name, exp_type, type(arg)) error(err, 3) end end local function check_not_empty(tbl, arg_n) if next(tbl) == nil then local info = debug.getinfo(2) local err = string.format("bad argument #%d to '%s' (expected table to not be empty)", arg_n, info.name) error(err, 3) end end -- Publishes an event, if an event handler has been specified. -- Currently this propagates the events cluster-wide. -- @param[type=string] type The event type to publish -- @param[type=table] data_t The payload to publish in the event local function event(self, type, table, schema, data_t) if self.events_handler then if schema.marshall_event then data_t = schema.marshall_event(schema, data_t) else data_t = {} end local payload = { collection = table, primary_key = schema.primary_key, type = type, entity = data_t } self.events_handler:publish(self.events_handler.TYPES.CLUSTER_PROPAGATE, payload) end end local DAO = Object:extend() --- Instanciate a DAO. -- The DAO Factory is responsible for instanciating DAOs for each entity. -- This method is only documented for clarity. -- @param db An instance of the underlying database object (`cassandra_db` or `postgres_db`) -- @param model_mt The related model metatable. Such metatables contain, among other things, validation methods. -- @param schema The schema of the entity for which this DAO is instanciated. The schema contains crucial informations about how to interact with the database (fields type, table name, etc...) -- @param constraints A table of contraints built by the DAO Factory. Such constraints are mostly useful for databases without support for foreign keys. SQL databases handle those contraints natively. -- @param events_handler Instance of the events propagation class, used to propagate data invalidation events through the cluster. -- @return self function DAO:new(db, model_mt, schema, constraints, events_handler) self.db = db self.model_mt = model_mt self.schema = schema self.table = schema.table self.constraints = constraints self.events_handler = events_handler end --- Insert a row. -- Insert a given Lua table as a row in the related table. -- @param[type=table] tbl Table to insert as a row. -- @param[type=table] options Options to use for this insertion. (`ttl`: Time-to-live for this row, in seconds) -- @treturn table res A table representing the insert row (with fields created during the insertion). -- @treturn table err If an error occured, a table describing the issue. function DAO:insert(tbl, options) check_arg(tbl, 1, "table") local model = self.model_mt(tbl) local ok, err = model:validate {dao = self} if not ok then return nil, err end for col, field in pairs(model.__schema.fields) do if field.dao_insert_value and model[col] == nil then local f = self.db.dao_insert_values[field.type] if f then model[col] = f() end end end local res, err = self.db:insert(self.table, self.schema, model, self.constraints, options) if not err then event(self, event_types.ENTITY_CREATED, self.table, self.schema, res) end return res, err end --- Find a row. -- Find a row by its given, mandatory primary key. All other fields are ignored. -- @param[type=table] tbl A table containing the primary key field(s) for this row. -- @treturn table row The row, or nil if none could be found. -- @treturn table err If an error occured, a table describing the issue. function DAO:find(tbl) check_arg(tbl, 1, "table") local model = self.model_mt(tbl) if not model:has_primary_keys() then error("Missing PRIMARY KEY field", 2) end local primary_keys, _, _, err = model:extract_keys() if err then return nil, Errors.schema(err) end return self.db:find(self.table, self.schema, primary_keys) end --- Find all rows. -- Find all rows in the table, eventually matching the values in the given fields. -- @param[type=table] tbl (optional) A table containing the fields and values to search for. -- @treturn rows An array of rows. -- @treturn table err If an error occured, a table describing the issue. function DAO:find_all(tbl) if tbl ~= nil then check_arg(tbl, 1, "table") check_not_empty(tbl, 1) local ok, err = schemas_validation.is_schema_subset(tbl, self.schema) if not ok then return nil, Errors.schema(err) end end return self.db:find_all(self.table, tbl, self.schema) end --- Find a paginated set of rows. -- Find a pginated set of rows eventually matching the values in the given fields. -- @param[type=table] tbl (optional) A table containing the fields and values to filter for. -- @param page_offset Offset at which to resume pagination. -- @param page_size Size of the page to retrieve (number of rows). -- @treturn table rows An array of rows. -- @treturn table err If an error occured, a table describing the issue. function DAO:find_page(tbl, page_offset, page_size) if tbl ~= nil then check_arg(tbl, 1, "table") check_not_empty(tbl, 1) local ok, err = schemas_validation.is_schema_subset(tbl, self.schema) if not ok then return nil, Errors.schema(err) end end if page_size == nil then page_size = 100 end check_arg(page_size, 3, "number") return self.db:find_page(self.table, tbl, page_offset, page_size, self.schema) end --- Count the number of rows. -- Count the number of rows matching the given values. -- @param[type=table] tbl (optional) A table containing the fields and values to filter for. -- @treturn number count The total count of rows matching the given filter, or total count of rows if no filter was given. -- @treturn table err If an error occured, a table describing the issue. function DAO:count(tbl) if tbl ~= nil then check_arg(tbl, 1, "table") check_not_empty(tbl, 1) local ok, err = schemas_validation.is_schema_subset(tbl, self.schema) if not ok then return nil, Errors.schema(err) end end if tbl ~= nil and next(tbl) == nil then tbl = nil end return self.db:count(self.table, tbl, self.schema) end local function fix(old, new, schema) for col, field in pairs(schema.fields) do if old[col] ~= nil and new[col] ~= nil and field.schema ~= nil then local f_schema, err if type(field.schema) == "function" then f_schema, err = field.schema(old) if err then error(err) end else f_schema = field.schema end for f_k in pairs(f_schema.fields) do if new[col][f_k] == nil and old[col][f_k] ~= nil then new[col][f_k] = old[col][f_k] end end fix(old[col], new[col], f_schema) end end end --- Update a row. -- Update a row in the related table. Performe a partial update by default (only fields in `tbl` will) -- be updated. If asked, can perform a "full" update, replacing the entire entity (assuming it is valid) -- with the one specified in `tbl` at once. -- @param[type=table] tbl A table containing the new values for this row. -- @param[type=table] filter_keys A table which must contain the primary key(s) to select the row to be updated. -- @param[type=table] options Options to use for this update. (`full`: performs a full update of the entity). -- @treturn table res A table representing the updated entity. -- @treturn table err If an error occured, a table describing the issue. function DAO:update(tbl, filter_keys, options) check_arg(tbl, 1, "table") check_not_empty(tbl, 1) check_arg(filter_keys, 2, "table") check_not_empty(filter_keys, 2) options = options or {} for k, v in pairs(filter_keys) do if tbl[k] == nil then tbl[k] = v end end local model = self.model_mt(tbl) local ok, err = model:validate {dao = self, update = true, full_update = options.full} if not ok then return nil, err end local primary_keys, values, nils, err = model:extract_keys() if err then return nil, Errors.schema(err) end local old, err = self.db:find(self.table, self.schema, primary_keys) if err then return nil, err elseif old == nil then return end if not options.full then fix(old, values, self.schema) end local res, err = self.db:update(self.table, self.schema, self.constraints, primary_keys, values, nils, options.full, model, options) if err then return nil, err elseif res then event(self, event_types.ENTITY_UPDATED, self.table, self.schema, old) return setmetatable(res, nil) end end --- Delete a row. -- Delete a row in table related to this instance. Also deletes all rows with a relashionship to the deleted row -- (via foreign key relations). For SQL databases such as PostgreSQL, the underlying implementation -- leverages "FOREIGN KEY" constraints, but for others such as Cassandra, such operations are executed -- manually. -- @param[type=table] tbl A table containing the primary key field(s) for this row. -- @treturn table row A table representing the deleted row -- @treturn table err If an error occured, a table describing the issue. function DAO:delete(tbl) check_arg(tbl, 1, "table") local model = self.model_mt(tbl) if not model:has_primary_keys() then error("Missing PRIMARY KEY field", 2) end local primary_keys, _, _, err = model:extract_keys() if err then return nil, Errors.schema(err) end -- Find associated entities local associated_entites = {} if self.constraints.cascade ~= nil then for f_entity, cascade in pairs(self.constraints.cascade) do local f_fetch_keys = {[cascade.f_col] = tbl[cascade.col]} local rows, err = self.db:find_all(cascade.table, f_fetch_keys, cascade.schema) if err then return nil, err end associated_entites[cascade.table] = { schema = cascade.schema, entities = rows } end end local row, err = self.db:delete(self.table, self.schema, primary_keys, self.constraints) if not err and row ~= nil then event(self, event_types.ENTITY_DELETED, self.table, self.schema, row) -- Also propagate the deletion for the associated entities for k, v in pairs(associated_entites) do for _, entity in ipairs(v.entities) do event(self, event_types.ENTITY_DELETED, k, v.schema, entity) end end end return row, err end return DAO
apache-2.0
Scavenge/darkstar
scripts/zones/West_Sarutabaruta_[S]/npcs/Sealed_Entrance_1.lua
29
2253
----------------------------------- -- Area: West Sarutabaruta [S] -- NPC: Sealed Entrance (Sealed_Entrance_1) -- @pos -245.000 -18.100 660.000 95 ----------------------------------- package.loaded["scripts/zones/West_Sarutabaruta_[S]/TextIDs"] = nil; ------------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/West_Sarutabaruta_[S]/TextIDs"); ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) local QuestStatus = player:getQuestStatus(CRYSTAL_WAR, SNAKE_ON_THE_PLAINS); local HasPutty = player:hasKeyItem(ZONPAZIPPAS_ALLPURPOSE_PUTTY); local MaskBit1 = player:getMaskBit(player:getVar("SEALED_DOORS"),0) local MaskBit2 = player:getMaskBit(player:getVar("SEALED_DOORS"),1) local MaskBit3 = player:getMaskBit(player:getVar("SEALED_DOORS"),2) if (QuestStatus == QUEST_ACCEPTED and HasPutty) then if (MaskBit1 == false) then if (MaskBit2 == false or MaskBit3 == false) then player:setMaskBit(player:getVar("SEALED_DOORS"),"SEALED_DOORS",0,true); player:messageSpecial(DOOR_OFFSET+1,ZONPAZIPPAS_ALLPURPOSE_PUTTY); else player:setMaskBit(player:getVar("SEALED_DOORS"),"SEALED_DOORS",0,true); player:messageSpecial(DOOR_OFFSET+4,ZONPAZIPPAS_ALLPURPOSE_PUTTY); player:delKeyItem(ZONPAZIPPAS_ALLPURPOSE_PUTTY); end else player:messageSpecial(DOOR_OFFSET+2,ZONPAZIPPAS_ALLPURPOSE_PUTTY); end elseif (player:getQuestStatus(CRYSTAL_WAR,SNAKE_ON_THE_PLAINS) == QUEST_COMPLETED) then player:messageSpecial(DOOR_OFFSET+2, ZONPAZIPPAS_ALLPURPOSE_PUTTY); else player:messageSpecial(DOOR_OFFSET+3); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
PicoleDeLimao/Ninpou2
game/dota_addons/ninpou2/scripts/vscripts/libraries/animations.lua
10
16024
ANIMATIONS_VERSION = "1.00" --[[ Lua-controlled Animations Library by BMD Installation -"require" this file inside your code in order to gain access to the StartAnmiation and EndAnimation global. -Additionally, ensure that this file is placed in the vscripts/libraries path and that the vscripts/libraries/modifiers/modifier_animation.lua, modifier_animation_translate.lua, modifier_animation_translate_permanent.lua, and modifier_animation_freeze.lua files exist and are in the correct path Usage -Animations can be started for any unit and are provided as a table of information to the StartAnimation call -Repeated calls to StartAnimation for a single unit will cancel any running animation and begin the new animation -EndAnimation can be called in order to cancel a running animation -Animations are specified by a table which has as potential parameters: -duration: The duration to play the animation. The animation will be cancelled regardless of how far along it is at the end fo the duration. -activity: An activity code which will be used as the base activity for the animation i.e. DOTA_ACT_RUN, DOTA_ACT_ATTACK, etc. -rate: An optional (will be 1.0 if unspecified) animation rate to be used when playing this animation. -translate: An optional translate activity modifier string which can be used to modify the animation sequence. Example: For ACT_DOTA_RUN+haste, this should be "haste" -translate2: A second optional translate activity modifier string which can be used to modify the animation sequence further. Example: For ACT_DOTA_ATTACK+sven_warcry+sven_shield, this should be "sven_warcry" or "sven_shield" while the translate property is the other translate modifier -A permanent activity translate can be applied to a unit by calling AddAnimationTranslate for that unit. This allows for a permanent "injured" or "aggressive" animation stance. -Permanent activity translate modifiers can be removed with RemoveAnimationTranslate. -Animations can be frozen in place at any time by calling FreezeAnimation(unit[, duration]). Leaving the duration off will cause the animation to be frozen until UnfreezeAnimation is called. -Animations can be unfrozen at any time by calling UnfreezeAnimation(unit) Notes -Animations can only play for valid activities/sequences possessed by the model the unit is using. -Sequences requiring 3+ activity modifier translates (i.e "stun+fear+loadout" or similar) are not possible currently in this library. -Calling EndAnimation and attempting to StartAnimation a new animation for the same unit withing ~2 server frames of the animation end will likely fail to play the new animation. Calling StartAnimation directly without ending the previous animation will automatically add in this delay and cancel the previous animation. -The maximum animation rate which can be used is 12.75, and animation rates can only exist at a 0.05 resolution (i.e. 1.0, 1.05, 1.1 and not 1.06) -StartAnimation and EndAnimation functions can also be accessed through GameRules as GameRules.StartAnimation and GameRules.EndAnimation for use in scoped lua files (triggers, vscript ai, etc) -This library requires that the "libraries/timers.lua" be present in your vscripts directory. Examples: --Start a running animation at 2.5 rate for 2.5 seconds StartAnimation(unit, {duration=2.5, activity=ACT_DOTA_RUN, rate=2.5}) --End a running animation EndAnimation(unit) --Start a running + hasted animation at .8 rate for 5 seconds StartAnimation(unit, {duration=5, activity=ACT_DOTA_RUN, rate=0.8, translate="haste"}) --Start a shield-bash animation for sven with variable rate StartAnimation(unit, {duration=1.5, activity=ACT_DOTA_ATTACK, rate=RandomFloat(.5, 1.5), translate="sven_warcry", translate2="sven_shield"}) --Start a permanent injured translate modifier AddAnimationTranslate(unit, "injured") --Remove a permanent activity translate modifier RemoveAnimationTranslate(unit) --Freeze an animation for 4 seconds FreezeAnimation(unit, 4) --Unfreeze an animation UnfreezeAnimation(unit) ]] LinkLuaModifier( "modifier_animation", "libraries/modifiers/modifier_animation.lua", LUA_MODIFIER_MOTION_NONE ) LinkLuaModifier( "modifier_animation_translate", "libraries/modifiers/modifier_animation_translate.lua", LUA_MODIFIER_MOTION_NONE ) LinkLuaModifier( "modifier_animation_translate_permanent", "libraries/modifiers/modifier_animation_translate_permanent.lua", LUA_MODIFIER_MOTION_NONE ) LinkLuaModifier( "modifier_animation_freeze", "libraries/modifiers/modifier_animation_freeze.lua", LUA_MODIFIER_MOTION_NONE ) require('libraries/timers') local _ANIMATION_TRANSLATE_TO_CODE = { abysm= 13, admirals_prow= 307, agedspirit= 3, aggressive= 4, agrressive= 163, am_blink= 182, ancestors_edge= 144, ancestors_pauldron= 145, ancestors_vambrace= 146, ancestral_scepter= 67, ancient_armor= 6, anvil= 7, arcana= 8, armaments_set= 20, axes= 188, backstab= 41, backstroke_gesture= 283, backward= 335, ball_lightning= 231, batter_up= 43, bazooka= 284, belly_flop= 180, berserkers_blood= 35, black= 44, black_hole= 194, bladebiter= 147, blood_chaser= 134, bolt= 233, bot= 47, brain_sap= 185, broodmother_spin= 50, burning_fiend= 148, burrow= 229, burrowed= 51, cat_dancer_gesture= 285, cauldron= 29, charge= 97, charge_attack= 98, chase= 246, chasm= 57, chemical_rage= 2, chicken_gesture= 258, come_get_it= 39, corpse_dress= 104, corpse_dresstop= 103, corpse_scarf= 105, cryAnimationExportNode= 341, crystal_nova= 193, culling_blade= 184, dagger_twirl= 143, dark_wraith= 174, darkness= 213, dc_sb_charge= 107, dc_sb_charge_attack= 108, dc_sb_charge_finish= 109, dc_sb_ultimate= 110, deadwinter_soul= 96, death_protest= 94, demon_drain= 116, desolation= 55, digger= 176, dismember= 218, divine_sorrow= 117, divine_sorrow_loadout= 118, divine_sorrow_loadout_spawn= 119, divine_sorrow_sunstrike= 120, dizzying_punch= 343, dog_of_duty= 342, dogofduty= 340, dominator= 254, dryad_tree= 311, dualwield= 14, duel_kill= 121, earthshock= 235, emp= 259, enchant_totem= 313, ["end"]= 243, eyeoffetizu= 34, f2p_doom= 131, face_me= 286, faces_hakama= 111, faces_mask= 113, faces_wraps= 112, fast= 10, faster= 11, fastest= 12, fear= 125, fiends_grip= 186, fiery_soul= 149, finger= 200, firefly= 190, fish_slap= 123, fishstick= 339, fissure= 195, flying= 36, focusfire= 124, forcestaff_enemy= 122, forcestaff_friendly= 15, forward= 336, fountain= 49, freezing_field= 191, frost_arrow= 37, frostbite= 192, frostiron_raider= 150, frostivus= 54, ftp_dendi_back= 126, gale= 236, get_burned= 288, giddy_up_gesture= 289, glacier= 101, glory= 345, good_day_sir= 40, great_safari= 267, greevil_black_hole= 58, greevil_blade_fury= 59, greevil_bloodlust= 60, greevil_cold_snap= 61, greevil_decrepify= 62, greevil_diabolic_edict= 63, greevil_echo_slam= 64, greevil_fatal_bonds= 65, greevil_ice_wall= 66, greevil_laguna_blade= 68, greevil_leech_seed= 69, greevil_magic_missile= 70, greevil_maledict= 71, greevil_miniboss_black_brain_sap= 72, greevil_miniboss_black_nightmare= 73, greevil_miniboss_blue_cold_feet= 74, greevil_miniboss_blue_ice_vortex= 75, greevil_miniboss_green_living_armor= 76, greevil_miniboss_green_overgrowth= 77, greevil_miniboss_orange_dragon_slave= 78, greevil_miniboss_orange_lightstrike_array= 79, greevil_miniboss_purple_plague_ward= 80, greevil_miniboss_purple_venomous_gale= 81, greevil_miniboss_red_earthshock= 82, greevil_miniboss_red_overpower= 83, greevil_miniboss_white_purification= 84, greevil_miniboss_yellow_ion_shell= 85, greevil_miniboss_yellow_surge= 86, greevil_natures_attendants= 87, greevil_phantom_strike= 88, greevil_poison_nova= 89, greevil_purification= 90, greevil_shadow_strike= 91, greevil_shadow_wave= 92, groove_gesture= 305, ground_pound= 128, guardian_angel= 215, guitar= 290, hang_loose_gesture= 291, happy_dance= 293, harlequin= 129, haste= 45, hook= 220, horn= 292, immortal= 28, impale= 201, impatient_maiden= 100, impetus= 138, injured= 5, ["injured rare"]= 247, injured_aggressive= 130, instagib= 21, iron= 255, iron_surge= 99, item_style_2= 133, jump_gesture= 294, laguna= 202, leap= 206, level_1= 140, level_2= 141, level_3= 142, life_drain= 219, loadout= 0, loda= 173, lodestar= 114, loser= 295, lsa= 203, lucentyr= 158, lute= 296, lyreleis_breeze= 159, mace= 160, mag_power_gesture= 298, magic_ends_here= 297, mana_drain= 204, mana_void= 183, manias_mask= 135, manta= 38, mask_lord= 299, masquerade= 25, meld= 162, melee= 334, miniboss= 164, moon_griffon= 166, moonfall= 165, moth= 53, nihility= 95, obeisance_of_the_keeper= 151, obsidian_helmet= 132, odachi= 32, offhand_basher= 42, omnislash= 198, overpower1= 167, overpower2= 168, overpower3= 169, overpower4= 170, overpower5= 171, overpower6= 172, pegleg= 248, phantom_attack= 16, pinfold= 175, plague_ward= 237, poison_nova= 238, portrait_fogheart= 177, poundnpoint= 300, powershot= 242, punch= 136, purification= 216, pyre= 26, qop_blink= 221, ravage= 225, red_moon= 30, reincarnate= 115, remnant= 232, repel= 217, requiem= 207, roar= 187, robot_gesture= 301, roshan= 181, salvaged_sword= 152, sandking_rubyspire_burrowstrike= 52, sb_bracers= 251, sb_helmet= 250, sb_shoulder= 252, sb_spear= 253, scream= 222, serene_honor= 153, shadow_strike= 223, shadowraze= 208, shake_moneymaker= 179, sharp_blade= 303, shinobi= 27, shinobi_mask= 154, shinobi_tail= 23, shrapnel= 230, silent_ripper= 178, slam= 196, slasher_chest= 262, slasher_mask= 263, slasher_offhand= 261, slasher_weapon= 260, sm_armor= 264, sm_head= 56, sm_shoulder= 265, snipe= 226, snowangel= 17, snowball= 102, sonic_wave= 224, sparrowhawk_bow= 269, sparrowhawk_cape= 270, sparrowhawk_hood= 272, sparrowhawk_quiver= 271, sparrowhawk_shoulder= 273, spin= 199, split_shot= 1, sprint= 275, sprout= 209, staff_swing= 304, stalker_exo= 93, start= 249, stinger= 280, stolen_charge= 227, stolen_firefly= 189, strike= 228, sugarrush= 276, suicide_squad= 18, summon= 210, sven_shield= 256, sven_warcry= 257, swag_gesture= 287, swordonshoulder= 155, taunt_fullbody= 19, taunt_killtaunt= 139, taunt_quickdraw_gesture= 268, taunt_roll_gesture= 302, techies_arcana= 9, telebolt= 306, teleport= 211, thirst= 137, tidebringer= 24, tidehunter_boat= 22, tidehunter_toss_fish= 312, tidehunter_yippy= 347, timelord_head= 309, tinker_rollermaw= 161, torment= 279, totem= 197, transition= 278, trapper= 314, tree= 310, trickortreat= 277, triumphant_timelord= 127, turbulent_teleport= 308, twinblade_attack= 315, twinblade_attack_b= 316, twinblade_attack_c= 317, twinblade_attack_d= 318, twinblade_attack_injured= 319, twinblade_death= 320, twinblade_idle= 321, twinblade_idle_injured= 322, twinblade_idle_rare= 323, twinblade_injured_attack_b= 324, twinblade_jinada= 325, twinblade_jinada_injured= 326, twinblade_shuriken_toss= 327, twinblade_shuriken_toss_injured= 328, twinblade_spawn= 329, twinblade_stun= 330, twinblade_track= 331, twinblade_track_injured= 332, twinblade_victory= 333, twister= 274, unbroken= 106, vendetta= 337, viper_strike= 239, viridi_set= 338, void= 214, vortex= 234, wall= 240, ward= 241, wardstaff= 344, wave= 205, web= 48, whalehook= 156, whats_that= 281, when_nature_attacks= 31, white= 346, windrun= 244, windy= 245, winterblight= 157, witchdoctor_jig= 282, with_item= 46, wolfhound= 266, wraith_spin= 33, wrath= 212, rampant= 348, overload= 349, surge=350, es_prosperity=351, Espada_pistola=352, overload_injured=353, ss_fortune=354, liquid_fire=355, jakiro_icemelt=356, jakiro_roar=357, chakram=358, doppelwalk=359, enrage=360, fast_run=361, overpower=362, overwhelmingodds=363, pregame=364, shadow_dance=365, shukuchi=366, strength=367, twinblade_run=368, twinblade_run_injured=369, windwalk=370, } function StartAnimation(unit, table) local duration = table.duration local activity = table.activity local translate = table.translate local translate2 = table.translate2 local rate = table.rate or 1.0 rate = math.floor(math.max(0,math.min(255/20, rate)) * 20 + .5) local stacks = activity + bit.lshift(rate,11) if translate ~= nil then if _ANIMATION_TRANSLATE_TO_CODE[translate] == nil then print("[ANIMATIONS.lua] ERROR, no translate-code found for '" .. translate .. "'. This translate may be misspelled or need to be added to the enum manually.") return end stacks = stacks + bit.lshift(_ANIMATION_TRANSLATE_TO_CODE[translate],19) end if translate2 ~= nil and _ANIMATION_TRANSLATE_TO_CODE[translate2] == nil then print("[ANIMATIONS.lua] ERROR, no translate-code found for '" .. translate2 .. "'. This translate may be misspelled or need to be added to the enum manually.") return end if unit:HasModifier("modifier_animation") or (unit._animationEnd ~= nil and unit._animationEnd + .067 > GameRules:GetGameTime()) then EndAnimation(unit) Timers:CreateTimer(.066, function() if translate2 ~= nil then unit:AddNewModifier(unit, nil, "modifier_animation_translate", {duration=duration, translate=translate2}) unit:SetModifierStackCount("modifier_animation_translate", unit, _ANIMATION_TRANSLATE_TO_CODE[translate2]) end unit._animationEnd = GameRules:GetGameTime() + duration unit:AddNewModifier(unit, nil, "modifier_animation", {duration=duration, translate=translate}) unit:SetModifierStackCount("modifier_animation", unit, stacks) end) else if translate2 ~= nil then unit:AddNewModifier(unit, nil, "modifier_animation_translate", {duration=duration, translate=translate2}) unit:SetModifierStackCount("modifier_animation_translate", unit, _ANIMATION_TRANSLATE_TO_CODE[translate2]) end unit._animationEnd = GameRules:GetGameTime() + duration unit:AddNewModifier(unit, nil, "modifier_animation", {duration=duration, translate=translate}) unit:SetModifierStackCount("modifier_animation", unit, stacks) end end function FreezeAnimation(unit, duration) if duration then unit:AddNewModifier(unit, nil, "modifier_animation_freeze", {duration=duration}) else unit:AddNewModifier(unit, nil, "modifier_animation_freeze", {}) end end function UnfreezeAnimation(unit) unit:RemoveModifierByName("modifier_animation_freeze") end function EndAnimation(unit) unit._animationEnd = GameRules:GetGameTime() unit:RemoveModifierByName("modifier_animation") unit:RemoveModifierByName("modifier_animation_translate") end function AddAnimationTranslate(unit, translate) if translate == nil or _ANIMATION_TRANSLATE_TO_CODE[translate] == nil then print("[ANIMATIONS.lua] ERROR, no translate-code found for '" .. translate .. "'. This translate may be misspelled or need to be added to the enum manually.") return end unit:AddNewModifier(unit, nil, "modifier_animation_translate_permanent", {duration=duration, translate=translate}) unit:SetModifierStackCount("modifier_animation_translate_permanent", unit, _ANIMATION_TRANSLATE_TO_CODE[translate]) end function RemoveAnimationTranslate(unit) unit:RemoveModifierByName("modifier_animation_translate_permanent") end GameRules.StartAnimation = StartAnimation GameRules.EndAnimation = EndAnimation GameRules.AddAnimationTranslate = AddAnimationTranslate GameRules.RemoveAnimationTranslate = RemoveAnimationTranslate
apache-2.0
Zero-K-Experiments/Zero-K-Experiments
scripts/screamer.lua
16
1987
include "constants.lua" -------------------------------------------------------------------------------- -- pieces -------------------------------------------------------------------------------- local base, turret, barrel, flare = piece('base', 'turret', 'barrel', 'flare') local smokePiece = {turret, barrel} -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local SIG_Idle = 1 local SIG_Aim = 2 local lastHeading = 0 local function IdleAnim() Signal(SIG_Idle) SetSignalMask(SIG_Idle) while true do Turn(turret, y_axis, lastHeading - math.rad(30), math.rad(60)) Sleep(math.random(3000, 6500)) Turn(turret, y_axis, lastHeading + math.rad(30), math.rad(60)) Sleep(math.random(3000, 6500)) end end function script.Create() while (GetUnitValue(COB.BUILD_PERCENT_LEFT) ~= 0) do Sleep(400) end StartThread(SmokeUnit, smokePiece) StartThread(IdleAnim) end function script.QueryWeapon() return flare end function script.AimFromWeapon() return turret end local function RestoreAfterDelay() Sleep(6000) StartThread(IdleAnim) end function script.AimWeapon(num, heading, pitch) Signal(SIG_Idle) Signal(SIG_Aim) SetSignalMask(SIG_Aim) Turn(turret, y_axis, heading, math.rad(360)) Turn(barrel, x_axis, -pitch, math.rad(90)) WaitForTurn(turret, y_axis) WaitForTurn(barrel, x_axis) lastHeading = heading StartThread(RestoreAfterDelay) return true end function script.BlockShot(num, targetID) return GG.OverkillPrevention_CheckBlock(unitID, targetID, 1600.1, 50) end function script.Killed(recentDamage, maxHealth) local severity = recentDamage / maxHealth if (severity <= .5) then Explode(base, sfxNone) Explode(turret, sfxNone) Explode(barrel, sfxNone) return 1 -- corpsetype else Explode(base, sfxShatter) Explode(turret, sfxSmoke + sfxFire) Explode(barrel, sfxSmoke + sfxFire + sfxExplode) return 2 -- corpsetype end end
gpl-2.0
Scavenge/darkstar
scripts/globals/abilities/choral_roll.lua
19
2717
----------------------------------- -- Ability: Choral Roll -- Decreases spell interruption rate for party members within area of effect -- Optimal Job: Bard -- Lucky Number: 2 -- Unlucky Number: 6 -- Level: 26 -- -- Die Roll |No BRD |With BRD -- -------- -------- ------- -- 1 |-13 |-38 -- 2 |-55 |-80 -- 3 |-17 |-42 -- 4 |-20 |-45 -- 5 |-25 |-50 -- 6 |-8 |-33 -- 7 |-30 |-55 -- 8 |-35 |-60 -- 9 |-40 |-65 -- 10 |-45 |-70 -- 11 |-65 |-90 -- Bust |+25 |+25 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/ability"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) local effectID = EFFECT_CHORAL_ROLL ability:setRange(ability:getRange() + player:getMod(MOD_ROLL_RANGE)); if (player:hasStatusEffect(effectID)) then return MSGBASIC_ROLL_ALREADY_ACTIVE,0; elseif atMaxCorsairBusts(player) then return MSGBASIC_CANNOT_PERFORM,0; else return 0,0; end end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(caster,target,ability,action) if (caster:getID() == target:getID()) then corsairSetup(caster, ability, action, EFFECT_CHORAL_ROLL, JOBS.BRD); end local total = caster:getLocalVar("corsairRollTotal") return applyRoll(caster,target,ability,action,total) end; function applyRoll(caster,target,ability,action,total) local duration = 300 + caster:getMerit(MERIT_WINNING_STREAK) local effectpowers = {13, 55, 17, 20, 25, 8, 30, 35, 40, 45, 65, 25} local effectpower = effectpowers[total]; if (caster:getLocalVar("corsairRollBonus") == 1 and total < 12) then effectpower = effectpower + 25 end if (caster:getMainJob() == JOBS.COR and caster:getMainLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl()); elseif (caster:getSubJob() == JOBS.COR and caster:getSubLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl()); end if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(MERIT_BUST_DURATION), EFFECT_CHORAL_ROLL, effectpower, 0, duration, caster:getID(), total, MOD_SPELLINTERRUPT) == false) then ability:setMsg(422); elseif total > 11 then ability:setMsg(426); end return total; end
gpl-3.0
Arashbrsh/lifemaic
plugins/Fake.lua
45
6690
local function kick_user(user_id, chat_id) local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end local function ban_user(user_id, chat_id) -- Save to redis local hash = 'banned:'..chat_id..':'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function banall_user(user_id) local data = load_data(_config.moderation.data) local groups = 'groups' for k,v in pairs(data[tostring(groups)]) do chat_id = v ban_user(user_id, chat_id) end for k,v in pairs(_config.realm) do chat_id = v ban_user(user_id, chat_id) end end local function unbanall_user(user_id) local data = load_data(_config.moderation.data) local groups = 'groups' for k,v in pairs(data[tostring(groups)]) do chat_id = v local hash = 'banned:'..chat_id..':'..user_id redis:del(hash) end for k,v in pairs(_config.realm) do chat_id = v local hash = 'banned:'..chat_id..':'..user_id redis:del(hash) end end local function is_banned(user_id, chat_id) local hash = 'banned:'..chat_id..':'..user_id local banned = redis:get(hash) return banned or false end local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat if action == 'chat_add_user' or action == 'chat_add_user_link' then local user_id if msg.action.link_issuer then user_id = msg.from.id else user_id = msg.action.user.id end print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned then print('User is banned!') kick_user(user_id, msg.to.id) end end -- No further checks return msg end -- BANNED USER TALKING if msg.to.type == 'chat' then local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned then print('Banned user talking!') ban_user(user_id, chat_id) msg.text = '' end end return msg end local function username_id(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local chat_id = cb_extra.chat_id local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if member_id == our_id then return false end if get_cmd == 'kick' then return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id..':'..member_id redis:del(hash) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') return unbanall_user(member_id, chat_id) end end end return send_large_msg(receiver, text) end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == 'kickme' then if msg.to.type == 'chat' then kick_user(msg.from.id, msg.to.id) end end if not is_momod(msg) then if not is_sudo(msg) then return nil end end if matches[1] == 'ban' then local chat_id = msg.to.id if msg.to.type == 'chat' then if string.match(matches[2], '^%d+$') then if matches[2] == our_id then return false end local user_id = matches[2] ban_user(user_id, chat_id) else local member = string.gsub(matches[2], '@', '') local get_cmd = 'ban' chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end return 'User '..user_id..' banned' end end if matches[1] == 'unban' then local chat_id = msg.to.id if msg.to.type == 'chat' then if string.match(matches[2], '^%d+$') then local user_id = matches[2] local hash = 'banned:'..chat_id..':'..user_id redis:del(hash) return 'User '..user_id..' unbanned' else local member = string.gsub(matches[2], '@', '') local get_cmd = 'unban' chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end end if matches[1] == 'kick' then if msg.to.type == 'chat' then if string.match(matches[2], '^%d+$') then if matches[2] == our_id then return false end kick_user(matches[2], msg.to.id) else local member = string.gsub(matches[2], '@', '') local get_cmd = 'kick' chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end else return 'This isn\'t a chat group' end end if not is_admin(msg) then return end if matches[1] == 'banall' then local user_id = matches[2] local chat_id = msg.to.id if msg.to.type == 'chat' then if string.match(matches[2], '^%d+$') then if matches[2] == our_id then return false end banall_user(user_id) return 'User '..user_id..' banned' else local member = string.gsub(matches[2], '@', '') local get_cmd = 'banall' chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end end if matches[1] == 'unbanall' then local user_id = matches[2] local chat_id = msg.to.id if msg.to.type == 'chat' then if string.match(matches[2], '^%d+$') then if matches[2] == our_id then return false end unbanall_user(user_id) return 'User '..user_id..' unbanned' else local member = string.gsub(matches[2], '@', '') local get_cmd = 'unbanall' chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end end end return { description = "Plugin to manage bans and kicks.", patterns = { "^!(kick) (.*)$", "^/(banall) (.*)$", "^!(ban) (.*)$", "^/(ban) (.*)$", "^!(unban) (.*)$", "^/(unban) (.*)$", "^/(unbanall) (.*)$", "^!(kick) (.*)$", "^/(kick) (.*)$", "^/(kickme)$", "^!(kickme)$", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process }
gpl-2.0
Zero-K-Experiments/Zero-K-Experiments
LuaUI/Widgets/chili_new/controls/progressbar.lua
10
3388
--//============================================================================= --- Progressbar module --- Progressbar fields. -- Inherits from Control. -- @see control.Control -- @table Progressbar -- @int[opt=0] min minimum value of the Progressbar -- @int[opt=100] max maximum value of the Progressbar -- @int[opt=100] value value of the Progressbar -- @string[opt=""] caption text to be displayed -- @tparam {r,g,b,a} color specifies the color of the bar (default: {0,0,1,1}) -- @tparam {r,g,b,a} backgroundColor specifies the background color (default: {1,1,1,1}) -- @tparam {func1,fun2,...} OnChange function listeners for value change (default {}) Progressbar = Control:Inherit{ classname = "progressbar", defaultWidth = 90, defaultHeight = 20, min = 0, max = 100, value = 100, caption = "", color = {0,0,1,1}, backgroundColor = {1,1,1,1}, OnChange = {}, } local this = Progressbar local inherited = this.inherited --//============================================================================= function Progressbar:New(obj) obj = inherited.New(self,obj) obj:SetMinMax(obj.min,obj.max) obj:SetValue(obj.value) return obj end --//============================================================================= function Progressbar:_Clamp(v) if (self.min<self.max) then if (v<self.min) then v = self.min elseif (v>self.max) then v = self.max end else if (v>self.min) then v = self.min elseif (v<self.max) then v = self.max end end return v end --//============================================================================= --- Sets the new color -- @tparam {r,g,b,a} c color table function Progressbar:SetColor(...) local color = _ParseColorArgs(...) table.merge(color,self.color) if (not table.iequal(color,self.color)) then self.color = color self:Invalidate() end end --- Sets the minimum and maximum value of the progress bar -- @int[opt=0] min minimum value -- @int[opt=1] max maximum value (why is 1 the default?) function Progressbar:SetMinMax(min,max) self.min = tonumber(min) or 0 self.max = tonumber(max) or 1 self:SetValue(self.value) end --- Sets the value of the progress bar -- @int v value of the progress abr -- @bool[opt=false] setcaption whether the caption should be set as well function Progressbar:SetValue(v,setcaption) v = self:_Clamp(v) local oldvalue = self.value if (v ~= oldvalue) then self.value = v if (setcaption) then self:SetCaption(v) end self:CallListeners(self.OnChange,v,oldvalue) self:Invalidate() end end --- Sets the caption -- @string str caption to be set function Progressbar:SetCaption(str) if (self.caption ~= str) then self.caption = str self:Invalidate() end end --//============================================================================= function Progressbar:DrawControl() local percent = (self.value-self.min)/(self.max-self.min) local x = self.x local y = self.y local w = self.width local h = self.height gl.Color(self.backgroundColor) gl.Rect(w*percent,y,w,h) gl.Color(self.color) gl.Rect(0,y,w*percent,h) if (self.caption) then (self.font):Print(self.caption, w*0.5, h*0.5, "center", "center") end end --//=============================================================================
gpl-2.0
Scavenge/darkstar
scripts/zones/Sauromugue_Champaign/npcs/qm3.lua
14
2473
----------------------------------- -- Area: Sauromugue Champaign -- NPC: qm3 (???) (Tower 3) -- Involved in Quest: THF AF "As Thick As Thieves" -- @pos 417.121 15.598 -137.466 120 ----------------------------------- package.loaded["scripts/zones/Sauromugue_Champaign/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/Sauromugue_Champaign/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local thickAsThievesGrapplingCS = player:getVar("thickAsThievesGrapplingCS"); if (thickAsThievesGrapplingCS >= 2 and thickAsThievesGrapplingCS <= 7) then if (trade:hasItemQty(17474,1) and trade:getItemCount() == 1) then -- Trade grapel player:messageSpecial(THF_AF_WALL_OFFSET+3,0,17474); -- You cannot get a decent grip on the wall using the [Grapnel]. end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local thickAsThieves = player:getQuestStatus(WINDURST,AS_THICK_AS_THIEVES); local thickAsThievesGrapplingCS = player:getVar("thickAsThievesGrapplingCS"); if (thickAsThieves == QUEST_ACCEPTED) then if (thickAsThievesGrapplingCS == 3) then player:messageSpecial(THF_AF_MOB); GetMobByID(17269107):setSpawn(414,16,-131); SpawnMob(17269107):updateClaim(player); -- Climbpix Highrise elseif (thickAsThievesGrapplingCS == 0 or thickAsThievesGrapplingCS == 1 or thickAsThievesGrapplingCS == 2 or thickAsThievesGrapplingCS == 4 or thickAsThievesGrapplingCS == 5 or thickAsThievesGrapplingCS == 6 or thickAsThievesGrapplingCS == 7) then player:messageSpecial(THF_AF_WALL_OFFSET); end else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Crystalwarrior/ZombieDefence
zombie.lua
1
3689
function init_zombie_director() local z = {} z.timer = 10 z.wave = 0 z.wave_period = 30 --A single wave lasts 30 seconds z.grace_period = 15 --Time until next wave z.zombie_per_second = 2 --Spawn a zombie every second z.spawn_timer = 0 --timer itself z.state = 0 --What state of director are we in? 0 = Grace Period, 1 = Active Wave -- z.types = { -- { -- name = 'slow' -- basehealth = 10 -- basespeed = 50 -- attack = 5 -- attackspeed = 1 -- color = {0, 125, 0, 255} -- scale = 16 -- wave = 0 -- spawnchance = 1 -- } -- { -- name = 'fast' -- basehealth = 3 -- basespeed = 125 -- attack = 2 -- attackspeed = 0.3 -- color = {125, 125, 0, 255} -- scale = 14 -- wave = 4 -- spawnchance = 0.2 -- } -- } return z end function create_zombie(zombie_director, type, x, y) local z = HC.circle(x, y, type.scale) z.health = type.basehealth z.speed = type.basespeed z.color = type.color z.type = type z.targ_x = x z.targ_y = y table.insert(zombie_director, z) return z end function process_zombies(zombie_director, dt) zombie_director.timer = zombie_director.timer - dt if zombie_director.timer <= 0 then if zombie_director.state == 0 then zombie_director.wave = zombie_director.wave + 1 --Increase wave zombie_director.zombie_per_second = math.max(zombie_director.zombie_per_second * 0.8, 0.3) --Make it harder zombie_director.state = 1 zombie_director.timer = zombie_director.wave_period elseif zombie_director.state == 1 then zombie_director.state = 0 zombie_director.spawn_timer = 0 zombie_director.timer = zombie_director.grace_period end end if zombie_director.state == 1 then zombie_director.spawn_timer = zombie_director.spawn_timer + dt if zombie_director.spawn_timer > zombie_director.zombie_per_second then zombie_director.spawn_timer = 0 local player = get_player() if player ~= nil then local player_x,player_y = player:center() local angle = math.pi * 2 * love.math.random() local x = player_x + 300 * math.cos(angle) local y = player_y + 300 * math.sin(angle) local wave = zombie_director.wave local hp = 5 * math.clamp(wave/5, 1, 10) local speed = 50 * math.clamp(wave/5, 1, 10) create_zombie(zombie_director, {scale = 16, basespeed = speed, basehealth = hp, color = {0, 125, 0, 255}}, x, y) end end end --Zombie AI for i,z in ipairs(zombie_director) do local player = get_player() if player ~= nil then local player_x,player_y = player:center() z.targ_x = player_x z.targ_y = player_y end local x,y = z:center() local dx = z.targ_x - x local dy = z.targ_y - y local dm = math.sqrt(dx * dx + dy * dy) if dm == 0 then dm = 1 end local mx = dt * z.speed * dx / dm local my = dt * z.speed * dy / dm if dx < 0 and mx < dx then mx = dx end if dx > 0 and mx > dx then mx = dx end if dy < 0 and my < dy then my = dy end if dy > 0 and my > dy then my = dy end z:move(mx, my) end end function zombie_hurt(z, zombie_director, i, dmg) z.health = z.health - dmg if z.health <= 0 then zombie_death(z, zombie_director, i) end end function zombie_death(z, zombie_director, i) local add = math.round(5 * (z.type.basehealth/5)) local player = get_player() if player ~= nil then player.money = player.money + add end zombie_remove(z, zombie_director, i) end function zombie_remove(z, zombie_director, i) HC.remove(z) table.remove(zombie_director, i) end function draw_zombies(zombie_director) for i,z in ipairs(zombie_director) do draw_zombie(z) end end function draw_zombie(z) love.graphics.setColor(z.color[1], z.color[2], z.color[3], z.color[4]) z:draw('line') end
unlicense
Scavenge/darkstar
scripts/globals/items/weavers_belt.lua
12
1185
----------------------------------------- -- ID: 15447 -- Item: Weaver's Belt -- Enchantment: Synthesis image support -- 2Min, All Races ----------------------------------------- -- Enchantment: Synthesis image support -- Duration: 2Min -- Clothcraft Skill +3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_CLOTHCRAFT_IMAGERY) == true) then result = 239; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_CLOTHCRAFT_IMAGERY,3,0,120); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_SKILL_CLT, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_SKILL_CLT, 1); end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Yuhtunga_Jungle/npcs/Cermet_Headstone.lua
11
4417
----------------------------------- -- Area: Yuhtunga Jungle -- NPC: Cermet Headstone -- Involved in Mission: ZM5 Headstone Pilgrimage (Fire Fragment) -- @pos 491 20 301 123 ----------------------------------- package.loaded["scripts/zones/Yuhtunga_Jungle/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Yuhtunga_Jungle/TextIDs"); require("scripts/globals/missions"); require("scripts/globals/keyitems"); require("scripts/globals/titles"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(790,1) and trade:getItemCount() == 1) then if (player:getCurrentMission(ZILART) == HEADSTONE_PILGRIMAGE and player:hasKeyItem(FIRE_FRAGMENT) and player:hasCompleteQuest(OUTLANDS,WRATH_OF_THE_OPO_OPOS) == false) then player:addQuest(OUTLANDS,WRATH_OF_THE_OPO_OPOS); player:startEvent(202,790); elseif (player:hasCompletedMission(ZILART,HEADSTONE_PILGRIMAGE) and player:hasCompleteQuest(OUTLANDS,WRATH_OF_THE_OPO_OPOS) == false) then player:addQuest(OUTLANDS,WRATH_OF_THE_OPO_OPOS); player:startEvent(202,790); else player:messageSpecial(NOTHING_HAPPENS); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- printf("zilart: %i",player:getCurrentMission(ZILART)); if (player:getCurrentMission(ZILART) == HEADSTONE_PILGRIMAGE) then -- if requirements are met and 15 mins have passed since mobs were last defeated, spawn them if (player:hasKeyItem(FIRE_FRAGMENT) == false and GetServerVariable("[ZM4]Fire_Headstone_Active") < os.time()) then -- Don't try to pop Carthi and Tipha if already up. if (GetMobAction(17281030) == ACTION_NONE and GetMobAction(17281031) == ACTION_NONE) then player:startEvent(200,FIRE_FRAGMENT); else player:messageSpecial(CANNOT_REMOVE_FRAG); end -- if 15 min window is open and requirements are met, receive key item elseif (player:hasKeyItem(FIRE_FRAGMENT) == false and GetServerVariable("[ZM4]Fire_Headstone_Active") > os.time()) then player:addKeyItem(FIRE_FRAGMENT); -- Check and see if all fragments have been found (no need to check fire and dark frag) if (player:hasKeyItem(ICE_FRAGMENT) and player:hasKeyItem(EARTH_FRAGMENT) and player:hasKeyItem(WATER_FRAGMENT) and player:hasKeyItem(WIND_FRAGMENT) and player:hasKeyItem(LIGHTNING_FRAGMENT) and player:hasKeyItem(LIGHT_FRAGMENT)) then player:messageSpecial(FOUND_ALL_FRAGS,FIRE_FRAGMENT); player:addTitle(BEARER_OF_THE_EIGHT_PRAYERS); player:completeMission(ZILART,HEADSTONE_PILGRIMAGE); player:addMission(ZILART,THROUGH_THE_QUICKSAND_CAVES); else player:messageSpecial(KEYITEM_OBTAINED,FIRE_FRAGMENT); end else player:messageSpecial(ALREADY_OBTAINED_FRAG,FIRE_FRAGMENT); end elseif (player:hasCompletedMission(ZILART,HEADSTONE_PILGRIMAGE)) then player:messageSpecial(ZILART_MONUMENT); else player:messageSpecial(CANNOT_REMOVE_FRAG); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 200 and option == 1) then SpawnMob(17281031):updateClaim(player); -- Carthi SpawnMob(17281030):updateClaim(player); -- Tipha SetServerVariable("[ZM4]Fire_Headstone_Active",0); elseif (csid == 202) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13143); else player:tradeComplete(); player:addItem(13143); player:completeQuest(OUTLANDS,WRATH_OF_THE_OPO_OPOS); player:addTitle(FRIEND_OF_THE_OPOOPOS); player:messageSpecial(ITEM_OBTAINED,13143); end end end;
gpl-3.0
tempbottle/tundra
scripts/tundra/tools/generic-asm.lua
28
2495
module(..., package.seeall) local path = require "tundra.path" local util = require "tundra.util" local boot = require "tundra.boot" local scanner = require "tundra.scanner" local depgraph = require "tundra.depgraph" local default_keywords = { "include" } local default_bin_keywords = { "incbin" } local function get_asm_scanner(env, fn) local function test_bool(name, default) val = env:get(name, default) if val == "yes" or val == "true" or val == "1" then return 1 else return 0 end end local function new_scanner() local paths = util.map(env:get_list("ASMINCPATH"), function (v) return env:interpolate(v) end) local data = { Paths = paths, Keywords = env:get_list("ASMINC_KEYWORDS", default_keywords), KeywordsNoFollow = env:get_list("ASMINC_BINARY_KEYWORDS", default_bin_keywords), RequireWhitespace = test_bool("ASMINC_REQUIRE_WHITESPACE", "yes"), UseSeparators = test_bool("ASMINC_USE_SEPARATORS", "yes"), BareMeansSystem = test_bool("ASMINC_BARE_MEANS_SYSTEM", "no"), } return scanner.make_generic_scanner(data) end return env:memoize("ASMINCPATH", "_asm_scanner", new_scanner) end -- Register implicit make functions for assembly files. -- These functions are called to transform source files in unit lists into -- object files. This function is registered as a setup function so it will be -- run after user modifications to the environment, but before nodes are -- processed. This way users can override the extension lists. local function generic_asm_setup(env) local _assemble = function(env, pass, fn) local object_fn = path.make_object_filename(env, fn, '$(OBJECTSUFFIX)') return depgraph.make_node { Env = env, Label = 'Asm $(@)', Pass = pass, Action = "$(ASMCOM)", InputFiles = { fn }, OutputFiles = { object_fn }, Scanner = get_asm_scanner(env, fn), } end for _, ext in ipairs(env:get_list("ASM_EXTS")) do env:register_implicit_make_fn(ext, _assemble) end end function apply(_outer_env, options) _outer_env:add_setup_function(generic_asm_setup) _outer_env:set_many { ["ASM_EXTS"] = { ".s", ".asm" }, ["ASMINCPATH"] = {}, ["ASMDEFS"] = "", ["ASMDEFS_DEBUG"] = "", ["ASMDEFS_PRODUCTION"] = "", ["ASMDEFS_RELEASE"] = "", ["ASMOPTS"] = "", ["ASMOPTS_DEBUG"] = "", ["ASMOPTS_PRODUCTION"] = "", ["ASMOPTS_RELEASE"] = "", } end
gpl-3.0
Scavenge/darkstar
scripts/zones/The_Shrouded_Maw/bcnms/darkness_named.lua
30
2857
----------------------------------- -- Area: The_Shrouded_Maw -- Name: darkness_named ----------------------------------- package.loaded["scripts/zones/The_Shrouded_Maw/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/zones/The_Shrouded_Maw/TextIDs"); require("scripts/globals/missions"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) local inst = player:getBattlefieldID(); if (inst == 1) then local TileOffset = 16818258; for i = TileOffset, TileOffset+7 do local TileOffsetA = GetNPCByID(i):getAnimation(); if (TileOffsetA == 8) then GetNPCByID(i):setAnimation(9); end end elseif (inst == 2) then local TileOffset = 16818266; for i = TileOffset, TileOffset+7 do local TileOffsetA = GetNPCByID(i):getAnimation(); if (TileOffsetA == 8) then GetNPCByID(i):setAnimation(9); end end elseif (inst == 3) then local TileOffset = 16818274; for i = TileOffset, TileOffset+7 do local TileOffsetA = GetNPCByID(i):getAnimation(); if (TileOffsetA == 8) then GetNPCByID(i):setAnimation(9); end end end end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage player:addExp(1000); if (player:getCurrentMission(COP) == DARKNESS_NAMED and player:getVar("PromathiaStatus") == 2) then player:addTitle(TRANSIENT_DREAMER); player:setVar("PromathiaStatus",3); player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0); end elseif (leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); end;
gpl-3.0
flux-framework/flux-core
src/shell/lua.d/mvapich.lua
3
1511
------------------------------------------------------------- -- Copyright 2020 Lawrence Livermore National Security, LLC -- (c.f. AUTHORS, NOTICE.LLNS, COPYING) -- -- This file is part of the Flux resource manager framework. -- For details, see https://github.com/flux-framework. -- -- SPDX-License-Identifier: LGPL-3.0 ------------------------------------------------------------- if shell.options.mpi == "none" then return end local f, err = require 'flux'.new () if not f then error (err) end -- Lua implementation of dirname(3) to avoid pulling in posix module local function dirname (d) if not d:match ("/") then return "." end return d:match ("^(.*[^/])/.-$") end local function setenv_prepend (var, val) local path = shell.getenv (var) -- If path not already set, then set it to val if not path then shell.setenv (var, val) -- O/w, if val is not already set in path, prepend it elseif path:match ("^[^:]+") ~= val then shell.setenv (var, val .. ':' .. path) end -- O/w, val already first in path. Do nothing end local libpmi = f:getattr ('conf.pmi_library_path') setenv_prepend ("LD_LIBRARY_PATH", dirname (libpmi)) shell.setenv ("MPIRUN_NTASKS", shell.info.ntasks) shell.setenv ("MPIRUN_RSH_LAUNCH", 1) plugin.register { name = "mvapich", handlers = { { topic = "task.init", fn = function () local rank = task.info.rank task.setenv ("MPIRUN_RANK", rank) end } } }
lgpl-3.0
Scavenge/darkstar
scripts/zones/Uleguerand_Range/npcs/HomePoint#4.lua
27
1258
----------------------------------- -- Area: Uleguerand_Range -- NPC: HomePoint#4 -- @pos ----------------------------------- package.loaded["scripts/zones/Uleguerand_Range/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Uleguerand_Range/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21ff, 79); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x21ff) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
Zero-K-Experiments/Zero-K-Experiments
effects/cegtags.lua
12
5801
-- heatray_scorcher -- redlaser_ak -- yellowlaser_hlt -- yellowlaser_can -- orangelaser -- stormtag -- redlaser_llt -- samtag -- slashtag return { ["heatray_scorcher"] = { greenlaser = { air = true, class = [[CSimpleGroundFlash]], count = 1, ground = true, water = true, properties = { colormap = [[0.6 0.2 0.41 0.05 0 0 0 0.01]], size = 160, sizegrowth = 0, texture = [[groundflash]], ttl = 10, }, }, }, ["redlaser_ak"] = { redlaser_light = { air = true, class = [[CSimpleGroundFlash]], count = 1, ground = true, water = true, properties = { colormap = [[1 0 0 0.05 0 0 0 0.01]], size = 80, sizegrowth = 0, texture = [[groundflash]], ttl = 5, }, }, }, ["yellowlaser_hlt"] = { yellowlaser = { air = true, class = [[CSimpleGroundFlash]], count = 1, ground = true, water = true, properties = { colormap = [[1 1 0 0.03 0 0 0 0.01]], size = 320, sizegrowth = 0, texture = [[groundflash]], ttl = 10, }, }, }, ["yellowlaser_can"] = { yellowlaser = { air = true, class = [[CSimpleGroundFlash]], count = 1, ground = true, water = true, properties = { colormap = [[1 1 0 0.05 0 0 0 0.01]], size = 160, sizegrowth = 0, texture = [[groundflash]], ttl = 10, }, }, }, ["orangelaser"] = { orangelaser = { air = true, class = [[CSimpleGroundFlash]], count = 1, ground = true, water = true, properties = { colormap = [[1 0.5 0 0.05 0 0 0 0.01]], size = 120, sizegrowth = 0, texture = [[groundflash]], ttl = 10, }, }, }, ["stormtag"] = { fluffy = { air = true, class = [[CSimpleParticleSystem]], count = 2, ground = true, water = true, properties = { airdrag = 0.9, colormap = [[1 1 1 1 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 7, emitvector = [[dir]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 60, particlelifespread = 0, particlesize = [[2.5 i-0.2]], particlesizespread = 0, particlespeed = [[1 i0.10]], particlespeedspread = 0.5, pos = [[0, 0, 0]], sizegrowth = 0.2, sizemod = 1.0, texture = [[smokesmall]], }, }, }, ["redlaser_llt"] = { redlaser = { air = true, class = [[CSimpleGroundFlash]], count = 1, ground = true, water = true, properties = { colormap = [[1 0 0 0.03 0 0 0 0.01]], size = 160, sizegrowth = 0, texture = [[groundflash]], ttl = 10, }, }, }, ["samtag"] = { fluffy = { air = true, class = [[CSimpleParticleSystem]], count = 10, ground = true, water = true, properties = { airdrag = 0.9, colormap = [[1 1 1 1 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 7, emitvector = [[dir]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 60, particlelifespread = 0, particlesize = [[5 i-0.45]], particlesizespread = 0, particlespeed = [[1 i0.72]], particlespeedspread = 0.5, pos = [[0, 0, 0]], sizegrowth = 0.2, sizemod = 1.0, texture = [[smokesmall]], }, }, }, ["slashtag"] = { fluffy = { air = true, class = [[CSimpleParticleSystem]], count = 10, ground = true, water = true, properties = { airdrag = 0.6, colormap = [[1 1 1 1 1 1 1 1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 3, emitvector = [[dir]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 30, particlelifespread = 0, particlesize = [[5 i-0.45]], particlesizespread = 0, particlespeed = [[-8 i4]], particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0.2, sizemod = 1.0, texture = [[smokesmall]], }, }, }, }
gpl-2.0
Zero-K-Experiments/Zero-K-Experiments
LuaRules/Gadgets/lups_nano_spray.lua
7
12924
-- $Id: lups_nano_spray.lua 3171 2008-11-06 09:06:29Z det $ ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "LupsNanoSpray", desc = "Wraps the nano spray to LUPS", author = "jK", date = "2008-2012", license = "GNU GPL, v2 or later", layer = 0, enabled = true } end local spGetFactoryCommands = Spring.GetFactoryCommands local spGetCommandQueue = Spring.GetCommandQueue local function GetCmdTag(unitID) local cmdTag = 0 local cmds = spGetFactoryCommands(unitID,1) if (cmds) then local cmd = cmds[1] if cmd then cmdTag = cmd.tag end end if cmdTag == 0 then local cmds = spGetCommandQueue(unitID,1) if (cmds) then local cmd = cmds[1] if cmd then cmdTag = cmd.tag end end end return cmdTag end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- if (gadgetHandler:IsSyncedCode()) then ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- --// bw-compability local alreadyWarned = 0 local function WarnDeprecated() if (alreadyWarned<10) then alreadyWarned = alreadyWarned + 1 Spring.Log("LUPS", LOG.WARNING, "LUS/COB: QueryNanoPiece is deprecated! Use Spring.SetUnitNanoPieces() instead!") end end function gadget:Initialize() GG.LUPS = GG.LUPS or {} GG.LUPS.QueryNanoPiece = WarnDeprecated gadgetHandler:RegisterGlobal("QueryNanoPiece", WarnDeprecated) end function gadget:Shutdown() gadgetHandler:DeregisterGlobal("QueryNanoPiece") end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- else ------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------- local Lups --// Lua Particle System local initialized = false --// if LUPS isn't started yet, we try it once a gameframe later local tryloading = 1 --// try to activate lups if it isn't found ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- --// Speed-ups local GetUnitRadius = Spring.GetUnitRadius local GetFeatureRadius = Spring.GetFeatureRadius local spGetFeatureDefID = Spring.GetFeatureDefID local spGetTeamColor = Spring.GetTeamColor local spGetGameFrame = Spring.GetGameFrame local type = type local pairs = pairs ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- if (not GetFeatureRadius) then GetFeatureRadius = function(featureID) local fDefID = spGetFeatureDefID(featureID) return (FeatureDefs[fDefID].radius or 0) end end local function SetTable(table,arg1,arg2,arg3,arg4) table[1] = arg1 table[2] = arg2 table[3] = arg3 table[4] = arg4 end local function CopyTable(outtable,intable) for i,v in pairs(intable) do if (type(v)=='table') then if (type(outtable[i])~='table') then outtable[i] = {} end CopyTable(outtable[i],v) else outtable[i] = v end end end local function CopyMergeTables(table1,table2) local ret = {} CopyTable(ret,table2) CopyTable(ret,table1) return ret end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- «« some basic functions »» -- local supportedFxs = {} local function fxSupported(fxclass) if (supportedFxs[fxclass]~=nil) then return supportedFxs[fxclass] else supportedFxs[fxclass] = Lups.HasParticleClass(fxclass) return supportedFxs[fxclass] end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- Lua StrFunc parsing and execution -- local loadstring = loadstring local pcall = pcall local function ParseLuaStrFunc(strfunc) local luaCode = [[ return function(count,inversed) local limcount = (count/6) limcount = limcount/(limcount+1) return ]] .. strfunc .. [[ end ]] local luaFunc = loadstring(luaCode) local success,ret = pcall(luaFunc) if (success) then return ret else Spring.Echo("LUPS(NanoSpray): parsing error in user function: \n" .. ret) return function() return 0 end end end local function ParseLuaCode(t) for i,v in pairs(t) do if (type(v)=="string")and(i~="texture")and(i~="fxtype") then t[i] = ParseLuaStrFunc(v) end end end local function ExecuteLuaCode(t) for i,v in pairs(t) do if (type(v)=="function") then t[i]=v(t.count,t.inversed) end end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- «« NanoSpray handling »» -- local nanoParticles = {} local maxEngineParticles = Spring.GetConfigInt("MaxNanoParticles", 10000) local function GetFaction(udid) --local udef_factions = UnitDefs[udid].factions or {} --return ((#udef_factions~=1) and 'unknown') or udef_factions[1] return "default" -- default end local factionsNanoFx = { default = { fxtype = "NanoLasers", alpha = "0.2+count/30", corealpha = "0.2+count/120", corethickness = "limcount", streamThickness = "0.5+5*limcount", streamSpeed = "limcount*0.05", }, ["default_high_quality"] = { fxtype = "NanoParticles", alpha = 0.27, size = 6, sizeSpread = 6, sizeGrowth = 0.65, rotSpeed = 0.1, rotSpread = 360, texture = "bitmaps/Other/Poof.png", particles = 1.2, }, --[[arm = { fxtype = "NanoParticles", delaySpread = 30, size = 3, sizeSpread = 5, sizeGrowth = 0.25, texture = "bitmaps/PD/nano.png" }, ["arm_high_quality"] = { fxtype = "NanoParticles", alpha = 0.27, size = 6, sizeSpread = 6, sizeGrowth = 0.65, rotSpeed = 0.1, rotSpread = 360, texture = "bitmaps/Other/Poof.png", particles = 1.2, }, core = { fxtype = "NanoLasers", alpha = "0.2+count/30", corealpha = "0.2+count/120", corethickness = "limcount", streamThickness = "0.5+5*limcount", streamSpeed = "limcount*0.05", }, unknown = { fxtype = "NanoLasers", alpha = "0.2+count/30", corealpha = "0.2+count/120", corethickness = "limcount", streamThickness = "0.5+5*limcount", streamSpeed = "limcount*0.05", },]]-- } ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- local builders = {} local function BuilderFinished(unitID) builders[#builders+1] = unitID end local function BuilderDestroyed(unitID) for i=1,#builders do if (builders[i] == unitID) then builders[i] = builders[#builders] end end builders[#builders] = nil end function gadget:GameFrame(frame) for i=1,#builders do local unitID = builders[i] if ((unitID + frame) % 30 < 1) then --// only update once per second local strength = (Spring.GetUnitCurrentBuildPower(unitID) or 0)*(Spring.GetUnitRulesParam(unitID, "totalEconomyChange") or 1) -- * 16 if (strength > 0) then local type, target, isFeature = Spring.Utilities.GetUnitNanoTarget(unitID) if (target) then local endpos local radius = 30 if (type=="restore") then endpos = target radius = target[4] target = -1 elseif (not isFeature) then radius = (GetUnitRadius(target) or 1) * 0.80 else radius = (GetFeatureRadius(target) or 1) * 0.80 end local terraform = false local inversed = false if (type=="restore") then terraform = true elseif (type=="reclaim") then inversed = true end --[[ if (type=="reclaim") and (strength > 0) then --// reclaim is done always at full speed strength = 1 end ]]-- local cmdTag = GetCmdTag(unitID) local teamID = Spring.GetUnitTeam(unitID) local allyID = Spring.GetUnitAllyTeam(unitID) local unitDefID = Spring.GetUnitDefID(unitID) local faction = GetFaction(unitDefID) local teamColor = {Spring.GetTeamColor(teamID)} local nanoPieces = Spring.GetUnitNanoPieces(unitID) or {} for j=1,#nanoPieces do local nanoPieceID = nanoPieces[j] --local nanoPieceIDAlt = Spring.GetUnitScriptPiece(unitID, nanoPieceID) --if (unitID+frame)%60 == 0 then -- Spring.Echo("Nanopiece nums (output)", j, UnitDefs[unitDefID].name, nanoPieceID, nanoPieceIDAlt) --end local nanoParams = { targetID = target, isFeature = isFeature, unitpiece = nanoPieceID, unitID = unitID, unitDefID = unitDefID, teamID = teamID, allyID = allyID, nanopiece = nanoPieceID, targetpos = endpos, count = strength * 30, color = teamColor, type = type, targetradius = radius, terraform = terraform, inversed = inversed, cmdTag = cmdTag, --//used to end the fx when the command is finished life = 60, } local nanoSettings = CopyMergeTables(factionsNanoFx[faction] or factionsNanoFx.default, nanoParams) ExecuteLuaCode(nanoSettings) local fxType = nanoSettings.fxtype if (not nanoParticles[unitID]) then nanoParticles[unitID] = {} end local unitFxs = nanoParticles[unitID] if Lups then unitFxs[#unitFxs+1] = Lups.AddParticles(nanoSettings.fxtype,nanoSettings) end end end end end end --//for end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- function gadget:Update() if (spGetGameFrame()<1) then return end gadgetHandler:RemoveCallIn("Update") Lups = GG['Lups'] if (Lups) then initialized=true else return end --// enable freaky arm nano fx when quality>3 if ((Lups.Config["quality"] or 3) >= 3) then factionsNanoFx.default = factionsNanoFx["default_high_quality"] end --// init user custom nano fxs for faction,fx in pairs(Lups.Config or {}) do if (fx and (type(fx)=='table') and fx.fxtype) then local fxType = fx.fxtype local fxSettings = fx if (fxType)and ((fxType:lower()=="nanolasers")or (fxType:lower()=="nanoparticles"))and (fxSupported(fxType))and (fxSettings) then factionsNanoFx[faction] = fxSettings end end end for faction,fx in pairs(factionsNanoFx) do if (not fxSupported(fx.fxtype or "noneNANO")) then factionsNanoFx[faction] = factionsNanoFx.default end local factionNanoFx = factionsNanoFx[faction] factionNanoFx.delaySpread = 30 factionNanoFx.fxtype = factionNanoFx.fxtype:lower() if ((Lups.Config["quality"] or 2)>=2)and((factionNanoFx.fxtype=="nanolasers")or(factionNanoFx.fxtype=="nanolasersshader")) then factionNanoFx.flare = true end --// parse lua code in the table, so we can execute it later ParseLuaCode(factionNanoFx) end end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- local registeredBuilders = {} function gadget:UnitFinished(uid, udid) if (UnitDefs[udid].isBuilder) and not registeredBuilders[uid] then BuilderFinished(uid) registeredBuilders[uid] = nil end end function gadget:UnitDestroyed(uid, udid) if (UnitDefs[udid].isBuilder) and registeredBuilders[uid] then BuilderDestroyed(uid) registeredBuilders[uid] = nil end end function gadget:Initialize() for _,unitID in ipairs(Spring.GetAllUnits()) do local unitDefID = Spring.GetUnitDefID(unitID) gadget:UnitFinished(unitID, unitDefID) end end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- end
gpl-2.0
Scavenge/darkstar
scripts/zones/Spire_of_Vahzl/npcs/_0n2.lua
66
1356
----------------------------------- -- Area: Spire_of_vahlz -- NPC: web of regret ----------------------------------- package.loaded["scripts/zones/Spire_of_Vahzl/TextIDs"] = nil; ----------------------------------- require("scripts/globals/bcnm"); require("scripts/zones/Spire_of_Vahzl/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return 1; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdate CSID: %u",csid); -- printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinish CSID: %u",csid); -- printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Abyssea-Grauberg/npcs/qm8.lua
14
1343
----------------------------------- -- Zone: Abyssea-Grauberg -- NPC: qm8 (???) -- Spawns Ika-Roa -- @pos ? ? ? 254 ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --[[ if (trade:hasItemQty(3270,1) and trade:getItemCount() == 1) then -- Player has all the required items. if (GetMobAction(17818048) == ACTION_NONE) then -- Mob not already spawned from this SpawnMob(17818048):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:tradeComplete(); end end ]] end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(1010, 3270); -- Inform player what items they need. end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
ld-test/dromozoa-chunk
dromozoa/chunk/opcodes_5_1.lua
3
2177
return { { 0x00, "MOVE", false, true, "R", "N", "ABC" }; { 0x01, "LOADK", false, true, "K", "N", "ABx" }; { 0x02, "LOADBOOL", false, true, "U", "U", "ABC" }; { 0x03, "LOADNIL", false, true, "R", "N", "ABC" }; { 0x04, "GETUPVAL", false, true, "U", "N", "ABC" }; { 0x05, "GETGLOBAL", false, true, "K", "N", "ABx" }; { 0x06, "GETTABLE", false, true, "R", "K", "ABC" }; { 0x07, "SETGLOBAL", false, false, "K", "N", "ABx" }; { 0x08, "SETUPVAL", false, false, "U", "N", "ABC" }; { 0x09, "SETTABLE", false, false, "K", "K", "ABC" }; { 0x0A, "NEWTABLE", false, true, "U", "U", "ABC" }; { 0x0B, "SELF", false, true, "R", "K", "ABC" }; { 0x0C, "ADD", false, true, "K", "K", "ABC" }; { 0x0D, "SUB", false, true, "K", "K", "ABC" }; { 0x0E, "MUL", false, true, "K", "K", "ABC" }; { 0x0F, "DIV", false, true, "K", "K", "ABC" }; { 0x10, "MOD", false, true, "K", "K", "ABC" }; { 0x11, "POW", false, true, "K", "K", "ABC" }; { 0x12, "UNM", false, true, "R", "N", "ABC" }; { 0x13, "NOT", false, true, "R", "N", "ABC" }; { 0x14, "LEN", false, true, "R", "N", "ABC" }; { 0x15, "CONCAT", false, true, "R", "R", "ABC" }; { 0x16, "JMP", false, false, "R", "N", "AsBx" }; { 0x17, "EQ", true, false, "K", "K", "ABC" }; { 0x18, "LT", true, false, "K", "K", "ABC" }; { 0x19, "LE", true, false, "K", "K", "ABC" }; { 0x1A, "TEST", true, true, "R", "U", "ABC" }; { 0x1B, "TESTSET", true, true, "R", "U", "ABC" }; { 0x1C, "CALL", false, true, "U", "U", "ABC" }; { 0x1D, "TAILCALL", false, true, "U", "U", "ABC" }; { 0x1E, "RETURN", false, false, "U", "N", "ABC" }; { 0x1F, "FORLOOP", false, true, "R", "N", "AsBx" }; { 0x20, "FORPREP", false, true, "R", "N", "AsBx" }; { 0x21, "TFORLOOP", true, false, "N", "U", "ABC" }; { 0x22, "SETLIST", false, false, "U", "U", "ABC" }; { 0x23, "CLOSE", false, false, "N", "N", "ABC" }; { 0x24, "CLOSURE", false, true, "U", "N", "ABx" }; { 0x25, "VARARG", false, true, "U", "N", "ABC" }; }
gpl-3.0
1yvT0s/luvit
deps/fs.lua
6
18282
--[[ Copyright 2014-2015 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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. --]] exports.name = "luvit/fs" exports.version = "1.2.2" exports.dependencies = { "luvit/utils@1.0.0", "luvit/path@1.0.0", "luvit/stream@1.1.0", } exports.license = "Apache 2" exports.homepage = "https://github.com/luvit/luvit/blob/master/deps/fs.lua" exports.description = "Node-style filesystem module for luvit" exports.tags = {"luvit", "fs", "stream"} local uv = require('uv') local adapt = require('utils').adapt local bind = require('utils').bind local join = require('path').join local Error = require('core').Error local Writable = require('stream').Writable local Readable = require('stream').Readable local fs = exports function fs.close(fd, callback) return adapt(callback, uv.fs_close, fd) end function fs.closeSync(fd) return uv.fs_close(fd) end function fs.open(path, flags, mode, callback) local ft = type(flags) local mt = type(mode) -- (path, callback) if (ft == 'function' or ft == 'thread') and (mode == nil and callback == nil) then callback, flags = flags, nil -- (path, flags, callback) elseif (mt == 'function' or mt == 'thread') and (callback == nil) then callback, mode = mode, nil end -- Default flags to 'r' if flags == nil then flags = 'r' end -- Default mode to 0666 if mode == nil then mode = 438 -- 0666 -- Assume strings are octal numbers elseif mt == 'string' then mode = tonumber(mode, 8) end return adapt(callback, uv.fs_open, path, flags, mode) end function fs.openSync(path, flags, mode) if flags == nil then flags = "r" end if mode == nil then mode = 438 -- 0666 elseif type(mode) == "string" then mode = tonumber(mode, 8) end return uv.fs_open(path, flags, mode) end function fs.read(fd, size, offset, callback) local st = type(size) local ot = type(offset) if (st == 'function' or st == 'thread') and (offset == nil and callback == nil) then callback, size = size, nil elseif (ot == 'function' or ot == 'thread') and (callback == nil) then callback, offset = offset, nil end if size == nil then size = 4096 end if offset == nil then offset = -1 end return adapt(callback, uv.fs_read, fd, size, offset) end function fs.readSync(fd, size, offset) if size == nil then size = 4096 end if offset == nil then offset = -1 end return uv.fs_read(fd, size, offset) end function fs.unlink(path, callback) return adapt(callback, uv.fs_unlink, path) end function fs.unlinkSync(path) return uv.fs_unlink(path) end function fs.write(fd, offset, data, callback) local ot = type(offset) if (ot == 'function' or ot == 'thread') and (callback == nil) then callback, offset = offset, nil end if offset == nil then offset = -1 -- -1 means append end return adapt(callback, uv.fs_write, fd, data, offset) end function fs.writeSync(fd, offset, data) if offset == nil then offset = -1 -- -1 means append end return uv.fs_write(fd, data, offset) end function fs.mkdir(path, mode, callback) local mt = type(mode) if (mt == 'function' or mt == 'thread') and (callback == nil) then callback, mode = mode, nil end if mode == nil then mode = 511 -- 0777 elseif type(mode) == 'string' then mode = tonumber(mode, 8) end return adapt(callback, uv.fs_mkdir, path, mode) end function fs.mkdirSync(path, mode) if mode == nil then mode = 511 elseif type(mode) == 'string' then mode = tonumber(mode, 8) end return uv.fs_mkdir(path, mode) end function fs.mkdirpSync(path, mode) local success, err = fs.mkdirSync(path, mode) if success or string.match(err, "^EEXIST") then return true end if string.match(err, "^ENOENT:") then success, err = fs.mkdirpSync(join(path, ".."), mode) if not success then return nil, err end return fs.mkdirSync(path, mode) end return nil, err end function fs.mkdtemp(template, callback) return adapt(callback, uv.fs_mkdtemp, template) end function fs.mkdtempSync(template) return uv.fs_mkdtemp(template) end function fs.rmdir(path, callback) return adapt(callback, uv.fs_rmdir, path) end function fs.rmdirSync(path) return uv.fs_rmdir(path) end local function readdir(path, callback) uv.fs_scandir(path, function (err, req) if err then return callback(Error:new(err)) end local files = {} local i = 1 while true do local ent = uv.fs_scandir_next(req) if not ent then break end files[i] = ent.name i = i + 1 end callback(nil, files) end) end function fs.readdir(path, callback) return adapt(callback, readdir, path) end function fs.readdirSync(path) local req = uv.fs_scandir(path) local files = {} local i = 1 while true do local ent = uv.fs_scandir_next(req) if not ent then break end files[i] = ent.name i = i + 1 end return files end local function scandir(path, callback) uv.fs_scandir(path, function (err, req) if err then return callback(err) end callback(nil, function () local ent = uv.fs_scandir_next(req) if ent then return ent.name, ent.type end end) end) end function fs.scandir(path, callback) return adapt(callback, scandir, path) end function fs.scandirSync(path) local req = uv.fs_scandir(path) return function () local ent = uv.fs_scandir_next(req) if ent then return ent.name, ent.type end end end function fs.exists(path, callback) local stat,err = uv.fs_stat(path) callback(err,stat~=nil) end function fs.existsSync(path) local stat, err = uv.fs_stat(path) return stat ~= nil, err end function fs.stat(path, callback) return adapt(callback, uv.fs_stat, path) end function fs.statSync(path) return uv.fs_stat(path) end function fs.fstat(fd, callback) return adapt(callback, uv.fs_fstat, fd) end function fs.fstatSync(fd) return uv.fs_fstat(fd) end function fs.lstat(path, callback) return adapt(callback, uv.fs_lstat, path) end function fs.lstatSync(path) return uv.fs_lstat(path) end function fs.rename(path, newPath, callback) return adapt(callback, uv.fs_rename, path, newPath) end function fs.renameSync(path, newPath) return uv.fs_rename(path, newPath) end function fs.fsync(fd, callback) return adapt(callback, uv.fs_fsync, fd) end function fs.fsyncSync(fd) return uv.fs_fsync(fd) end function fs.fdatasync(fd, callback) return adapt(callback, uv.fs_fdatasync, fd) end function fs.fdatasyncSync(fd) return uv.fs_fdatasync(fd) end function fs.ftruncate(fd, offset, callback) local ot = type(offset) if (ot == 'function' or ot == 'thread') and (callback == nil) then callback, offset = offset, nil end if offset == nil then offset = 0 end return adapt(callback, uv.fs_ftruncate, fd, offset) end function fs.truncate(fname, offset, callback) local ot = type(offset) if (ot == 'function' or ot == 'thread') and (callback == nil) then callback, offset = offset, nil end if offset == nil then offset = 0 end fs.open(fname,'w', function(err,fd) if(err) then callback(err) else local cb = function(error) uv.fs_close(fd) callback(error) end return adapt(cb, uv.fs_ftruncate, fd, offset) end end) end function fs.ftruncateSync(fd, offset) if offset == nil then offset = 0 end return uv.fs_ftruncate(fd, offset) end function fs.truncateSync(fname, offset) if offset == nil then offset = 0 end local fd, err = fs.openSync(fname, "w") local ret if fd then ret, err = uv.fs_ftruncate(fd, offset) fs.closeSync(fd) end return ret,err end function fs.sendfile(outFd, inFd, offset, length, callback) return adapt(callback, uv.fs_sendfile, outFd, inFd, offset, length) end function fs.sendfileSync(outFd, inFd, offset, length) return uv.fs_sendfile(outFd, inFd, offset, length) end function fs.access(path, flags, callback) local ft = type(flags) if (ft == 'function' or ft == 'thread') and (callback == nil) then callback, flags = flags, nil end if flags == nil then flags = 0 end return adapt(callback, uv.fs_access, path, flags) end function fs.accessSync(path, flags) if flags == nil then flags = 0 end return uv.fs_access(path, flags) end function fs.chmod(path, mode, callback) return adapt(callback, uv.fs_chmod, path, mode) end function fs.chmodSync(path, mode) return uv.fs_chmod(path, mode) end function fs.fchmod(fd, mode, callback) return adapt(callback, uv.fs_fchmod, fd, mode) end function fs.fchmodSync(fd, mode) return uv.fs_fchmod(fd, mode) end function fs.utime(path, atime, mtime, callback) return adapt(callback, uv.fs_utime, path, atime, mtime) end function fs.utimeSync(path, atime, mtime) return uv.fs_utime(path, atime, mtime) end function fs.futime(fd, atime, mtime, callback) return adapt(callback, uv.fs_futime, fd, atime, mtime) end function fs.futimeSync(fd, atime, mtime) return uv.fs_futime(fd, atime, mtime) end function fs.link(path, newPath, callback) return adapt(callback, uv.fs_link, path, newPath) end function fs.linkSync(path, newPath) return uv.fs_link(path, newPath) end function fs.symlink(path, newPath, options, callback) local ot = type(options) if (ot == 'function' or ot == 'thread') and (callback == nil) then callback, options = options, nil end return adapt(callback, uv.fs_symlink, path, newPath, options) end function fs.symlinkSync(path, newPath, options) return uv.fs_symlink(path, newPath, options) end function fs.readlink(path, callback) return adapt(callback, uv.fs_readlink, path) end function fs.readlinkSync(path) return uv.fs_readlink(path) end function fs.chown(path, uid, gid, callback) return adapt(callback, uv.fs_chown, path, uid, gid) end function fs.chownSync(path, uid, gid) return uv.fs_chown(path, uid, gid) end function fs.fchown(fd, uid, gid, callback) return adapt(callback, uv.fs_fchown, fd, uid, gid) end function fs.fchownSync(fd, uid, gid) return uv.fs_fchown(fd, uid, gid) end local function noop() end local function readFile(path, callback) local fd, onStat, onRead, onChunk, pos, chunks uv.fs_open(path, "r", 438 --[[ 0666 ]], function (err, result) if err then return callback(err) end fd = result uv.fs_fstat(fd, onStat) end) function onStat(err, stat) if err then return onRead(err) end if stat.size > 0 then uv.fs_read(fd, stat.size, 0, onRead) else -- the kernel lies about many files. -- Go ahead and try to read some bytes. pos = 0 chunks = {} uv.fs_read(fd, 8192, 0, onChunk) end end function onRead(err, chunk) uv.fs_close(fd, noop) return callback(err, chunk) end function onChunk(err, chunk) if err then uv.fs_close(fd, noop) return callback(err) end if chunk and #chunk > 0 then chunks[#chunks + 1] = chunk pos = pos + #chunk return uv.fs_read(fd, 8192, pos, onChunk) end uv.fs_close(fd, noop) return callback(nil, table.concat(chunks)) end end function fs.readFile(path, callback) return adapt(callback, readFile, path) end function fs.readFileSync(path) local fd, stat, chunk, err fd, err = uv.fs_open(path, "r", 438 --[[ 0666 ]]) if err then return false, err end stat, err = uv.fs_fstat(fd) if stat then if stat.size > 0 then chunk, err = uv.fs_read(fd, stat.size, 0) else local chunks = {} local pos = 0 while true do chunk, err = uv.fs_read(fd, 8192, pos) if not chunk or #chunk == 0 then break end pos = pos + #chunk chunks[#chunks + 1] = chunk end if not err then chunk = table.concat(chunks) end end end uv.fs_close(fd, noop) return chunk, err end local function writeFile(path, data, callback) local fd, onWrite uv.fs_open(path, "w", 438 --[[ 0666 ]], function (err, result) if err then return callback(err) end fd = result uv.fs_write(fd, data, 0, onWrite) end) function onWrite(err) uv.fs_close(fd, noop) return callback(err) end end function fs.writeFile(path, data, callback) adapt(callback, writeFile, path, data) end function fs.writeFileSync(path, data) local _, fd, err fd, err = uv.fs_open(path, "w", 438 --[[ 0666 ]]) if err then return false, err end _, err = uv.fs_write(fd, data, 0) uv.fs_close(fd, noop) return not err, err end fs.WriteStream = Writable:extend() function fs.WriteStream:initialize(path, options) Writable.initialize(self) self.options = options or {} self.path = path self.fd = nil self.pos = nil self.bytesWritten = 0 if self.options.fd then self.fd = self.options.fd end if self.options.flags then self.flags = self.options.flags else self.flags = 'w' end if self.options.mode then self.mode = self.options.mode else self.mode = 438 end if self.options.start then self.start = self.options.start end self.pos = self.start if not self.fd then self:open() end self:on('finish', bind(self.close, self)) end function fs.WriteStream:open(callback) if self.fd then self:destroy() end fs.open(self.path, self.flags, nil, function(err, fd) if err then self:destroy() self:emit('error', err) if callback then callback(err) end return end self.fd = fd self:emit('open', fd) if callback then callback() end end) end function fs.WriteStream:_write(data, callback) if not self.fd then return self:once('open', bind(self._write, self, data, callback)) end fs.write(self.fd, nil, data, function(err, bytes) if err then self:destroy() return callback(err) end self.bytesWritten = self.bytesWritten + bytes callback() end) end function fs.WriteStream:close() self:destroy() end function fs.WriteStream:destroy() if self.fd then fs.close(self.fd) self.fd = nil end end function fs.createWriteStream(path, options) return fs.WriteStream:new(path, options) end fs.WriteStreamSync = fs.WriteStream:extend() function fs.WriteStreamSync:initialize(path, options) fs.WriteStream.initialize(self, path, options) end function fs.WriteStreamSync:open(callback) local err if self.fd then self:destroy() end self.fd, err = fs.openSync(self.path, "a") if err then self:destroy() self:emit('error', err) if callback then callback(err) end return end self:emit('open', self.fd) if callback then callback() end end function fs.WriteStreamSync:_write(data, callback) if not self.fd then return self:once('open', bind(self._write, self, data, callback)) end local written, err = fs.writeSync(self.fd, -1, data) if err then self:destroy() return callback(err) end self.bytesWritten = self.bytesWritten + written callback() end local CHUNK_SIZE = 65536 local read_options = { flags = "r", mode = "0644", chunkSize = CHUNK_SIZE, fd = nil, reading = nil, length = nil -- nil means read to EOF } local read_meta = {__index=read_options} fs.ReadStream = Readable:extend() function fs.ReadStream:initialize(path, options) Readable.initialize(self) if not options then options = read_options else setmetatable(options, read_meta) end self.fd = options.fd self.mode = options.mode self.path = path self.offset = options.offset self.chunkSize = options.chunkSize self.length = options.length self.bytesRead = 0 if not self.fd then self:open() end self:on('end', bind(self.close, self)) end function fs.ReadStream:open(callback) if self.fd then self:destroy() end fs.open(self.path, self.flags, self.mode, function(err, fd) if err then self:destroy() self:emit('error', err) if callback then callback(err) end return end self.fd = fd self:emit('open', fd) if callback then callback() end end) end function fs.ReadStream:_read(n) if not self.fd then return self:once('open', bind(self._read, self, n)) end local to_read = self.chunkSize or n if self.length then -- indicating length was set in option; need to check boundary if to_read + self.bytesRead > self.length then to_read = self.length - self.bytesRead end end fs.read(self.fd, to_read, self.offset, function(err, bytes) if err then return self:destroy(err) end if #bytes > 0 then self.bytesRead = self.bytesRead + #bytes if self.offset then self.offset = self.offset + #bytes end self:push(bytes) else self:push() end end) end function fs.ReadStream:close() self:destroy() end function fs.ReadStream:destroy(err) if err then self:emit('error', err) end if self.fd then fs.close(self.fd) self.fd = nil end end function fs.createReadStream(path, options) return fs.ReadStream:new(path, options) end function fs.appendFile(filename, data, callback) callback = callback or function() end local function write(fd, offset, buffer, callback) local function onWrite(err, written) if err then return fs.close(fd, function() callback(err) end) end if written == #buffer then fs.close(fd, callback) else offset = offset + written buffer = buffer:sub(offset) write(fd, offset, buffer, callback) end end fs.write(fd, -1, data, onWrite) end fs.open(filename, "a", 438 --[[ 0666 ]], function(err, fd) if err then return callback(err) end write(fd, -1, data, callback) end) end function fs.appendFileSync(path, data) local written local fd, err = fs.openSync(path, 'a') if not fd then return err end written, err = fs.writeSync(fd, -1, data) if not written then fs.close(fd) ; return err end fs.close(fd) end
apache-2.0
Scavenge/darkstar
scripts/zones/LaLoff_Amphitheater/npcs/qm2.lua
17
2234
----------------------------------- -- Area: LaLoff_Amphitheater -- NPC: Shimmering Circle (BCNM Exits) ------------------------------------- package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil; ------------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/LaLoff_Amphitheater/TextIDs"); ---- 0: ---- 1: ---- 2: ---- 3: ---- 4: ---- 5: ---- 6: ---- 7: ---- 8: ---- 9: -- Death cutscenes: -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); -- hume -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0); -- taru -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,2,0); -- mithra -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,0); -- elvaan -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,4,0); -- galka -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,5,0); -- divine might -- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,6,0); -- skip ending cs ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdate CSID: %u",csid); -- printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinish CSID: %u",csid); -- printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
Kyklas/luci-proto-hso
applications/luci-openvpn/luasrc/model/cbi/openvpn-advanced.lua
6
20068
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.ip") require("luci.model.uci") local knownParams = { -- -- Widget Name Default(s) Description Option(s) -- { "Service", { -- initialisation and daemon options { ListValue, "verb", { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }, translate("Set output verbosity") }, { Flag, "mlock", 0, translate("Disable Paging") }, { Flag, "disable_occ", 0, translate("Disable options consistency check") }, -- { Value, "user", "root", translate("Set UID to user") }, -- { Value, "group", "root", translate("Set GID to group") }, { Value, "cd", "/etc/openvpn", translate("Change to directory before initialization") }, { Value, "chroot", "/var/run", translate("Chroot to directory after initialization") }, -- { Value, "daemon", "Instance-Name", translate("Daemonize after initialization") }, -- { Value, "syslog", "Instance-Name", translate("Output to syslog and do not daemonize") }, { Flag, "passtos", 0, translate("TOS passthrough (applies to IPv4 only)") }, -- { Value, "inetd", "nowait Instance-Name", translate("Run as an inetd or xinetd server") }, { Value, "log", "/var/log/openvpn.log", translate("Write log to file") }, { Value, "log_append", "/var/log/openvpn.log", translate("Append log to file") }, { Flag, "suppress_timestamps", 0, translate("Don't log timestamps") }, -- { Value, "writepid", "/var/run/openvpn.pid", translate("Write process ID to file") }, { Value, "nice", 0, translate("Change process priority") }, { Flag, "fast_io", 0, translate("Optimize TUN/TAP/UDP writes") }, { Value, "echo", "some params echoed to log", translate("Echo parameters to log") }, { ListValue, "remap_usr1", { "SIGHUP", "SIGTERM" }, translate("Remap SIGUSR1 signals") }, { Value, "status", "/var/run/openvpn.status 5", translate("Write status to file every n seconds") }, { Value, "status_version", { 1, 2 }, translate("Status file format version") }, -- status { Value, "mute", 5, translate("Limit repeated log messages") }, { Value, "up", "/usr/bin/ovpn-up", translate("Shell cmd to execute after tun device open") }, { Value, "up_delay", 5, translate("Delay tun/tap open and up script execution") }, { Value, "down", "/usr/bin/ovpn-down", translate("Shell cmd to run after tun device close") }, { Flag, "down_pre", 0, translate("Call down cmd/script before TUN/TAP close") }, { Flag, "up_restart", 0, translate("Run up/down scripts for all restarts") }, { Value, "route_up", "/usr/bin/ovpn-routeup", translate("Execute shell cmd after routes are added") }, { Value, "ipchange", "/usr/bin/ovpn-ipchange", translate("Execute shell command on remote ip change"), { mode="p2p" } }, { DynamicList, "setenv", { "VAR1 value1", "VAR2 value2" }, translate("Pass environment variables to script") }, { Value, "tls_verify", "/usr/bin/ovpn-tlsverify", translate("Shell command to verify X509 name") }, { Value, "client_connect", "/usr/bin/ovpn-clientconnect", translate("Run script cmd on client connection") }, { Flag, "client_disconnect", 0, translate("Run script cmd on client disconnection") }, { Value, "learn_address", "/usr/bin/ovpn-learnaddress", translate("Executed in server mode whenever an IPv4 address/route or MAC address is added to OpenVPN's internal routing table") }, { Value, "auth_user_pass_verify", "/usr/bin/ovpn-userpass via-env", translate("Executed in server mode on new client connections, when the client is still untrusted") }, { ListValue, "script_security", { 0, 1, 2, 3 }, translate("Policy level over usage of external programs and scripts"), {mode="server" } }, } }, { "Networking", { -- socket config { ListValue, "mode", { "p2p", "server" }, translate("Major mode") }, { Value, "local", "0.0.0.0", translate("Local host name or ip address") }, { Value, "port", 1194, translate("TCP/UDP port # for both local and remote") }, { Value, "lport", 1194, translate("TCP/UDP port # for local (default=1194)") }, { Value, "rport", 1194, translate("TCP/UDP port # for remote (default=1194)") }, { Flag, "float", 0, translate("Allow remote to change its IP or port") }, { Flag, "nobind", 0, translate("Do not bind to local address and port") }, { Value, "dev", "tun0", translate("tun/tap device") }, { ListValue, "dev_type", { "tun", "tap" }, translate("Type of used device") }, { Value, "dev_node", "/dev/net/tun", translate("Use tun/tap device node") }, { Flag, "tun_ipv6", 0, translate("Make tun device IPv6 capable") }, { Value, "ifconfig", "10.200.200.3 10.200.200.1", translate("Set tun/tap adapter parameters") }, { Flag, "ifconfig_noexec", 0, translate("Don't actually execute ifconfig") }, { Flag, "ifconfig_nowarn", 0, translate("Don't warn on ifconfig inconsistencies") }, { DynamicList, "route", "10.123.0.0 255.255.0.0", translate("Add route after establishing connection") }, { Value, "route_gateway", "10.234.1.1", translate("Specify a default gateway for routes") }, { Value, "route_delay", 0, translate("Delay n seconds after connection") }, { Flag, "route_noexec", 0, translate("Don't add routes automatically") }, { ListValue, "mtu_disc", { "yes", "maybe", "no" }, translate("Enable Path MTU discovery") }, { Flag, "mtu_test", 0, translate("Empirically measure MTU") }, { ListValue, "comp_lzo", { "yes", "no", "adaptive" }, translate("Use fast LZO compression") }, { Flag, "comp_noadapt", 0, translate("Don't use adaptive lzo compression"), { comp_lzo=1 } }, { Value, "link_mtu", 1500, translate("Set TCP/UDP MTU") }, { Value, "tun_mtu", 1500, translate("Set tun/tap device MTU") }, { Value, "tun_mtu_extra", 1500, translate("Set tun/tap device overhead") }, { Value, "fragment", 1500, translate("Enable internal datagram fragmentation"), { proto="udp" } }, { Value, "mssfix", 1500, translate("Set upper bound on TCP MSS"), { proto="udp" } }, { Value, "sndbuf", 65536, translate("Set the TCP/UDP send buffer size") }, { Value, "rcvbuf", 65536, translate("Set the TCP/UDP receive buffer size") }, { Value, "txqueuelen", 100, translate("Set tun/tap TX queue length") }, { Value, "shaper", 10240, translate("Shaping for peer bandwidth") }, { Value, "inactive", 240, translate("tun/tap inactivity timeout") }, { Value, "keepalive", "10 60", translate("Helper directive to simplify the expression of --ping and --ping-restart in server mode configurations") }, { Value, "ping", 30, translate("Ping remote every n seconds over TCP/UDP port") }, { Value, "ping_exit", 120, translate("Remote ping timeout") }, { Value, "ping_restart", 60, translate("Restart after remote ping timeout") }, { Flag, "ping_timer_rem", 0, translate("Only process ping timeouts if routes exist") }, { Flag, "persist_tun", 0, translate("Keep tun/tap device open on restart") }, { Flag, "persist_key", 0, translate("Don't re-read key on restart") }, { Flag, "persist_local_ip", 0, translate("Keep local IP address on restart") }, { Flag, "persist_remote_ip", 0, translate("Keep remote IP address on restart") }, -- management channel { Value, "management", "127.0.0.1 31194 /etc/openvpn/mngmt-pwds", translate("Enable management interface on <em>IP</em> <em>port</em>") }, { Flag, "management_query_passwords", 0, translate("Query management channel for private key") }, -- management { Flag, "management_hold", 0, translate("Start OpenVPN in a hibernating state") }, -- management { Value, "management_log_cache", 100, translate("Number of lines for log file history") }, -- management { ListValue, "topology", { "net30", "p2p", "subnet" }, translate("'net30', 'p2p', or 'subnet'"), {dev_type="tun" } }, } }, { "VPN", { { Value, "server", "10.200.200.0 255.255.255.0", translate("Configure server mode"), { server_mode="1" } }, { Value, "server_bridge", "10.200.200.1 255.255.255.0 10.200.200.200 10.200.200.250", translate("Configure server bridge"), { server_mode="1" } }, { DynamicList, "push", { "redirect-gateway", "comp-lzo" }, translate("Push options to peer"), { server_mode="1" } }, { Flag, "push_reset", 0, translate("Don't inherit global push options"), { server_mode="1" } }, { Flag, "disable", 0, translate("Client is disabled"), { server_mode="1" } }, { Value, "ifconfig_pool", "10.200.200.100 10.200.200.150 255.255.255.0", translate("Set aside a pool of subnets"), { server_mode="1" } }, { Value, "ifconfig_pool_persist", "/etc/openvpn/ipp.txt 600", translate("Persist/unpersist ifconfig-pool"), { server_mode="1" } }, -- { Flag, "ifconfig_pool_linear", 0, translate("Use individual addresses rather than /30 subnets"), { server_mode="1" } }, -- deprecated and replaced by --topology p2p { Value, "ifconfig_push", "10.200.200.1 255.255.255.255", translate("Push an ifconfig option to remote"), { server_mode="1" } }, { Value, "iroute", "10.200.200.0 255.255.255.0", translate("Route subnet to client"), { server_mode="1" } }, { Flag, "client_to_client", 0, translate("Allow client-to-client traffic"), { server_mode="1" } }, { Flag, "duplicate_cn", 0, translate("Allow multiple clients with same certificate"), { server_mode="1" } }, { Value, "client_config_dir", "/etc/openvpn/ccd", translate("Directory for custom client config files"), { server_mode="1" } }, { Flag, "ccd_exclusive", 0, translate("Refuse connection if no custom client config"), { server_mode="1" } }, { Value, "tmp_dir", "/var/run/openvpn", translate("Temporary directory for client-connect return file"), { server_mode="1" } }, { Value, "hash_size", "256 256", translate("Set size of real and virtual address hash tables"), { server_mode="1" } }, { Value, "bcast_buffers", 256, translate("Number of allocated broadcast buffers"), { server_mode="1" } }, { Value, "tcp_queue_limit", 64, translate("Maximum number of queued TCP output packets"), { server_mode="1" } }, { Value, "max_clients", 10, translate("Allowed maximum of connected clients"), { server_mode="1" } }, { Value, "max_routes_per_client", 256, translate("Allowed maximum of internal"), { server_mode="1" } }, { Value, "connect_freq", "3 10", translate("Allowed maximum of new connections"), { server_mode="1" } }, { Flag, "client_cert_not_required", 0, translate("Don't require client certificate"), { server_mode="1" } }, { Flag, "username_as_common_name", 0, translate("Use username as common name"), { server_mode="1" } }, { Flag, "client", 0, translate("Configure client mode"), { server_mode="0" }, { server_mode="" } }, { Flag, "pull", 0, translate("Accept options pushed from server"), { client="1" } }, { Value, "auth_user_pass", "/etc/openvpn/userpass.txt", translate("Authenticate using username/password"), { client="1" } }, { ListValue, "auth_retry", { "none", "nointeract", "interact" }, translate("Handling of authentication failures"), { client="1" } }, { Value, "explicit_exit_notify", 1, translate("Send notification to peer on disconnect"), { client="1" } }, { DynamicList, "remote", "1.2.3.4", translate("Remote host name or ip address"), { client="1" } }, { Flag, "remote_random", 1, translate("Randomly choose remote server"), { client="1" } }, { ListValue, "proto", { "udp", "tcp-client", "tcp-server" }, translate("Use protocol"), { client="1" } }, { Value, "connect_retry", 5, translate("Connection retry interval"), { proto="tcp-client" }, { client="1" } }, { Value, "http_proxy", "192.168.1.100 8080", translate("Connect to remote host through an HTTP proxy"), { client="1" } }, { Flag, "http_proxy_retry", 0, translate("Retry indefinitely on HTTP proxy errors"), { client="1" } }, { Value, "http_proxy_timeout", 5, translate("Proxy timeout in seconds"), { client="1" } }, { DynamicList, "http_proxy_option", { "VERSION 1.0", "AGENT OpenVPN/2.0.9" }, translate("Set extended HTTP proxy options"), { client="1" } }, { Value, "socks_proxy", "192.168.1.200 1080", translate("Connect through Socks5 proxy"), { client="1" } }, { Value, "socks_proxy_retry", 5, translate("Retry indefinitely on Socks proxy errors"), { client="1" } }, -- client && socks_proxy { Value, "resolv_retry", "infinite", translate("If hostname resolve fails, retry"), { client="1" } }, { ListValue, "redirect_gateway", { "", "local", "def1", "local def1" }, translate("Automatically redirect default route"), { client="1" } }, } }, { "Cryptography", { { Value, "secret", "/etc/openvpn/secret.key 1", translate("Enable Static Key encryption mode (non-TLS)") }, { Value, "auth", "SHA1", translate("HMAC authentication for packets") }, -- parse { Value, "cipher", "BF-CBC", translate("Encryption cipher for packets") }, -- parse { Value, "keysize", 1024, translate("Size of cipher key") }, -- parse { Value, "engine", "dynamic", translate("Enable OpenSSL hardware crypto engines") }, -- parse { Flag, "no_replay", 0, translate("Disable replay protection") }, { Value, "replay_window", "64 15", translate("Replay protection sliding window size") }, { Flag, "mute_replay_warnings", 0, translate("Silence the output of replay warnings") }, { Value, "replay_persist", "/var/run/openvpn-replay-state", translate("Persist replay-protection state") }, { Flag, "no_iv", 0, translate("Disable cipher initialisation vector") }, { Flag, "tls_server", 0, translate("Enable TLS and assume server role"), { tls_client="" }, { tls_client="0" } }, { Flag, "tls_client", 0, translate("Enable TLS and assume client role"), { tls_server="" }, { tls_server="0" } }, { FileUpload, "ca", "/etc/easy-rsa/keys/ca.crt", translate("Certificate authority") }, { FileUpload, "dh", "/etc/easy-rsa/keys/dh1024.pem", translate("Diffie Hellman parameters") }, { FileUpload, "cert", "/etc/easy-rsa/keys/some-client.crt", translate("Local certificate") }, { FileUpload, "key", "/etc/easy-rsa/keys/some-client.key", translate("Local private key") }, { FileUpload, "pkcs12", "/etc/easy-rsa/keys/some-client.pk12", translate("PKCS#12 file containing keys") }, { ListValue, "key_method", { 1, 2 }, translate("Enable TLS and assume client role") }, { Value, "tls_cipher", "DHE-RSA-AES256-SHA:DHE-DSS-AES256-SHA:AES256-SHA:EDH-RSA-DES-CBC3-SHA:EDH-DSS-DES-CBC3-SHA:DES-CBC3-SHA:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA:AES128-SHA:RC4-SHA:RC4-MD5:EDH-RSA-DES-CBC-SHA:EDH-DSS-DES-CBC-SHA:DES-CBC-SHA:EXP-EDH-RSA-DES-CBC-SHA:EXP-EDH-DSS-DES-CBC-SHA:EXP-DES-CBC-SHA:EXP-RC2-CBC-MD5:EXP-RC4-MD5", translate("TLS cipher") }, { Value, "tls_timeout", 2, translate("Retransmit timeout on TLS control channel") }, { Value, "reneg_bytes", 1024, translate("Renegotiate data chan. key after bytes") }, { Value, "reneg_pkts", 100, translate("Renegotiate data chan. key after packets") }, { Value, "reneg_sec", 3600, translate("Renegotiate data chan. key after seconds") }, { Value, "hand_window", 60, translate("Timeframe for key exchange") }, { Value, "tran_window", 3600, translate("Key transition window") }, { Flag, "single_session", 0, translate("Allow only one session") }, { Flag, "tls_exit", 0, translate("Exit on TLS negotiation failure") }, { Value, "tls_auth", "/etc/openvpn/tlsauth.key 1", translate("Additional authentication over TLS") }, --{ Value, "askpass", "[file]", translate("Get PEM password from controlling tty before we daemonize") }, { Flag, "auth_nocache", 0, translate("Don't cache --askpass or --auth-user-pass passwords") }, { Value, "tls_remote", "remote_x509_name", translate("Only accept connections from given X509 name") }, { ListValue, "ns_cert_type", { "client", "server" }, translate("Require explicit designation on certificate") }, { ListValue, "remote_cert_tls", { "client", "server" }, translate("Require explicit key usage on certificate") }, { Value, "crl_verify", "/etc/easy-rsa/keys/crl.pem", translate("Check peer certificate against a CRL") }, } } } local cts = { } local params = { } local m = Map("openvpn") local p = m:section( SimpleSection ) p.template = "openvpn/pageswitch" p.mode = "advanced" p.instance = arg[1] p.category = arg[2] or "Service" for _, c in ipairs(knownParams) do cts[#cts+1] = c[1] if c[1] == p.category then params = c[2] end end p.categories = cts local s = m:section( NamedSection, arg[1], "openvpn", translate("%s" % arg[2]) ) s.title = translate("%s" % arg[2]) s.addremove = false s.anonymous = true for _, option in ipairs(params) do local o = s:option( option[1], option[2], option[2], option[4] ) if option[1] == DummyValue then o.value = option[3] else if option[1] == DynamicList then o.cast = nil function o.cfgvalue(...) local val = AbstractValue.cfgvalue(...) return ( val and type(val) ~= "table" ) and { val } or val end end o.optional = true if type(option[3]) == "table" then if o.optional then o:value("", "-- remove --") end for _, v in ipairs(option[3]) do v = tostring(v) o:value(v) end o.default = tostring(option[3][1]) else o.default = tostring(option[3]) end end for i=5,#option do if type(option[i]) == "table" then o:depends(option[i]) end end end return m
apache-2.0
Scavenge/darkstar
scripts/zones/Spire_of_Vahzl/Zone.lua
30
1673
----------------------------------- -- -- Zone: Spire_of_Vahzl (23) -- ----------------------------------- package.loaded["scripts/zones/Spire_of_Vahzl/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Spire_of_Vahzl/TextIDs"); require("scripts/globals/missions"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-0.039,-2.049,293.640,64); -- Floor 1 {R} end if (player:getCurrentMission(COP) == DESIRES_OF_EMPTINESS and player:getVar("PromathiaStatus")==7) then cs = 0x0014; end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0014) then player:setVar("PromathiaStatus",8); end end;
gpl-3.0
Zomis/FactorioMods
search-engine_0.0.1/v2/plugins/loops/loops.lua
1
2814
local loop_plugins = { entities = { provides = "entity", controls = function() return { { type = "drop-down", ref = { "entity_type" }, items = { "container", "storage-tank", "any-machine", "assembling-machine", "furnace", "constant-combinator", "programmable-speaker", "lamp", "radar", "vehicle" }, selected_index = 1 } -- TODO: generic component for name search: text input -- (contains / starts with / exact match / fuzzy search, default to fuzzy here) -- fuzzy: https://codereview.stackexchange.com/questions/111957/vc-as-in-vancouver-or-valencia } end, func = function(search) -- TODO: Search in area: -- local cursor_stack = player.cursor_stack -- cursor_stack.clear() -- cursor_stack.set_stack({name="search-engine-area-filter", type="selection-tool", count = 1}) -- TODO: Support ghosts somehow? Especially showing what kind of ghost it is search.params.force = search.player.force local drop_down = search.gui_loop_params.entity_type search.params.type = drop_down.items[drop_down.selected_index] if search.params.type == "any-machine" then search.params.type = {"assembling-machine","furnace"} elseif search.params.type == "vehicle" then search.params.type = {"car","tank","spidertron"} end return search.player.surface.find_entities_filtered(search.params) end }, recipes = { provides = "recipe", controls = function() return { -- enabled, containing ingredient/product/anywhere } end, func = function() -- TODO: Use LuaGameScript.get_filtered_recipe_prototypes return game.recipe_prototypes end } } local function gui_elements() local r = {} for k, v in pairs(loop_plugins) do table.insert(r, { type = "button", caption = k, tags = { loop_id = k, provides = v.provides } }) end return r end local function create_loop(loop_id, search) return loop_plugins[loop_id].func(search) end local function provides(loop_id) return loop_plugins[loop_id].provides end local function controls(loop_id, search) return loop_plugins[loop_id].controls(search) end return { controls = controls, gui_elements = gui_elements, provides = provides, create_loop = create_loop }
mit
kjc88/sl4a
lua/luasocket/etc/qp.lua
59
1025
----------------------------------------------------------------------------- -- Little program to convert to and from Quoted-Printable -- LuaSocket sample files -- Author: Diego Nehab -- RCS ID: $Id: qp.lua,v 1.5 2004/06/17 21:46:22 diego Exp $ ----------------------------------------------------------------------------- local ltn12 = require("ltn12") local mime = require("mime") local convert arg = arg or {} local mode = arg and arg[1] or "-et" if mode == "-et" then local normalize = mime.normalize() local qp = mime.encode("quoted-printable") local wrap = mime.wrap("quoted-printable") convert = ltn12.filter.chain(normalize, qp, wrap) elseif mode == "-eb" then local qp = mime.encode("quoted-printable", "binary") local wrap = mime.wrap("quoted-printable") convert = ltn12.filter.chain(qp, wrap) else convert = mime.decode("quoted-printable") end local source = ltn12.source.chain(ltn12.source.file(io.stdin), convert) local sink = ltn12.sink.file(io.stdout) ltn12.pump.all(source, sink)
apache-2.0
Scavenge/darkstar
scripts/zones/Abyssea-Tahrongi/npcs/qm13.lua
42
1872
----------------------------------- -- Zone: Abyssea-Tahrongi -- NPC: ??? -- Spawns Chloris -- @pos ? ? ? 45 ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/status"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --[[ if (GetMobAction(16961946) == ACTION_NONE) then -- NM not already spawned from this if (player:hasKeyItem(VEINOUS_HECTEYES_EYELID) and player:hasKeyItem(TORN_BAT_WING) and player:hasKeyItem(GORY_SCORPION_CLAW) -- I broke it into 3 lines at the 'and' because it was so long. and player:hasKeyItem(MOSSY_ADAMANTOISE_SHELL)) then player:startEvent(1020, VEINOUS_HECTEYES_EYELID, TORN_BAT_WING, GORY_SCORPION_CLAW, MOSSY_ADAMANTOISE_SHELL); -- Ask if player wants to use KIs else player:startEvent(1021, VEINOUS_HECTEYES_EYELID, TORN_BAT_WING, GORY_SCORPION_CLAW, MOSSY_ADAMANTOISE_SHELL); -- Do not ask, because player is missing at least 1. end end ]] end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 1020 and option == 1) then SpawnMob(16961946):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:delKeyItem(VEINOUS_HECTEYES_EYELID); player:delKeyItem(TORN_BAT_WING); player:delKeyItem(GORY_SCORPION_CLAW); player:delKeyItem(MOSSY_ADAMANTOISE_SHELL); end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Kazham/npcs/Nti_Badolsoma.lua
17
1071
----------------------------------- -- Area: Kazham -- NPC: Nti Badolsoma -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("BathedInScent") == 1) then player:startEvent(0x00B2); -- scent from Blue Rafflesias else player:startEvent(0x0058); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
kankaristo/premake-core
src/actions/vstudio/vs2010_rules_xml.lua
12
8363
--- -- vs2010_rules_xml.lua -- Generate a Visual Studio 201x custom rules XML file. -- Copyright (c) 2014 Jason Perkins and the Premake project -- premake.vstudio.vs2010.rules.xml = {} local m = premake.vstudio.vs2010.rules.xml m.elements = {} local p = premake --- -- Entry point; generate the root <ProjectSchemaDefinitions> element. --- m.elements.project = function(r) return { p.xmlUtf8, m.projectSchemaDefinitions, m.rule, m.ruleItem, m.fileExtension, m.contentType, } end function m.generate(r) p.callArray(m.elements.project, r) p.out('</ProjectSchemaDefinitions>') end --- -- Generate the main <Rule> element. --- m.elements.rule = function(r) return { m.dataSource, m.categories, m.inputs, m.properties, m.commandLineTemplate, m.beforeTargets, m.afterTargets, m.outputs, m.executionDescription, m.additionalDependencies, m.additionalOptions, } end function m.rule(r) p.push('<Rule') p.w('Name="%s"', r.name) p.w('PageTemplate="tool"') p.w('DisplayName="%s"', r.display or r.name) p.w('Order="200">') p.callArray(m.elements.rule, r) p.pop('</Rule>') end --- -- Generate the list of categories. --- function m.categories(r) local categories = { [1] = { name="General" }, [2] = { name="Command Line", subtype="CommandLine" }, } p.push('<Rule.Categories>') for i = 1, #categories do m.category(categories[i]) end p.pop('</Rule.Categories>') end function m.category(cat) local attribs = p.capture(function() p.push() p.w('Name="%s"', cat.name) if cat.subtype then p.w('Subtype="%s"', cat.subtype) end p.pop() end) p.push('<Category') p.outln(attribs .. '>') p.push('<Category.DisplayName>') p.w('<sys:String>%s</sys:String>', cat.name) p.pop('</Category.DisplayName>') p.pop('</Category>') end --- -- Generate the list of property definitions. --- function m.properties(r) local defs = r.propertydefinition for i = 1, #defs do local def = defs[i] if def.kind == "boolean" then m.boolProperty(def) elseif def.kind == "list" then m.stringListProperty(def) elseif type(def.values) == "table" then m.enumProperty(def) else m.stringProperty(def) end end end function m.baseProperty(def, suffix) local c = p.capture(function () p.w('Name="%s"', def.name) p.w('HelpContext="0"') p.w('DisplayName="%s"', def.display or def.name) if def.description then p.w('Description="%s"', def.description) end end) if suffix then c = c .. suffix end p.outln(c) end function m.boolProperty(def) p.push('<BoolProperty') m.baseProperty(def) p.w('Switch="%s" />', def.switch or "[value]") p.pop() end function m.enumProperty(def) p.push('<EnumProperty') m.baseProperty(def, '>') local values = def.values local switches = def.switch or {} local keys = table.keys(def.values) table.sort(keys) for _, key in pairs(keys) do p.push('<EnumValue') p.w('Name="%d"', key) if switches[key] then p.w('DisplayName="%s"', values[key]) p.w('Switch="%s" />', switches[key]) else p.w('DisplayName="%s" />', values[key]) end p.pop() end p.pop('</EnumProperty>') end function m.stringProperty(def) p.push('<StringProperty') m.baseProperty(def) p.w('Switch="%s" />', def.switch or "[value]") p.pop() end function m.stringListProperty(def) p.push('<StringListProperty') m.baseProperty(def) p.w('Separator="%s"', def.separator or " ") p.w('Switch="%s" />', def.switch or "[value]") p.pop() end --- -- Implementations of individual elements. --- function m.additionalDependencies(r) p.push('<StringListProperty') p.w('Name="AdditionalDependencies"') p.w('DisplayName="Additional Dependencies"') p.w('IncludeInCommandLine="False"') p.w('Visible="false" />') p.pop() end function m.additionalOptions(r) p.push('<StringProperty') p.w('Subtype="AdditionalOptions"') p.w('Name="AdditionalOptions"') p.w('Category="Command Line">') p.push('<StringProperty.DisplayName>') p.w('<sys:String>Additional Options</sys:String>') p.pop('</StringProperty.DisplayName>') p.push('<StringProperty.Description>') p.w('<sys:String>Additional Options</sys:String>') p.pop('</StringProperty.Description>') p.pop('</StringProperty>') end function m.afterTargets(r) p.push('<DynamicEnumProperty') p.w('Name="%sAfterTargets"', r.name) p.w('Category="General"') p.w('EnumProvider="Targets"') p.w('IncludeInCommandLine="False">') p.push('<DynamicEnumProperty.DisplayName>') p.w('<sys:String>Execute After</sys:String>') p.pop('</DynamicEnumProperty.DisplayName>') p.push('<DynamicEnumProperty.Description>') p.w('<sys:String>Specifies the targets for the build customization to run after.</sys:String>') p.pop('</DynamicEnumProperty.Description>') p.push('<DynamicEnumProperty.ProviderSettings>') p.push('<NameValuePair') p.w('Name="Exclude"') p.w('Value="^%sAfterTargets|^Compute" />', r.name) p.pop() p.pop('</DynamicEnumProperty.ProviderSettings>') p.push('<DynamicEnumProperty.DataSource>') p.push('<DataSource') p.w('Persistence="ProjectFile"') p.w('ItemType=""') p.w('HasConfigurationCondition="true" />') p.pop() p.pop('</DynamicEnumProperty.DataSource>') p.pop('</DynamicEnumProperty>') end function m.beforeTargets(r) p.push('<DynamicEnumProperty') p.w('Name="%sBeforeTargets"', r.name) p.w('Category="General"') p.w('EnumProvider="Targets"') p.w('IncludeInCommandLine="False">') p.push('<DynamicEnumProperty.DisplayName>') p.w('<sys:String>Execute Before</sys:String>') p.pop('</DynamicEnumProperty.DisplayName>') p.push('<DynamicEnumProperty.Description>') p.w('<sys:String>Specifies the targets for the build customization to run before.</sys:String>') p.pop('</DynamicEnumProperty.Description>') p.push('<DynamicEnumProperty.ProviderSettings>') p.push('<NameValuePair') p.w('Name="Exclude"') p.w('Value="^%sBeforeTargets|^Compute" />', r.name) p.pop() p.pop('</DynamicEnumProperty.ProviderSettings>') p.push('<DynamicEnumProperty.DataSource>') p.push('<DataSource') p.w('Persistence="ProjectFile"') p.w('HasConfigurationCondition="true" />') p.pop() p.pop('</DynamicEnumProperty.DataSource>') p.pop('</DynamicEnumProperty>') end function m.commandLineTemplate(r) p.push('<StringProperty') p.w('Name="CommandLineTemplate"') p.w('DisplayName="Command Line"') p.w('Visible="False"') p.w('IncludeInCommandLine="False" />') p.pop() end function m.contentType(r) p.push('<ContentType') p.w('Name="%s"', r.name) p.w('DisplayName="%s"', r.display or r.name) p.w('ItemType="%s" />', r.name) p.pop() end function m.dataSource(r) p.push('<Rule.DataSource>') p.push('<DataSource') p.w('Persistence="ProjectFile"') p.w('ItemType="%s" />', r.name) p.pop() p.pop('</Rule.DataSource>') end function m.executionDescription(r) p.push('<StringProperty') p.w('Name="ExecutionDescription"') p.w('DisplayName="Execution Description"') p.w('Visible="False"') p.w('IncludeInCommandLine="False" />') p.pop() end function m.fileExtension(r) p.push('<FileExtension') p.w('Name="*%s"', r.fileextension) p.w('ContentType="%s" />', r.name) p.pop() end function m.inputs(r) p.push('<StringListProperty') p.w('Name="Inputs"') p.w('Category="Command Line"') p.w('IsRequired="true"') p.w('Switch=" ">') p.push('<StringListProperty.DataSource>') p.push('<DataSource') p.w('Persistence="ProjectFile"') p.w('ItemType="%s"', r.name) p.w('SourceType="Item" />') p.pop() p.pop('</StringListProperty.DataSource>') p.pop('</StringListProperty>') end function m.outputs(r) p.push('<StringListProperty') p.w('Name="Outputs"') p.w('DisplayName="Outputs"') p.w('Visible="False"') p.w('IncludeInCommandLine="False" />') p.pop() end function m.ruleItem(r) p.push('<ItemType') p.w('Name="%s"', r.name) p.w('DisplayName="%s" />', r.display or r.name) p.pop() end function m.projectSchemaDefinitions(r) p.push('<ProjectSchemaDefinitions xmlns="http://schemas.microsoft.com/build/2009/properties" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib">') end
bsd-3-clause
Scavenge/darkstar
scripts/zones/Talacca_Cove/npcs/_1l0.lua
9
1865
----------------------------------- -- Area: Talacca_Cove -- NPC: rock slab (corsair job flag quest) -- @pos -99 -7 -91 57 ----------------------------------- package.loaded["scripts/zones/Talacca_Cove/TextIDs"] = nil; package.loaded["scripts/globals/bcnm"] = nil; ----------------------------------- require("scripts/zones/Talacca_Cove/TextIDs"); require("scripts/globals/bcnm"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) LuckOfTheDraw = player:getVar("LuckOfTheDraw"); if (LuckOfTheDraw ==4) then player:startEvent(0x0003); elseif (EventTriggerBCNM(player,npc)) then return; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0003) then -- complete corsair job flag quest player:setVar("LuckOfTheDraw",5); -- var will remain for af quests player:addItem(5493); player:messageSpecial(ITEM_OBTAINED,5493); player:delKeyItem(FORGOTTEN_HEXAGUN); player:unlockJob(17); player:messageSpecial(YOU_CAN_NOW_BECOME_A_CORSAIR); player:completeQuest(AHT_URHGAN,LUCK_OF_THE_DRAW); elseif (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/RuLude_Gardens/npcs/Trail_Markings.lua
7
3062
----------------------------------- -- Area: Rulude Gardens -- NPC: Trail Markings -- Dynamis-Jeuno Enter -- @pos 35 9 -51 243 ----------------------------------- package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/dynamis"); require("scripts/zones/RuLude_Gardens/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if bit.band(player:getVar("Dynamis_Status"),1) == 1 then player:startEvent(0x2720); -- cs with Cornelia elseif (player:getVar("DynaJeuno_Win") == 1) then player:startEvent(0x272a,HYDRA_CORPS_TACTICAL_MAP); -- Win CS elseif (player:hasKeyItem(VIAL_OF_SHROUDED_SAND)) then local firstDyna = 0; local realDay = os.time(); local dynaWaitxDay = player:getVar("dynaWaitxDay"); local dynaUniqueID = GetServerVariable("[DynaJeuno]UniqueID"); if (checkFirstDyna(player,4)) then -- First Dyna-Jeuno => CS firstDyna = 1; end if (player:getMainLvl() < DYNA_LEVEL_MIN) then player:messageSpecial(PLAYERS_HAVE_NOT_REACHED_LEVEL,DYNA_LEVEL_MIN); elseif ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or (player:getVar("DynamisID") == dynaUniqueID and dynaUniqueID > 0)) then player:startEvent(0x271c,4,firstDyna,0,BETWEEN_2DYNA_WAIT_TIME,64,VIAL_OF_SHROUDED_SAND,4236,4237); else dayRemaining = math.floor(((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) - realDay)/3456); player:messageSpecial(YOU_CANNOT_ENTER_DYNAMIS,dayRemaining,4); end else player:messageSpecial(UNUSUAL_ARRANGEMENT_LEAVES); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("updateRESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("finishRESULT: %u",option); if (csid == 0x2720) then player:addKeyItem(VIAL_OF_SHROUDED_SAND); player:messageSpecial(KEYITEM_OBTAINED,VIAL_OF_SHROUDED_SAND); player:setVar("Dynamis_Status",bit.band(player:getVar("Dynamis_Status"),bit.bnot(1))); elseif (csid == 0x272a) then player:setVar("DynaJeuno_Win",0); elseif (csid == 0x271c and option == 0) then if (checkFirstDyna(player,4)) then player:setVar("Dynamis_Status",bit.bor(player:getVar("Dynamis_Status"),16)); end player:setVar("enteringDynamis",1); player:setPos(48.930,10.002,-71.032,195,0xBC); end end;
gpl-3.0
kankaristo/premake-core
tests/actions/make/cs/test_flags.lua
16
1106
-- -- tests/actions/make/cs/test_flags.lua -- Tests compiler and linker flags for C# Makefiles. -- Copyright (c) 2013 Jason Perkins and the Premake project -- local suite = test.declare("make_cs_flags") local make = premake.make local cs = premake.make.cs local project = premake.project -- -- Setup -- local wks, prj function suite.setup() wks, prj = test.createWorkspace() end local function prepare() local cfg = test.getconfig(prj, "Debug") make.csFlags(cfg, premake.tools.dotnet) end -- -- Should return an empty assignment if nothing has been specified. -- function suite.isEmptyAssignment_onNoSettings() prepare() test.capture [[ FLAGS = /noconfig ]] end -- -- If the Unsafe flag has been set, it should be specified. -- function suite.onUnsafe() clr "Unsafe" prepare() test.capture [[ FLAGS = /unsafe /noconfig ]] end -- -- If an application icon has been set, it should be specified. -- function suite.onApplicationIcon() icon "MyProject.ico" prepare() test.capture [[ FLAGS = /noconfig /win32icon:"MyProject.ico" ]] end
bsd-3-clause
Scavenge/darkstar
scripts/zones/Empyreal_Paradox/mobs/Prishe.lua
23
2622
----------------------------------- -- Area: Empyreal Paradox -- MOB: Prishe -- Chains of Promathia 8-4 BCNM Fight ----------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/zones/Empyreal_Paradox/TextIDs"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) mob:addMod(MOD_REGAIN, 30); end ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobRoam ----------------------------------- function onMobRoam(mob) local wait = mob:getLocalVar("wait"); local ready = mob:getLocalVar("ready"); if (ready == 0 and wait > 240) then local baseID = 16924673 + (mob:getBattlefield():getBattlefieldNumber() - 1) * 2 if (GetMobAction(baseID) ~= ACTION_NONE) then mob:entityAnimationPacket("prov"); mob:messageText(mob, PRISHE_TEXT); else mob:entityAnimationPacket("prov"); mob:messageText(mob, PRISHE_TEXT + 1); baseID = baseID + 1; end mob:setLocalVar("ready", baseID); mob:setLocalVar("wait", 0); elseif (ready > 0) then mob:addEnmity(GetMobByID(ready),0,1); else mob:setLocalVar("wait", wait+3); end end; ----------------------------------- -- onMobEngaged Action ----------------------------------- function onMobEngaged(mob, target) mob:useMobAbility(1487); mob:addStatusEffectEx(EFFECT_SILENCE,0,0,0,5) end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) if (mob:getHPP() == 0 and mob:getLocalVar("Raise") == 1) then mob:entityAnimationPacket("sp00"); mob:messageText(mob, PRISHE_TEXT + 3); mob:addHP(mob:getMaxHP()); mob:addMP(mob:getMaxMP()); mob:setLocalVar("Raise", 0); mob:stun(3000); elseif (mob:getHPP() < 70 and mob:getLocalVar("HF") == 0) then mob:useMobAbility(1485); mob:messageText(mob, PRISHE_TEXT + 6); mob:setLocalVar("HF", 1); elseif (mob:getHPP() < 30 and mob:getLocalVar("Bene") == 0) then mob:useMobAbility(1486); mob:messageText(mob, PRISHE_TEXT + 7); mob:setLocalVar("Bene", 1); end -- mob:setStatus(0); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) mob:messageText(mob, PRISHE_TEXT + 2); end;
gpl-3.0
Scavenge/darkstar
scripts/globals/items/m&p_dumpling.lua
12
1257
----------------------------------------- -- ID: 5641 -- Item: M&P Dumpling -- Food Effect: 3Min, All Races ----------------------------------------- -- Intelligence 5 -- Agility -5 -- MP 30 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,180,5641); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 30); target:addMod(MOD_INT, 5); target:addMod(MOD_AGI, -5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 30); target:delMod(MOD_INT, 5); target:delMod(MOD_AGI, -5); end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Abyssea-Misareaux/npcs/qm6.lua
14
1354
----------------------------------- -- Zone: Abyssea-Misareaux -- NPC: qm6 (???) -- Spawns Ironclad Observer -- @pos ? ? ? 216 ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --[[ if (trade:hasItemQty(3090,1) and trade:getItemCount() == 1) then -- Player has all the required items. if (GetMobAction(17662469) == ACTION_NONE) then -- Mob not already spawned from this SpawnMob(17662469):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:tradeComplete(); end end ]] end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(1010, 3090); -- Inform player what items they need. end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
flux-framework/flux-core
src/bindings/lua/Test/Builder.lua
8
9606
-- -- lua-TestMore : <http://fperrad.github.com/lua-TestMore/> -- local debug = require 'debug' local io = require 'io' local os = require 'os' local error = error local gsub = require 'string'.gsub local match = require 'string'.match local pairs = pairs local pcall = pcall local print = print local rawget = rawget local setmetatable = setmetatable local tconcat = require 'table'.concat local tonumber = tonumber local tostring = tostring local type = type local table = table _ENV = nil local m = {} local testout = io and io.stdout local testerr = io and (io.stderr or io.stdout) function m.puts (f, str) f:write(str) end local function _print_to_fh (self, f, ...) if f then local msg = tconcat({...}) gsub(msg, "\n", "\n" .. self.indent) m.puts(f, self.indent .. msg .. "\n") else print(self.indent, ...) end end local function _print (self, ...) _print_to_fh(self, self:output(), ...) end local function print_comment (self, f, ...) local arg = {...} for k, v in pairs(arg) do arg[k] = tostring(v) end local msg = tconcat(arg) msg = gsub(msg, "\n", "\n# ") msg = gsub(msg, "\n# \n", "\n#\n") msg = gsub(msg, "\n# $", '') _print_to_fh(self, f, "# ", msg) end function m.create () local o = { data = setmetatable({}, { __index = m }), } setmetatable(o, { __index = function (t, k) return rawget(t, 'data')[k] end, __newindex = function (t, k, v) rawget(o, 'data')[k] = v end, }) o:reset() return o end local test function m.new () test = test or m.create() return test end local function in_todo (self) return self.todo_upto >= self.curr_test end function m:child (name) if self.child_name then error("You already have a child named (" .. self.child_name .. " running") end local child = m.create() child.indent = self.indent .. ' ' child.out_file = self.out_file child.fail_file = in_todo(self) and self.todo_file or self.fail_file child.todo_file = self.todo_file child.parent = self self.child_name = name return child end local function plan_handled (self) return self.have_plan or self.no_plan or self._skip_all end function m:subtest (name, func) if type(func) ~= 'function' then error("subtest()'s second argument must be a function") end self:diag('Subtest: ' .. name) local child = self:child(name) local parent = self.data self.data = child.data local r, msg = pcall(func) child.data = self.data self.data = parent if not r and not child._skip_all then error(msg, 0) end if not plan_handled(child) then child:done_testing() end child:finalize() end function m:finalize () if not self.parent then return end if self.child_name then error("Can't call finalize() with child (" .. self.child_name .. " active") end local parent = self.parent local name = parent.child_name parent.child_name = nil if self._skip_all then parent:skip(self._skip_all) elseif self.curr_test == 0 then parent:ok(false, "No tests run for subtest \"" .. name .. "\"", 2) else parent:ok(self.is_passing, name, 2) end self.parent = nil end function m:cleanup (func) table.insert (self._cleanup, func) end function m:reset () self.curr_test = 0 self._done_testing = false self.expected_tests = 0 self.is_passing = true self.todo_upto = -1 self.todo_reason = nil self.have_plan = false self.no_plan = false self._skip_all = false self.have_output_plan = false self.indent = '' self.parent = false self.child_name = false self._cleanup = {} self:reset_outputs() end local function _output_plan (self, max, directive, reason) if self.have_output_plan then error("The plan was already output") end local out = "1.." .. tostring(max) if directive then out = out .. " # " .. directive end if reason then out = out .. " " .. reason end _print(self, out) self.have_output_plan = true end function m:plan (arg) if self.have_plan then error("You tried to plan twice") end if type(arg) == 'string' and arg == 'no_plan' then self.have_plan = true self.no_plan = true return true elseif type(arg) ~= 'number' then error("Need a number of tests") elseif arg < 0 then error("Number of tests must be a positive integer. You gave it '" .. tostring(arg) .."'.") else self.expected_tests = arg self.have_plan = true _output_plan(self, arg) return arg end end function m:done_testing (num_tests) if num_tests then self.no_plan = false end num_tests = num_tests or self.curr_test if self._done_testing then tb:ok(false, "done_testing() was already called") return end self._done_testing = true if self.expected_tests > 0 and num_tests ~= self.expected_tests then self:ok(false, "planned to run " .. self.expected_tests .. " but done_testing() expects " .. num_tests) else self.expected_tests = num_tests end if not self.have_output_plan then _output_plan(self, num_tests) end self.have_plan = true -- The wrong number of tests were run if self.expected_tests ~= self.curr_test then self.is_passing = false end -- No tests were run if self.curr_test == 0 then self.is_passing = false end if not self.is_passing then os.exit (1) end for _,func in pairs (self._cleanup) do func () end end function m:has_plan () if self.expected_tests > 0 then return self.expected_tests end if self.no_plan then return 'no_plan' end return nil end function m:skip_all (reason) if self.have_plan then error("You tried to plan twice") end self._skip_all = reason _output_plan(self, 0, 'SKIP', reason) if self.parent then error("skip_all in child", 0) end os.exit(0) end local function _check_is_passing_plan (self) local plan = self:has_plan() if not plan or not tonumber(plan) then return end if plan < self.curr_test then self.is_passing = false end end function m:ok (test, name, level) if self.child_name then name = name or 'unnamed test' self.is_passing = false error("Cannot run test (" .. name .. ") with active children") end name = name or '' level = level or 0 self.curr_test = self.curr_test + 1 name = tostring(name) if match(name, '^[%d%s]+$') then self:diag(" You named your test '" .. name .."'. You shouldn't use numbers for your test names." .. "\n Very confusing.") end local out = '' if not test then out = "not " end out = out .. "ok " .. tostring(self.curr_test) if name ~= '' then out = out .. " - " .. name end if self.todo_reason and in_todo(self) then out = out .. " # TODO " .. self.todo_reason end _print(self, out) if not test then local msg = in_todo(self) and "Failed (TODO)" or "Failed" local info = debug and debug.getinfo(3 + level) if info then local file = info.short_src local line = info.currentline self:diag(" " .. msg .. " test (" .. file .. " at line " .. tostring(line) .. ")") else self:diag(" " .. msg .. " test") end end if not test and not in_todo(self) then self.is_passing = false end _check_is_passing_plan(self) end function m:BAIL_OUT (reason) local out = "Bail out!" if reason then out = out .. " " .. reason end _print(self, out) os.exit(255) end function m:current_test (num) if num then self.curr_test = num end return self.curr_test end function m:todo (reason, count) count = count or 1 self.todo_upto = self.curr_test + count self.todo_reason = reason end function m:skip (reason) local name = "# skip" if reason then name = name .. " " .. reason end self:ok(true, name, 1) end function m:todo_skip (reason) local name = "# TODO & SKIP" if reason then name = name .. " " .. reason end self:ok(false, name, 1) end function m:skip_rest (reason) for i = self.curr_test, self.expected_tests do tb:skip(reason) end end local function diag_file (self) if in_todo(self) then return self:todo_output() else return self:failure_output() end end function m:diag (...) print_comment(self, diag_file(self), ...) end function m:note (...) print_comment(self, self:output(), ...) end function m:output (f) if f then self.out_file = f end return self.out_file end function m:failure_output (f) if f then self.fail_file = f end return self.fail_file end function m:todo_output (f) if f then self.todo_file = f end return self.todo_file end function m:reset_outputs () self:output(testout) self:failure_output(testerr) self:todo_output(testout) end return m -- -- Copyright (c) 2009-2012 Francois Perrad -- -- This library is licensed under the terms of the MIT/X11 license, -- like Lua itself. --
lgpl-3.0
Scavenge/darkstar
scripts/zones/East_Ronfaure/mobs/Carrion_Worm.lua
14
1036
----------------------------------- -- Area: East Ronfaure -- MOB: Carrion Worm ----------------------------------- require("scripts/globals/fieldsofvalor"); require("scripts/zones/East_Ronfaure/MobIDs"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) checkRegime(player,mob,65,1); end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) local mobID = mob:getID(); if (Bigmouth_Billy_PH[mobID] ~= nil) then local ToD = GetServerVariable("[POP]Bigmouth_Billy"); if (ToD <= os.time(t) and GetMobAction(Bigmouth_Billy) == 0) then if (math.random(1,15) == 5) then UpdateNMSpawnPoint(Bigmouth_Billy); GetMobByID(Bigmouth_Billy):setRespawnTime(GetMobRespawnTime(mobID)); SetServerVariable("[PH]Bigmouth_Billy", mobID); DeterMob(mobID, true); end end end end;
gpl-3.0
yriveiro/nvim-files
lua/plugins/configs/cmp.lua
1
4178
local ok, cmp = pcall(require, 'cmp') if not ok then local u = require 'utils' u.nok_plugin 'cmp' return end local ok, luasnip = pcall(require, 'luasnip') if not ok then local u = require 'utils' u.nok_plugin 'luasnip' return end local ok, lspkind = pcall(require, 'lspkind') if not ok then local u = require 'utils' u.nok_plugin 'lspkind' return end local icons = { Class = 'ﴯ', Color = '', Constant = '', Constructor = '⌘', Enum = '', EnumMember = '', Event = '', Field = 'ﰠ', File = '', Folder = '', Function = '', Interface = '', Keyword = '', Method = '', Module = '', Operator = '', Property = 'ﰠ', Reference = '', Snippet = '', Struct = 'פּ', Text = '', TypeParameter = '', Unit = '', Value = '', Variable = '', } local menu = { buffer = 'Buffer', nvim_lsp = 'LSP', luasnip = 'Luasnip', nvim_lua = 'Lua', path = 'Path', cmdline = 'Command', nvim_lsp_signature_help = 'LSP Signature Help', cmdline_history = 'Command History', } -- Borrowed from AstroNvim configuration of cmp plugin local function has_words_before() local line, col = table.unpack(vim.api.nvim_win_get_cursor(0)) return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match '%s' == nil end cmp.setup { experimental = { ghost_text = true, }, completion = { completeopt = 'menu,menuone,noinsert', keyword_pattern = [[\%(-\?\d\+\%(\.\d\+\)\?\|\h\w*\%(-\w*\)*\)]], }, formatting = { fields = { 'kind', 'abbr', 'menu' }, format = lspkind.cmp_format { mode = 'symbol_text', -- show only symbol annotations maxwidth = 75, -- prevent the popup from showing more than provided characters (e.g 50 will not show more than 50 characters) ellipsis_char = '...', menu = menu, -- so that you can provide more controls on popup customization. (See [#30](https://github.com/onsails/lspkind-nvim/pull/30)) before = function(_, vim_item) vim_item.kind = icons[vim_item.kind] .. ' ' .. vim_item.kind return vim_item end, }, }, snippet = { expand = function(args) luasnip.lsp_expand(args.body) end, }, mapping = { ['<Up>'] = cmp.mapping.select_prev_item(), ['<Down>'] = cmp.mapping.select_next_item(), ['<C-Space>'] = cmp.mapping(cmp.mapping.complete(), { 'i', 's' }), ['<C-d>'] = cmp.mapping(cmp.mapping.scroll_docs(-1), { 'i', 'c' }), ['<C-f>'] = cmp.mapping(cmp.mapping.scroll_docs(1), { 'i', 'c' }), ['<C-q>'] = cmp.mapping.close(), ['<Tab>'] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_next_item() elseif luasnip.expandable() then luasnip.expand() elseif luasnip.expand_or_jumpable() then luasnip.expand_or_jump() elseif has_words_before() then cmp.complete() else fallback() end end, { 'i', 's' }), ['<S-Tab>'] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_prev_item() elseif luasnip.jumpable(-1) then luasnip.jump(-1) else fallback() end end, { 'i', 's' }), ['<CR>'] = cmp.mapping.confirm { select = true }, }, sources = { { name = 'nvim_lsp', priority = 900 }, -- { name = 'nvim_lsp_signature_help', priority = 1000 }, { name = 'luasnip', priority = 750 }, { name = 'buffer', option = { get_bufnrs = function() local bufs = {} for _, win in ipairs(vim.api.nvim_list_wins()) do bufs[vim.api.nvim_win_get_buf(win)] = true end return vim.tbl_keys(bufs) end, }, priority = 525, }, { name = 'path' }, { name = 'nvim_lua' }, }, preselect = cmp.PreselectMode.None, } cmp.setup.cmdline('/', { mapping = cmp.mapping.preset.cmdline(), sources = { { name = 'buffer' }, }, }) cmp.setup.cmdline(':', { mapping = cmp.mapping.preset.cmdline(), sources = cmp.config.sources { { name = 'cmdline' }, { name = 'cmdline_history' }, { name = 'path' }, }, })
mit
Kyklas/luci-proto-hso
modules/base/luasrc/cbi/datatypes.lua
62
6006
--[[ LuCI - Configuration Bind Interface - Datatype Tests (c) 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local fs = require "nixio.fs" local ip = require "luci.ip" local math = require "math" local util = require "luci.util" local tonumber, tostring, type, unpack, select = tonumber, tostring, type, unpack, select module "luci.cbi.datatypes" _M['or'] = function(v, ...) local i for i = 1, select('#', ...), 2 do local f = select(i, ...) local a = select(i+1, ...) if type(f) ~= "function" then if f == v then return true end i = i - 1 elseif f(v, unpack(a)) then return true end end return false end _M['and'] = function(v, ...) local i for i = 1, select('#', ...), 2 do local f = select(i, ...) local a = select(i+1, ...) if type(f) ~= "function" then if f ~= v then return false end i = i - 1 elseif not f(v, unpack(a)) then return false end end return true end function neg(v, ...) return _M['or'](v:gsub("^%s*!%s*", ""), ...) end function list(v, subvalidator, subargs) if type(subvalidator) ~= "function" then return false end local token for token in v:gmatch("%S+") do if not subvalidator(token, unpack(subargs)) then return false end end return true end function bool(val) if val == "1" or val == "yes" or val == "on" or val == "true" then return true elseif val == "0" or val == "no" or val == "off" or val == "false" then return true elseif val == "" or val == nil then return true end return false end function uinteger(val) local n = tonumber(val) if n ~= nil and math.floor(n) == n and n >= 0 then return true end return false end function integer(val) local n = tonumber(val) if n ~= nil and math.floor(n) == n then return true end return false end function ufloat(val) local n = tonumber(val) return ( n ~= nil and n >= 0 ) end function float(val) return ( tonumber(val) ~= nil ) end function ipaddr(val) return ip4addr(val) or ip6addr(val) end function ip4addr(val) if val then return ip.IPv4(val) and true or false end return false end function ip4prefix(val) val = tonumber(val) return ( val and val >= 0 and val <= 32 ) end function ip6addr(val) if val then return ip.IPv6(val) and true or false end return false end function ip6prefix(val) val = tonumber(val) return ( val and val >= 0 and val <= 128 ) end function port(val) val = tonumber(val) return ( val and val >= 0 and val <= 65535 ) end function portrange(val) local p1, p2 = val:match("^(%d+)%-(%d+)$") if p1 and p2 and port(p1) and port(p2) then return true else return port(val) end end function macaddr(val) if val and val:match( "^[a-fA-F0-9]+:[a-fA-F0-9]+:[a-fA-F0-9]+:" .. "[a-fA-F0-9]+:[a-fA-F0-9]+:[a-fA-F0-9]+$" ) then local parts = util.split( val, ":" ) for i = 1,6 do parts[i] = tonumber( parts[i], 16 ) if parts[i] < 0 or parts[i] > 255 then return false end end return true end return false end function hostname(val) if val and (#val < 254) and ( val:match("^[a-zA-Z_]+$") or (val:match("^[a-zA-Z0-9_][a-zA-Z0-9_%-%.]*[a-zA-Z0-9]$") and val:match("[^0-9%.]")) ) then return true end return false end function host(val) return hostname(val) or ipaddr(val) end function network(val) return uciname(val) or host(val) end function wpakey(val) if #val == 64 then return (val:match("^[a-fA-F0-9]+$") ~= nil) else return (#val >= 8) and (#val <= 63) end end function wepkey(val) if val:sub(1, 2) == "s:" then val = val:sub(3) end if (#val == 10) or (#val == 26) then return (val:match("^[a-fA-F0-9]+$") ~= nil) else return (#val == 5) or (#val == 13) end end function string(val) return true -- Everything qualifies as valid string end function directory( val, seen ) local s = fs.stat(val) seen = seen or { } if s and not seen[s.ino] then seen[s.ino] = true if s.type == "dir" then return true elseif s.type == "lnk" then return directory( fs.readlink(val), seen ) end end return false end function file( val, seen ) local s = fs.stat(val) seen = seen or { } if s and not seen[s.ino] then seen[s.ino] = true if s.type == "reg" then return true elseif s.type == "lnk" then return file( fs.readlink(val), seen ) end end return false end function device( val, seen ) local s = fs.stat(val) seen = seen or { } if s and not seen[s.ino] then seen[s.ino] = true if s.type == "chr" or s.type == "blk" then return true elseif s.type == "lnk" then return device( fs.readlink(val), seen ) end end return false end function uciname(val) return (val:match("^[a-zA-Z0-9_]+$") ~= nil) end function range(val, min, max) val = tonumber(val) min = tonumber(min) max = tonumber(max) if val ~= nil and min ~= nil and max ~= nil then return ((val >= min) and (val <= max)) end return false end function min(val, min) val = tonumber(val) min = tonumber(min) if val ~= nil and min ~= nil then return (val >= min) end return false end function max(val, max) val = tonumber(val) max = tonumber(max) if val ~= nil and max ~= nil then return (val <= max) end return false end function rangelength(val, min, max) val = tostring(val) min = tonumber(min) max = tonumber(max) if val ~= nil and min ~= nil and max ~= nil then return ((#val >= min) and (#val <= max)) end return false end function minlength(val, min) val = tostring(val) min = tonumber(min) if val ~= nil and min ~= nil then return (#val >= min) end return false end function maxlength(val, max) val = tostring(val) max = tonumber(max) if val ~= nil and max ~= nil then return (#val <= max) end return false end function phonedigit(val) return (val:match("^[0-9\*#!%.]+$") ~= nil) end
apache-2.0
Scavenge/darkstar
scripts/zones/LaLoff_Amphitheater/npcs/qm0_3.lua
17
1169
----------------------------------- -- Area: LaLoff_Amphitheater -- NPC: qm0 (warp player outside after they win fight) ------------------------------------- package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil; ------------------------------------- require("scripts/zones/LaLoff_Amphitheater/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0C); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdate CSID: %u",csid); -- printf("onUpdate RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinish CSID: %u",csid); -- printf("onFinish RESULT: %u",option); if (csid == 0x0C and option == 1) then player:setPos(-291.480,-42.088,-401.311,11,130); end end;
gpl-3.0
Kyklas/luci-proto-hso
libs/rpcc/luasrc/rpcc/ruci.lua
93
1432
--[[ LuCIRPCc (c) 2009 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local util = require "luci.util" local rawget, setmetatable = rawget, setmetatable local ipairs = ipairs --- Transparent UCI over RPC client. -- @cstyle instance module "luci.rpcc.ruci" local Proxy = util.class() --- Create a new UCI over RPC proxy. -- @param rpccl RPC client -- @return Network transparent UCI module function factory(rpccl) return { cursor = function(...) return Proxy(rpccl, rpccl:request("ruci.cursor", {...})) end, cursor_state = function(...) return Proxy(rpccl, rpccl:request("ruci.cursor_state", {...})) end } end function Proxy.__init__(self, rpccl, objid) self.__rpccl = rpccl self.__objid = objid setmetatable(self, { __index = function(self, key) return rawget(self, key) or Proxy[key] or function(self, ...) local argv = {self.__objid, ...} return self.__rpccl:request("ruci."..key, argv) end end }) end function Proxy.foreach(self, config, section, callback) local sections = self.__rpccl:request("ruci.foreach", {self.__objid, config, section}) if sections then for _, s in ipairs(sections) do callback(s) end return true else return false end end
apache-2.0
sil3ntboyy/TGuard1.0.0
plugins/arabic_lock.lua
4
1379
antiarabic = {}-- An empty table for solving multiple kicking problem do local function run(msg, matches) if is_momod(msg) then -- Ignore mods,owner,admins return end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)]['settings']['lock_arabic'] then if data[tostring(msg.to.id)]['settings']['lock_arabic'] == 'yes' then if is_whitelisted(msg.from.id) then return end if antiarabic[msg.from.id] == true then return end if msg.to.type == 'chat' then local receiver = get_receiver(msg) local username = msg.from.username local name = msg.from.first_name if username and is_super_group(msg) then send_large_msg(receiver , "Arabic&Persian is not allowed here\n@"..username.."["..msg.from.id.."]\nStatus: User kicked/msg deleted") else send_large_msg(receiver , "Arabic&Persian is not allowed here\nName: "..name.."["..msg.from.id.."]\nStatus: User kicked/msg deleted") end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked (arabic was locked) ") local chat_id = msg.to.id local user_id = msg.from.id kick_user(user_id, chat_id) end antiarabic[msg.from.id] = true end end return end local function cron() antiarabic = {} end return { patterns = { "([\216-\219][\128-\191])" }, run = run, cron = cron } end
gpl-2.0
Zero-K-Experiments/Zero-K-Experiments
LuaUI/Widgets/chili/Controls/screen.lua
2
7238
Screen = Object:Inherit{ --Screen = Control:Inherit{ classname = 'screen', x = 0, y = 0, width = 0, height = 0, preserveChildrenOrder = true, activeControl = nil, focusedControl = nil, hoveredControl = nil, currentTooltip = nil, _lastHoveredControl = nil, _lastClicked = Spring.GetTimer(), _lastClickedX = 0, _lastClickedY = 0, } local this = Screen local inherited = this.inherited --//============================================================================= function Screen:New(obj) local vsx,vsy = gl.GetViewSizes() if ((obj.width or -1) <= 0) then obj.width = vsx end if ((obj.height or -1) <= 0) then obj.height = vsy end obj = inherited.New(self,obj) TaskHandler.RequestGlobalDispose(obj) obj:RequestUpdate() return obj end function Screen:OnGlobalDispose(obj) if (UnlinkSafe(self.activeControl) == obj) then self.activeControl = nil end if (UnlinkSafe(self.hoveredControl) == obj) then self.hoveredControl = nil end if (UnlinkSafe(self._lastHoveredControl) == obj) then self._lastHoveredControl = nil end if (UnlinkSafe(self.focusedControl) == obj) then self.focusedControl = nil end end --//============================================================================= --FIXME add new coordspace Device (which does y-invert) function Screen:ParentToLocal(x,y) return x, y end function Screen:LocalToParent(x,y) return x, y end function Screen:LocalToScreen(x,y) return x, y end function Screen:ScreenToLocal(x,y) return x, y end function Screen:ScreenToClient(x,y) return x, y end function Screen:ClientToScreen(x,y) return x, y end function Screen:IsRectInView(x,y,w,h) return (x <= self.width) and (x + w >= 0) and (y <= self.height) and (y + h >= 0) end function Screen:IsVisibleOnScreen() return true end --//============================================================================= function Screen:Resize(w,h) self.width = w self.height = h self:CallChildren("RequestRealign") end --//============================================================================= function Screen:Update(...) --//FIXME create a passive MouseMove event and use it instead? self:RequestUpdate() local hoveredControl = UnlinkSafe(self.hoveredControl) local activeControl = UnlinkSafe(self.activeControl) if hoveredControl and (not activeControl) then local x, y = Spring.GetMouseState() y = select(2,gl.GetViewSizes()) - y local cx,cy = hoveredControl:ScreenToLocal(x, y) hoveredControl:MouseMove(cx, cy, 0, 0) end end function Screen:IsAbove(x,y,...) local activeControl = UnlinkSafe(self.activeControl) if activeControl then return true end y = select(2,gl.GetViewSizes()) - y local hoveredControl = inherited.IsAbove(self,x,y,...) --// tooltip if (UnlinkSafe(hoveredControl) ~= UnlinkSafe(self._lastHoveredControl)) then if self._lastHoveredControl then self._lastHoveredControl:MouseOut() end if hoveredControl then hoveredControl:MouseOver() end self.hoveredControl = MakeWeakLink(hoveredControl, self.hoveredControl) if (hoveredControl) then local control = hoveredControl --// find tooltip in hovered control or its parents while (not control.tooltip)and(control.parent) do control = control.parent end self.currentTooltip = control.tooltip else self.currentTooltip = nil end self._lastHoveredControl = self.hoveredControl elseif (self._lastHoveredControl) then self.currentTooltip = self._lastHoveredControl.tooltip end return (not not hoveredControl) end function Screen:MouseDown(x,y,...) y = select(2,gl.GetViewSizes()) - y local activeControl = inherited.MouseDown(self,x,y,...) self.activeControl = MakeWeakLink(activeControl, self.activeControl) if not CompareLinks(self.activeControl, self.focusedControl) then local focusedControl = UnlinkSafe(self.focusedControl) if focusedControl then focusedControl.state.focused = false focusedControl:FocusUpdate() --rename FocusLost() end self.focusedControl = nil if self.activeControl then self.focusedControl = MakeWeakLink(activeControl, self.focusedControl) self.focusedControl.state.focused = true self.focusedControl:FocusUpdate() --rename FocusGain() end end return (not not activeControl) end function Screen:MouseUp(x,y,...) y = select(2,gl.GetViewSizes()) - y local activeControl = UnlinkSafe(self.activeControl) if activeControl then local cx,cy = activeControl:ScreenToLocal(x,y) local now = Spring.GetTimer() local obj local hoveredControl = inherited.IsAbove(self,x,y,...) if CompareLinks(hoveredControl, activeControl) then --//FIXME send this to controls too, when they didn't `return self` in MouseDown! if (math.abs(x - self._lastClickedX)<3) and (math.abs(y - self._lastClickedY)<3) and (Spring.DiffTimers(now,self._lastClicked) < 0.45 ) --FIXME 0.45 := doubleClick time (use spring config?) then obj = activeControl:MouseDblClick(cx,cy,...) end if (obj == nil) then obj = activeControl:MouseClick(cx,cy,...) end end self._lastClicked = now self._lastClickedX = x self._lastClickedY = y obj = activeControl:MouseUp(cx,cy,...) or obj self.activeControl = nil return (not not obj) else return (not not inherited.MouseUp(self,x,y,...)) end end function Screen:MouseMove(x,y,dx,dy,...) y = select(2,gl.GetViewSizes()) - y local activeControl = UnlinkSafe(self.activeControl) if activeControl then local cx,cy = activeControl:ScreenToLocal(x,y) local obj = activeControl:MouseMove(cx,cy,dx,-dy,...) if (obj==false) then self.activeControl = nil elseif (not not obj)and(obj ~= activeControl) then self.activeControl = MakeWeakLink(obj, self.activeControl) return true else return true end end return (not not inherited.MouseMove(self,x,y,dx,-dy,...)) end function Screen:MouseWheel(x,y,...) y = select(2,gl.GetViewSizes()) - y local activeControl = UnlinkSafe(self.activeControl) if activeControl then local cx,cy = activeControl:ScreenToLocal(x,y) local obj = activeControl:MouseWheel(cx,cy,...) if (obj==false) then self.activeControl = nil elseif (not not obj)and(obj ~= activeControl) then self.activeControl = MakeWeakLink(obj, self.activeControl) return true else return true end end return (not not inherited.MouseWheel(self,x,y,...)) end function Screen:KeyPress(...) local focusedControl = UnlinkSafe(self.focusedControl) if focusedControl then return (not not focusedControl:KeyPress(...)) end return (not not inherited:KeyPress(...)) end function Screen:TextInput(...) local focusedControl = UnlinkSafe(self.focusedControl) if focusedControl then return (not not focusedControl:TextInput(...)) end return (not not inherited:TextInput(...)) end --//=============================================================================
gpl-2.0
Zero-K-Experiments/Zero-K-Experiments
LuaUI/Widgets/gfx_commands_fx.lua
6
15810
function widget:GetInfo() return { name = "Commands FX", desc = "Adds glow-pulses wherever commands are queued. Including mapmarks.", author = "Floris", date = "14.04.2014", license = "GNU GPL, v2 or later", layer = 2, enabled = true, } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- NOTE: STILL IN DEVELOPMENT! -- dont change without asking/permission please VFS.Include("LuaRules/Configs/customcmds.h.lua") -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local commandHistory = {} local commandHistoryCoords = {} -- this table is used to count cmd´s with same coordinates local commandCoordsRendered = {} -- this table is used to skip cmd´s that have the same coordinates local mapDrawNicknameTime = {} -- this table is used to filter out previous map drawing nicknames if user has drawn something new local mapEraseNicknameTime = {} -- local ownPlayerID = Spring.GetMyPlayerID() local commandCount = 0 local commandList = {} local spGetUnitPosition = Spring.GetUnitPosition local spGetCameraPosition = Spring.GetCameraPosition local spGetPlayerInfo = Spring.GetPlayerInfo local spTraceScreenRay = Spring.TraceScreenRay local spLoadCmdColorsConfig = Spring.LoadCmdColorsConfig local spGetTeamColor = Spring.GetTeamColor -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- options_path = 'Settings/Interface/Command Visibility'--/Formations' options_order = { 'lblformations', 'indicate_cf_v2', 'onClick'} options = { lblformations = { name = 'Formations', type = 'label'}, indicate_cf_v2 = { name = "Indicate for custom formations", desc = "Draw the command indication for commands given with custom formations.", type = 'bool', noHotkey = true, value = true }, onClick = { name = "Indicate for clicks", desc = "Draw the command indication for every click.", type = 'bool', noHotkey = true, value = false } } -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local OPTIONS = { showMapmarkFx = true, showMapmarkSpecNames = true, showMapmarkSpecIcons = false, -- showMapmarkFx must be true for this to work nicknameOpacityMultiplier = 6, -- multiplier applied to the given color opacity of the type: 'map_draw' scaleWithCamera = true, size = 28, opacity = 1, duration = 0.7, -- each type has its own duration, but this settings applies to all baseParts = 14, -- (note that if camera is distant the number of parts will be reduced, up to 6 as minimum) ringParts = 24, -- (note that if camera is distant the number of parts will be reduced, up to 6 as minimum) ringWidth = 2, ringStartSize = 4, ringScale = 0.75, reduceOverlapEffect = 0.08, -- when spotters have the same coordinates: reduce the opacity: 1 is no reducing while 0 is no adding types = { leftclick = { size = 0.58, duration = 1, baseColor = {1.00 ,0.50 ,0.00 ,0.28}, ringColor = {1.00 ,0.50 ,0.00 ,0.12} }, rightclick = { size = 0.58, duration = 1, baseColor = {1.00 ,0.75 ,0.00 ,0.25}, ringColor = {1.00 ,0.75 ,0.00 ,0.11} }, map_mark = { size = 2, duration = 4.5, baseColor = {1.00 ,1.00 ,1.00 ,0.40}, ringColor = {1.00 ,1.00 ,1.00 ,0.75} }, map_draw = { size = 0.63, duration = 1.4, baseColor = {1.00 ,1.00 ,1.00 ,0.15}, ringColor = {1.00 ,1.00 ,1.00 ,0.00} }, map_erase = { size = 2, duration = 3, baseColor = {1.00 ,1.00 ,1.00 ,0.13}, ringColor = {1.00 ,1.00 ,1.00 ,0.00} }, [CMD.MOVE] = { size = 1, duration = 1, baseColor = {0.00 ,1.00 ,0.00 ,0.25}, ringColor = {0.00 ,1.00 ,0.00 ,0.25} }, [CMD.FIGHT] = { size = 1.2, duration = 1, baseColor = {0.20 ,0.60 ,1.00 ,0.30}, ringColor = {0.20 ,0.60 ,1.00 ,0.40} }, [CMD.DGUN] = { size = 1.4, duration = 1, baseColor = {1.00 ,0.00 ,0.00 ,0.30}, ringColor = {1.00 ,0.00 ,0.00 ,0.40} }, [CMD.ATTACK] = { size = 1.4, duration = 1, baseColor = {1.00 ,0.00 ,0.00 ,0.30}, ringColor = {1.00 ,0.00 ,0.00 ,0.40} }, [CMD.PATROL] = { size = 1.4, duration = 1, baseColor = {0.40 ,0.40 ,1.00 ,0.30}, ringColor = {0.40 ,0.40 ,1.00 ,0.40} }, [CMD_JUMP] = { size = 1.2, duration = 1, baseColor = {0.00 ,1.00 ,1.00 ,0.25}, ringColor = {0.00 ,1.00 ,1.00 ,0.25} }, [CMD_PLACE_BEACON] = { size = 1.2, duration = 1, baseColor = {0.10 ,0.80 ,0.80 ,0.25}, ringColor = {0.10 ,0.80 ,0.80 ,0.25} }, [CMD_WAIT_AT_BEACON] = { size = 1.2, duration = 1, baseColor = {0.10 ,0.10 ,0.90 ,0.25}, ringColor = {0.10 ,0.10 ,0.90 ,0.25} }, [CMD_UNIT_SET_TARGET] = { size = 1.2, duration = 1, baseColor = {0.80 ,0.80 ,0.10 ,0.25}, ringColor = {0.80 ,0.80 ,0.10 ,0.25} }, [CMD_UNIT_SET_TARGET_CIRCLE] = { size = 1.2, duration = 1, baseColor = {0.80 ,0.80 ,0.10 ,0.25}, ringColor = {0.80 ,0.80 ,0.10 ,0.25} }, } } -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function Round(num, idp) local mult = 10^(idp or 0) return math.floor(num * mult + 0.5) / mult end local function DrawBaseGlow(parts, size, r,g,b,a) gl.Color(r,g,b,a) gl.Vertex(0, 0, 0) gl.Color(r,g,b,0) local radstep = (2.0 * math.pi) / parts for i = 0, parts do local a1 = (i * radstep) gl.Vertex(math.sin(a1)*size, 0, math.cos(a1)*size) end end local function DrawRingCircle(parts, ringSize, ringInnerSize, ringOuterSize, rRing,gRing,bRing,aRing) local radstep = (2.0 * math.pi) / parts for i = 1, parts do local a1 = (i * radstep) local a2 = ((i+1) * radstep) local a1Sin = math.sin(a1) local a2Sin = math.sin(a2) a1 = math.cos(a1) a2 = math.cos(a2) --(fadefrom) gl.Color(rRing,gRing,bRing,0) gl.Vertex(a2Sin*ringInnerSize, 0, a2*ringInnerSize) gl.Vertex(a1Sin*ringInnerSize, 0, a1*ringInnerSize) --(fadeto) gl.Color(rRing,gRing,bRing,aRing) gl.Vertex(a1Sin*ringSize, 0, a1*ringSize) gl.Vertex(a2Sin*ringSize, 0, a2*ringSize) --(fadefrom) gl.Color(rRing,gRing,bRing,aRing) gl.Vertex(a1Sin*ringSize, 0, a1*ringSize) gl.Vertex(a2Sin*ringSize, 0, a2*ringSize) --(fadeto) gl.Color(rRing,gRing,bRing,0) gl.Vertex(a2Sin*ringOuterSize, 0, a2*ringOuterSize) gl.Vertex(a1Sin*ringOuterSize, 0, a1*ringOuterSize) end end local function CircleVerticies(circleDivs) for i = 1, circleDivs do local theta = 2 * math.pi * i / circleDivs gl.Vertex(math.cos(theta), 0, math.sin(theta)) end end local function DrawGroundquad(wx,gy,wz,size) gl.TexCoord(0,0) gl.Vertex(wx-size,gy+size,wz-size) gl.TexCoord(0,1) gl.Vertex(wx-size,gy+size,wz+size) gl.TexCoord(1,1) gl.Vertex(wx+size,gy+size,wz+size) gl.TexCoord(1,0) gl.Vertex(wx+size,gy+size,wz-size) end local function AddCommandSpotter(cmdType, x, y, z, osClock, unitID, playerID) if not unitID then unitID = 0 end if not playerID then playerID = false end --local uniqueNumber = unitID..'_'..osClock .. math.random() --commandHistory[uniqueNumber] = { -- cmdType = cmdType, -- x = x, -- y = y, -- z = z, -- osClock = osClock, -- playerID = playerID --} commandCount = commandCount + 1 commandList[commandCount] = { cmdType = cmdType, x = x, y = y, z = z, osClock = osClock, playerID = playerID } if commandHistoryCoords[cmdType..x..y..z] then commandHistoryCoords[cmdType..x..y..z] = commandHistoryCoords[cmdType..x..y..z] + 1 else commandHistoryCoords[cmdType..x..y..z] = 1 end end ------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------ -- Engine Triggers ------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------ local circleDrawList function widget:Initialize() circleDrawList = gl.CreateList(gl.BeginEnd, GL.LINE_LOOP, CircleVerticies, 18) end function widget:MapDrawCmd(playerID, cmdType, x, y, z, a, b, c) local osClock = os.clock() if OPTIONS.showMapmarkFx then if cmdType == 'point' then AddCommandSpotter('map_mark', x, y, z, osClock, false, playerID) elseif cmdType == 'line' then mapDrawNicknameTime[playerID] = osClock AddCommandSpotter('map_draw', x, y, z, osClock, false, playerID) elseif cmdType == 'erase' then mapEraseNicknameTime[playerID] = osClock AddCommandSpotter('map_erase', x, y, z, osClock, false, playerID) end end end function widget:MousePress(x, y, button) if options.onClick.value then local traceType, tracedScreenRay = spTraceScreenRay(x, y, true) if button == 1 and tracedScreenRay and tracedScreenRay[3] then AddCommandSpotter('leftclick', tracedScreenRay[1], tracedScreenRay[2], tracedScreenRay[3], os.clock()) end if button == 3 and tracedScreenRay and tracedScreenRay[3] then AddCommandSpotter('rightclick', tracedScreenRay[1], tracedScreenRay[2], tracedScreenRay[3], os.clock()) end end end function widget:CommandNotify(cmdID, cmdParams, options) if type(cmdParams) == 'table' and #cmdParams >= 3 and OPTIONS.types[cmdID] then AddCommandSpotter(cmdID, cmdParams[1], cmdParams[2], cmdParams[3], os.clock()) end end function widget:UnitCommandNotify(unitID, cmdID, cmdParams, cmdOptions) if options.indicate_cf_v2.value then if type(cmdParams) == 'table' and #cmdParams >= 3 and OPTIONS.types[cmdID] then AddCommandSpotter(cmdID, cmdParams[1], cmdParams[2], cmdParams[3], os.clock(), unitID) end end end --function widget:GameFrame(f) -- AddCommandSpotter(CMD.MOVE, (f%25)*40+40, 48, (math.floor(f/25)%25)*40+40, os.clock()) --end function widget:DrawWorldPreUnit() local osClock = os.clock() --local camX, camY, camZ = spGetCameraPosition() gl.Blending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA) gl.DepthTest(false) commandCoordsRendered = {} local index = 1 while index <= commandCount do local cmdValue = commandList[index] --for cmdKey, cmdValue in pairs(commandHistory) do local clickOsClock = cmdValue.osClock local cmdType = cmdValue.cmdType local playerID = cmdValue.playerID local duration = OPTIONS.types[cmdType].duration * OPTIONS.duration -- remove when duration has passed if osClock - clickOsClock > duration then if commandHistoryCoords[cmdType..cmdValue.x..cmdValue.y..cmdValue.z] <= 1 then commandHistoryCoords[cmdType..cmdValue.x..cmdValue.y..cmdValue.z] = nil else commandHistoryCoords[cmdType..cmdValue.x..cmdValue.y..cmdValue.z] = commandHistoryCoords[cmdType..cmdValue.x..cmdValue.y..cmdValue.z] - 1 end --commandHistory[cmdKey] = nil commandList[index] = commandList[commandCount] commandList[commandCount] = nil commandCount = commandCount - 1 -- remove nicknames when user has drawn something new elseif OPTIONS.showMapmarkSpecNames and cmdType == 'map_draw' and mapDrawNicknameTime[playerID] ~= nil and clickOsClock < mapDrawNicknameTime[playerID] then --commandHistory[cmdKey] = nil commandList[index] = commandList[commandCount] commandList[commandCount] = nil commandCount = commandCount - 1 -- draw all elseif OPTIONS.types[cmdType].baseColor[4] > 0 or OPTIONS.types[cmdType].ringColor[4] > 0 then index = index + 1 if commandCoordsRendered[cmdType..cmdValue.x..cmdValue.y..cmdValue.z] == nil then commandCoordsRendered[cmdType..cmdValue.x..cmdValue.y..cmdValue.z] = true local alphaMultiplier = 1 + (OPTIONS.reduceOverlapEffect * (commandHistoryCoords[cmdType..cmdValue.x..cmdValue.y..cmdValue.z] - 1)) -- add a bit to the multiplier for each cmd issued on the same coords local size = OPTIONS.size * OPTIONS.types[cmdType].size local a = (1 - ((osClock - clickOsClock) / duration)) * OPTIONS.opacity * alphaMultiplier local baseColor = OPTIONS.types[cmdType].baseColor local ringColor = OPTIONS.types[cmdType].ringColor -- use player colors if cmdType == 'map_mark' or cmdType == 'map_draw' or cmdType == 'map_erase' then local _,_,spec,teamID = spGetPlayerInfo(playerID) local r,g,b = 1,1,1 if not spec then r,g,b = spGetTeamColor(teamID) end baseColor = {1,1,1,baseColor[4]} ringColor = {r,g,b,ringColor[4]} end local rRing = ringColor[1] local gRing = ringColor[2] local bRing = ringColor[3] local aRing = a * ringColor[4] local r = baseColor[1] local g = baseColor[2] local b = baseColor[3] a = a * baseColor[4] local ringSize = OPTIONS.ringStartSize + (size * OPTIONS.ringScale) * ((osClock - clickOsClock) / duration) --local ringInnerSize = ringSize - OPTIONS.ringWidth --local ringOuterSize = ringSize + OPTIONS.ringWidth gl.PushMatrix() gl.Translate(cmdValue.x, cmdValue.y, cmdValue.z) --local xDifference = camX - cmdValue.x --local yDifference = camY - cmdValue.y --local zDifference = camZ - cmdValue.z --local camDistance = math.sqrt(xDifference*xDifference + yDifference*yDifference + zDifference*zDifference) local camDistance = 4000 -- set scale (based on camera distance) local scale = 1 if OPTIONS.scaleWithCamera and camZ then scale = 0.82 + camDistance / 7500 gl.Scale(scale,scale,scale) end local parts = 8 -- base glow if baseColor[4] > 0 then --local parts = Round(((OPTIONS.baseParts - (camDistance / 800)) + (size / 20)) * scale) --if parts < 6 then parts = 6 end gl.BeginEnd(GL.TRIANGLE_FAN, DrawBaseGlow, parts, size, r,g,b,a) end -- ring circle: if aRing > 0 then --local parts = Round(((OPTIONS.ringParts - (camDistance / 800)) + (ringSize / 10)) * scale) ----parts = parts * (ringSize / (size*OPTIONS.ringScale)) -- this reduces parts when ring is little, but introduces temporary gaps when a part is added --if parts < 6 then parts = 6 end gl.Color(rRing,gRing,bRing,aRing) gl.Scale(ringSize,ringSize,ringSize) gl.LineWidth(OPTIONS.ringWidth) gl.CallList(circleDrawList) --gl.BeginEnd(GL.QUADS, DrawRingCircle, parts, ringSize, ringInnerSize, ringOuterSize, rRing,gRing,bRing,aRing) end -- draw + erase: nickname / draw icon if playerID and playerID ~= ownPlayerID and OPTIONS.showMapmarkSpecNames and (cmdType == 'map_draw' or cmdType == 'map_erase' and clickOsClock >= mapEraseNicknameTime[playerID]) then local nickname,_,spec = spGetPlayerInfo(playerID) if (spec) then gl.Color(r,g,b, a * OPTIONS.nicknameOpacityMultiplier) if OPTIONS.showMapmarkSpecIcons then if cmdType == 'map_draw' then gl.Texture('LuaUI/Images/commandsfx/pencil.png') else gl.Texture('LuaUI/Images/commandsfx/eraser.png') end local iconSize = 11 gl.BeginEnd(GL.QUADS,DrawGroundquad,iconSize,-iconSize,-iconSize,iconSize) gl.Texture(false) end gl.Billboard() gl.Text(nickname, 0, -28, 20, "cn") end end gl.PopMatrix() end end end gl.LineWidth(1) gl.Scale(1,1,1) gl.Color(1,1,1,1) end
gpl-2.0
xincun/nginx-openresty-windows
luajit-root/luajit/share/luajit-2.1.0-alpha/jit/dis_mips.lua
17
13221
---------------------------------------------------------------------------- -- LuaJIT MIPS disassembler module. -- -- Copyright (C) 2005-2013 Mike Pall. All rights reserved. -- Released under the MIT/X license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- This is a helper module used by the LuaJIT machine code dumper module. -- -- It disassembles all standard MIPS32R1/R2 instructions. -- Default mode is big-endian, but see: dis_mipsel.lua ------------------------------------------------------------------------------ local type = type local sub, byte, format = string.sub, string.byte, string.format local match, gmatch, gsub = string.match, string.gmatch, string.gsub local concat = table.concat local bit = require("bit") local band, bor, tohex = bit.band, bit.bor, bit.tohex local lshift, rshift, arshift = bit.lshift, bit.rshift, bit.arshift ------------------------------------------------------------------------------ -- Primary and extended opcode maps ------------------------------------------------------------------------------ local map_movci = { shift = 16, mask = 1, [0] = "movfDSC", "movtDSC", } local map_srl = { shift = 21, mask = 1, [0] = "srlDTA", "rotrDTA", } local map_srlv = { shift = 6, mask = 1, [0] = "srlvDTS", "rotrvDTS", } local map_special = { shift = 0, mask = 63, [0] = { shift = 0, mask = -1, [0] = "nop", _ = "sllDTA" }, map_movci, map_srl, "sraDTA", "sllvDTS", false, map_srlv, "sravDTS", "jrS", "jalrD1S", "movzDST", "movnDST", "syscallY", "breakY", false, "sync", "mfhiD", "mthiS", "mfloD", "mtloS", false, false, false, false, "multST", "multuST", "divST", "divuST", false, false, false, false, "addDST", "addu|moveDST0", "subDST", "subu|neguDS0T", "andDST", "orDST", "xorDST", "nor|notDST0", false, false, "sltDST", "sltuDST", false, false, false, false, "tgeSTZ", "tgeuSTZ", "tltSTZ", "tltuSTZ", "teqSTZ", false, "tneSTZ", } local map_special2 = { shift = 0, mask = 63, [0] = "maddST", "madduST", "mulDST", false, "msubST", "msubuST", [32] = "clzDS", [33] = "cloDS", [63] = "sdbbpY", } local map_bshfl = { shift = 6, mask = 31, [2] = "wsbhDT", [16] = "sebDT", [24] = "sehDT", } local map_special3 = { shift = 0, mask = 63, [0] = "extTSAK", [4] = "insTSAL", [32] = map_bshfl, [59] = "rdhwrTD", } local map_regimm = { shift = 16, mask = 31, [0] = "bltzSB", "bgezSB", "bltzlSB", "bgezlSB", false, false, false, false, "tgeiSI", "tgeiuSI", "tltiSI", "tltiuSI", "teqiSI", false, "tneiSI", false, "bltzalSB", "bgezalSB", "bltzallSB", "bgezallSB", false, false, false, false, false, false, false, false, false, false, false, "synciSO", } local map_cop0 = { shift = 25, mask = 1, [0] = { shift = 21, mask = 15, [0] = "mfc0TDW", [4] = "mtc0TDW", [10] = "rdpgprDT", [11] = { shift = 5, mask = 1, [0] = "diT0", "eiT0", }, [14] = "wrpgprDT", }, { shift = 0, mask = 63, [1] = "tlbr", [2] = "tlbwi", [6] = "tlbwr", [8] = "tlbp", [24] = "eret", [31] = "deret", [32] = "wait", }, } local map_cop1s = { shift = 0, mask = 63, [0] = "add.sFGH", "sub.sFGH", "mul.sFGH", "div.sFGH", "sqrt.sFG", "abs.sFG", "mov.sFG", "neg.sFG", "round.l.sFG", "trunc.l.sFG", "ceil.l.sFG", "floor.l.sFG", "round.w.sFG", "trunc.w.sFG", "ceil.w.sFG", "floor.w.sFG", false, { shift = 16, mask = 1, [0] = "movf.sFGC", "movt.sFGC" }, "movz.sFGT", "movn.sFGT", false, "recip.sFG", "rsqrt.sFG", false, false, false, false, false, false, false, false, false, false, "cvt.d.sFG", false, false, "cvt.w.sFG", "cvt.l.sFG", "cvt.ps.sFGH", false, false, false, false, false, false, false, false, false, "c.f.sVGH", "c.un.sVGH", "c.eq.sVGH", "c.ueq.sVGH", "c.olt.sVGH", "c.ult.sVGH", "c.ole.sVGH", "c.ule.sVGH", "c.sf.sVGH", "c.ngle.sVGH", "c.seq.sVGH", "c.ngl.sVGH", "c.lt.sVGH", "c.nge.sVGH", "c.le.sVGH", "c.ngt.sVGH", } local map_cop1d = { shift = 0, mask = 63, [0] = "add.dFGH", "sub.dFGH", "mul.dFGH", "div.dFGH", "sqrt.dFG", "abs.dFG", "mov.dFG", "neg.dFG", "round.l.dFG", "trunc.l.dFG", "ceil.l.dFG", "floor.l.dFG", "round.w.dFG", "trunc.w.dFG", "ceil.w.dFG", "floor.w.dFG", false, { shift = 16, mask = 1, [0] = "movf.dFGC", "movt.dFGC" }, "movz.dFGT", "movn.dFGT", false, "recip.dFG", "rsqrt.dFG", false, false, false, false, false, false, false, false, false, "cvt.s.dFG", false, false, false, "cvt.w.dFG", "cvt.l.dFG", false, false, false, false, false, false, false, false, false, false, "c.f.dVGH", "c.un.dVGH", "c.eq.dVGH", "c.ueq.dVGH", "c.olt.dVGH", "c.ult.dVGH", "c.ole.dVGH", "c.ule.dVGH", "c.df.dVGH", "c.ngle.dVGH", "c.deq.dVGH", "c.ngl.dVGH", "c.lt.dVGH", "c.nge.dVGH", "c.le.dVGH", "c.ngt.dVGH", } local map_cop1ps = { shift = 0, mask = 63, [0] = "add.psFGH", "sub.psFGH", "mul.psFGH", false, false, "abs.psFG", "mov.psFG", "neg.psFG", false, false, false, false, false, false, false, false, false, { shift = 16, mask = 1, [0] = "movf.psFGC", "movt.psFGC" }, "movz.psFGT", "movn.psFGT", false, false, false, false, false, false, false, false, false, false, false, false, "cvt.s.puFG", false, false, false, false, false, false, false, "cvt.s.plFG", false, false, false, "pll.psFGH", "plu.psFGH", "pul.psFGH", "puu.psFGH", "c.f.psVGH", "c.un.psVGH", "c.eq.psVGH", "c.ueq.psVGH", "c.olt.psVGH", "c.ult.psVGH", "c.ole.psVGH", "c.ule.psVGH", "c.psf.psVGH", "c.ngle.psVGH", "c.pseq.psVGH", "c.ngl.psVGH", "c.lt.psVGH", "c.nge.psVGH", "c.le.psVGH", "c.ngt.psVGH", } local map_cop1w = { shift = 0, mask = 63, [32] = "cvt.s.wFG", [33] = "cvt.d.wFG", } local map_cop1l = { shift = 0, mask = 63, [32] = "cvt.s.lFG", [33] = "cvt.d.lFG", } local map_cop1bc = { shift = 16, mask = 3, [0] = "bc1fCB", "bc1tCB", "bc1flCB", "bc1tlCB", } local map_cop1 = { shift = 21, mask = 31, [0] = "mfc1TG", false, "cfc1TG", "mfhc1TG", "mtc1TG", false, "ctc1TG", "mthc1TG", map_cop1bc, false, false, false, false, false, false, false, map_cop1s, map_cop1d, false, false, map_cop1w, map_cop1l, map_cop1ps, } local map_cop1x = { shift = 0, mask = 63, [0] = "lwxc1FSX", "ldxc1FSX", false, false, false, "luxc1FSX", false, false, "swxc1FSX", "sdxc1FSX", false, false, false, "suxc1FSX", false, "prefxMSX", false, false, false, false, false, false, false, false, false, false, false, false, false, false, "alnv.psFGHS", false, "madd.sFRGH", "madd.dFRGH", false, false, false, false, "madd.psFRGH", false, "msub.sFRGH", "msub.dFRGH", false, false, false, false, "msub.psFRGH", false, "nmadd.sFRGH", "nmadd.dFRGH", false, false, false, false, "nmadd.psFRGH", false, "nmsub.sFRGH", "nmsub.dFRGH", false, false, false, false, "nmsub.psFRGH", false, } local map_pri = { [0] = map_special, map_regimm, "jJ", "jalJ", "beq|beqz|bST00B", "bne|bnezST0B", "blezSB", "bgtzSB", "addiTSI", "addiu|liTS0I", "sltiTSI", "sltiuTSI", "andiTSU", "ori|liTS0U", "xoriTSU", "luiTU", map_cop0, map_cop1, false, map_cop1x, "beql|beqzlST0B", "bnel|bnezlST0B", "blezlSB", "bgtzlSB", false, false, false, false, map_special2, false, false, map_special3, "lbTSO", "lhTSO", "lwlTSO", "lwTSO", "lbuTSO", "lhuTSO", "lwrTSO", false, "sbTSO", "shTSO", "swlTSO", "swTSO", false, false, "swrTSO", "cacheNSO", "llTSO", "lwc1HSO", "lwc2TSO", "prefNSO", false, "ldc1HSO", "ldc2TSO", false, "scTSO", "swc1HSO", "swc2TSO", false, false, "sdc1HSO", "sdc2TSO", false, } ------------------------------------------------------------------------------ local map_gpr = { [0] = "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "sp", "r30", "ra", } ------------------------------------------------------------------------------ -- Output a nicely formatted line with an opcode and operands. local function putop(ctx, text, operands) local pos = ctx.pos local extra = "" if ctx.rel then local sym = ctx.symtab[ctx.rel] if sym then extra = "\t->"..sym end end if ctx.hexdump > 0 then ctx.out(format("%08x %s %-7s %s%s\n", ctx.addr+pos, tohex(ctx.op), text, concat(operands, ", "), extra)) else ctx.out(format("%08x %-7s %s%s\n", ctx.addr+pos, text, concat(operands, ", "), extra)) end ctx.pos = pos + 4 end -- Fallback for unknown opcodes. local function unknown(ctx) return putop(ctx, ".long", { "0x"..tohex(ctx.op) }) end local function get_be(ctx) local pos = ctx.pos local b0, b1, b2, b3 = byte(ctx.code, pos+1, pos+4) return bor(lshift(b0, 24), lshift(b1, 16), lshift(b2, 8), b3) end local function get_le(ctx) local pos = ctx.pos local b0, b1, b2, b3 = byte(ctx.code, pos+1, pos+4) return bor(lshift(b3, 24), lshift(b2, 16), lshift(b1, 8), b0) end -- Disassemble a single instruction. local function disass_ins(ctx) local op = ctx:get() local operands = {} local last = nil ctx.op = op ctx.rel = nil local opat = map_pri[rshift(op, 26)] while type(opat) ~= "string" do if not opat then return unknown(ctx) end opat = opat[band(rshift(op, opat.shift), opat.mask)] or opat._ end local name, pat = match(opat, "^([a-z0-9_.]*)(.*)") local altname, pat2 = match(pat, "|([a-z0-9_.|]*)(.*)") if altname then pat = pat2 end for p in gmatch(pat, ".") do local x = nil if p == "S" then x = map_gpr[band(rshift(op, 21), 31)] elseif p == "T" then x = map_gpr[band(rshift(op, 16), 31)] elseif p == "D" then x = map_gpr[band(rshift(op, 11), 31)] elseif p == "F" then x = "f"..band(rshift(op, 6), 31) elseif p == "G" then x = "f"..band(rshift(op, 11), 31) elseif p == "H" then x = "f"..band(rshift(op, 16), 31) elseif p == "R" then x = "f"..band(rshift(op, 21), 31) elseif p == "A" then x = band(rshift(op, 6), 31) elseif p == "M" then x = band(rshift(op, 11), 31) elseif p == "N" then x = band(rshift(op, 16), 31) elseif p == "C" then x = band(rshift(op, 18), 7) if x == 0 then x = nil end elseif p == "K" then x = band(rshift(op, 11), 31) + 1 elseif p == "L" then x = band(rshift(op, 11), 31) - last + 1 elseif p == "I" then x = arshift(lshift(op, 16), 16) elseif p == "U" then x = band(op, 0xffff) elseif p == "O" then local disp = arshift(lshift(op, 16), 16) operands[#operands] = format("%d(%s)", disp, last) elseif p == "X" then local index = map_gpr[band(rshift(op, 16), 31)] operands[#operands] = format("%s(%s)", index, last) elseif p == "B" then x = ctx.addr + ctx.pos + arshift(lshift(op, 16), 16)*4 + 4 ctx.rel = x x = "0x"..tohex(x) elseif p == "J" then x = band(ctx.addr + ctx.pos, 0xf0000000) + band(op, 0x03ffffff)*4 ctx.rel = x x = "0x"..tohex(x) elseif p == "V" then x = band(rshift(op, 8), 7) if x == 0 then x = nil end elseif p == "W" then x = band(op, 7) if x == 0 then x = nil end elseif p == "Y" then x = band(rshift(op, 6), 0x000fffff) if x == 0 then x = nil end elseif p == "Z" then x = band(rshift(op, 6), 1023) if x == 0 then x = nil end elseif p == "0" then if last == "r0" or last == 0 then local n = #operands operands[n] = nil last = operands[n-1] if altname then local a1, a2 = match(altname, "([^|]*)|(.*)") if a1 then name, altname = a1, a2 else name = altname end end end elseif p == "1" then if last == "ra" then operands[#operands] = nil end else assert(false) end if x then operands[#operands+1] = x; last = x end end return putop(ctx, name, operands) end ------------------------------------------------------------------------------ -- Disassemble a block of code. local function disass_block(ctx, ofs, len) if not ofs then ofs = 0 end local stop = len and ofs+len or #ctx.code stop = stop - stop % 4 ctx.pos = ofs - ofs % 4 ctx.rel = nil while ctx.pos < stop do disass_ins(ctx) end end -- Extended API: create a disassembler context. Then call ctx:disass(ofs, len). local function create(code, addr, out) local ctx = {} ctx.code = code ctx.addr = addr or 0 ctx.out = out or io.write ctx.symtab = {} ctx.disass = disass_block ctx.hexdump = 8 ctx.get = get_be return ctx end local function create_el(code, addr, out) local ctx = create(code, addr, out) ctx.get = get_le return ctx end -- Simple API: disassemble code (a string) at address and output via out. local function disass(code, addr, out) create(code, addr, out):disass() end local function disass_el(code, addr, out) create_el(code, addr, out):disass() end -- Return register name for RID. local function regname(r) if r < 32 then return map_gpr[r] end return "f"..(r-32) end -- Public module functions. return { create = create, create_el = create_el, disass = disass, disass_el = disass_el, regname = regname }
bsd-2-clause
vahidazizi/golbarg
libs/lua-redis.lua
1
35689
local redis = { _VERSION = 'redis-lua 2.0.4', _DESCRIPTION = 'A Lua client library for the redis key value storage system.', _COPYRIGHT = 'Copyright (C) 2009-2012 Daniele Alessandri', } -- The following line is used for backwards compatibility in order to keep the `Redis` -- global module name. Using `Redis` is now deprecated so you should explicitly assign -- the module to a local variable when requiring it: `local redis = require('redis')`. Redis = redis local unpack = _G.unpack or table.unpack local network, request, response = {}, {}, {} local defaults = { host = '127.0.0.1', port = 6379, tcp_nodelay = true, path = nil } local function merge_defaults(parameters) if parameters == nil then parameters = {} end for k, v in pairs(defaults) do if parameters[k] == nil then parameters[k] = defaults[k] end end return parameters end local function parse_boolean(v) if v == '1' or v == 'true' or v == 'TRUE' then return true elseif v == '0' or v == 'false' or v == 'FALSE' then return false else return nil end end local function toboolean(value) return value == 1 end local function sort_request(client, command, key, params) --[[ params = { by = 'weight_*', get = 'object_*', limit = { 0, 10 }, sort = 'desc', alpha = true, } ]] local query = { key } if params then if params.by then table.insert(query, 'BY') table.insert(query, params.by) end if type(params.limit) == 'table' then -- TODO: check for lower and upper limits table.insert(query, 'LIMIT') table.insert(query, params.limit[1]) table.insert(query, params.limit[2]) end if params.get then if (type(params.get) == 'table') then for _, getarg in pairs(params.get) do table.insert(query, 'GET') table.insert(query, getarg) end else table.insert(query, 'GET') table.insert(query, params.get) end end if params.sort then table.insert(query, params.sort) end if params.alpha == true then table.insert(query, 'ALPHA') end if params.store then table.insert(query, 'STORE') table.insert(query, params.store) end end request.multibulk(client, command, query) end local function zset_range_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_byscore_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.limit then table.insert(opts, 'LIMIT') table.insert(opts, options.limit.offset or options.limit[1]) table.insert(opts, options.limit.count or options.limit[2]) end if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_reply(reply, command, ...) local args = {...} local opts = args[4] if opts and (opts.withscores or string.lower(tostring(opts)) == 'withscores') then local new_reply = { } for i = 1, #reply, 2 do table.insert(new_reply, { reply[i], reply[i + 1] }) end return new_reply else return reply end end local function zset_store_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.weights and type(options.weights) == 'table' then table.insert(opts, 'WEIGHTS') for _, weight in ipairs(options.weights) do table.insert(opts, weight) end end if options.aggregate then table.insert(opts, 'AGGREGATE') table.insert(opts, options.aggregate) end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function mset_filter_args(client, command, ...) local args, arguments = {...}, {} if (#args == 1 and type(args[1]) == 'table') then for k,v in pairs(args[1]) do table.insert(arguments, k) table.insert(arguments, v) end else arguments = args end request.multibulk(client, command, arguments) end local function hash_multi_request_builder(builder_callback) return function(client, command, ...) local args, arguments = {...}, { } if #args == 2 then table.insert(arguments, args[1]) for k, v in pairs(args[2]) do builder_callback(arguments, k, v) end else arguments = args end request.multibulk(client, command, arguments) end end local function parse_info(response) local info = {} local current = info response:gsub('([^\r\n]*)\r\n', function(kv) if kv == '' then return end local section = kv:match('^# (%w+)$') if section then current = {} info[section:lower()] = current return end local k,v = kv:match(('([^:]*):([^:]*)'):rep(1)) if k:match('db%d+') then current[k] = {} v:gsub(',', function(dbkv) local dbk,dbv = kv:match('([^:]*)=([^:]*)') current[k][dbk] = dbv end) else current[k] = v end end) return info end local function load_methods(proto, commands) local client = setmetatable ({}, getmetatable(proto)) for cmd, fn in pairs(commands) do if type(fn) ~= 'function' then redis.error('invalid type for command ' .. cmd .. '(must be a function)') end client[cmd] = fn end for i, v in pairs(proto) do client[i] = v end return client end local function create_client(proto, client_socket, commands) local client = load_methods(proto, commands) client.error = redis.error client.network = { socket = client_socket, read = network.read, write = network.write, } client.requests = { multibulk = request.multibulk, } return client end -- ############################################################################ function network.write(client, buffer) local _, err = client.network.socket:send(buffer) if err then client.error(err) end end function network.read(client, len) if len == nil then len = '*l' end local line, err = client.network.socket:receive(len) if not err then return line else client.error('connection error: ' .. err) end end -- ############################################################################ function response.read(client) local payload = client.network.read(client) local prefix, data = payload:sub(1, -#payload), payload:sub(2) -- status reply if prefix == '+' then if data == 'OK' then return true elseif data == 'QUEUED' then return { queued = true } else return data end -- error reply elseif prefix == '-' then return client.error('redis error: ' .. data) -- integer reply elseif prefix == ':' then local number = tonumber(data) if not number then if res == 'nil' then return nil end client.error('cannot parse '..res..' as a numeric response.') end return number -- bulk reply elseif prefix == '$' then local length = tonumber(data) if not length then client.error('cannot parse ' .. length .. ' as data length') end if length == -1 then return nil end local nextchunk = client.network.read(client, length + 2) return nextchunk:sub(1, -3) -- multibulk reply elseif prefix == '*' then local count = tonumber(data) if count == -1 then return nil end local list = {} if count > 0 then local reader = response.read for i = 1, count do list[i] = reader(client) end end return list -- unknown type of reply else return client.error('unknown response prefix: ' .. prefix) end end -- ############################################################################ function request.raw(client, buffer) local bufferType = type(buffer) if bufferType == 'table' then client.network.write(client, table.concat(buffer)) elseif bufferType == 'string' then client.network.write(client, buffer) else client.error('argument error: ' .. bufferType) end end function request.multibulk(client, command, ...) local args = {...} local argsn = #args local buffer = { true, true } if argsn == 1 and type(args[1]) == 'table' then argsn, args = #args[1], args[1] end buffer[1] = '*' .. tostring(argsn + 1) .. "\r\n" buffer[2] = '$' .. #command .. "\r\n" .. command .. "\r\n" local table_insert = table.insert for _, argument in pairs(args) do local s_argument = tostring(argument) table_insert(buffer, '$' .. #s_argument .. "\r\n" .. s_argument .. "\r\n") end client.network.write(client, table.concat(buffer)) end -- ############################################################################ local function custom(command, send, parse) command = string.upper(command) return function(client, ...) send(client, command, ...) local reply = response.read(client) if type(reply) == 'table' and reply.queued then reply.parser = parse return reply else if parse then return parse(reply, command, ...) end return reply end end end local function command(command, opts) if opts == nil or type(opts) == 'function' then return custom(command, request.multibulk, opts) else return custom(command, opts.request or request.multibulk, opts.response) end end local define_command_impl = function(target, name, opts) local opts = opts or {} target[string.lower(name)] = custom( opts.command or string.upper(name), opts.request or request.multibulk, opts.response or nil ) end local undefine_command_impl = function(target, name) target[string.lower(name)] = nil end -- ############################################################################ local client_prototype = {} client_prototype.raw_cmd = function(client, buffer) request.raw(client, buffer .. "\r\n") return response.read(client) end -- obsolete client_prototype.define_command = function(client, name, opts) define_command_impl(client, name, opts) end -- obsolete client_prototype.undefine_command = function(client, name) undefine_command_impl(client, name) end client_prototype.quit = function(client) request.multibulk(client, 'QUIT') client.network.socket:shutdown() return true end client_prototype.shutdown = function(client) request.multibulk(client, 'SHUTDOWN') client.network.socket:shutdown() end -- Command pipelining client_prototype.pipeline = function(client, block) local requests, replies, parsers = {}, {}, {} local table_insert = table.insert local socket_write, socket_read = client.network.write, client.network.read client.network.write = function(_, buffer) table_insert(requests, buffer) end -- TODO: this hack is necessary to temporarily reuse the current -- request -> response handling implementation of redis-lua -- without further changes in the code, but it will surely -- disappear when the new command-definition infrastructure -- will finally be in place. client.network.read = function() return '+QUEUED' end local pipeline = setmetatable({}, { __index = function(env, name) local cmd = client[name] if not cmd then client.error('unknown redis command: ' .. name, 2) end return function(self, ...) local reply = cmd(client, ...) table_insert(parsers, #requests, reply.parser) return reply end end }) local success, retval = pcall(block, pipeline) client.network.write, client.network.read = socket_write, socket_read if not success then client.error(retval, 0) end client.network.write(client, table.concat(requests, '')) for i = 1, #requests do local reply, parser = response.read(client), parsers[i] if parser then reply = parser(reply) end table_insert(replies, i, reply) end return replies, #requests end -- Publish/Subscribe do local channels = function(channels) if type(channels) == 'string' then channels = { channels } end return channels end local subscribe = function(client, ...) request.multibulk(client, 'subscribe', ...) end local psubscribe = function(client, ...) request.multibulk(client, 'psubscribe', ...) end local unsubscribe = function(client, ...) request.multibulk(client, 'unsubscribe') end local punsubscribe = function(client, ...) request.multibulk(client, 'punsubscribe') end local consumer_loop = function(client) local aborting, subscriptions = false, 0 local abort = function() if not aborting then unsubscribe(client) punsubscribe(client) aborting = true end end return coroutine.wrap(function() while true do local message local response = response.read(client) if response[1] == 'pmessage' then message = { kind = response[1], pattern = response[2], channel = response[3], payload = response[4], } else message = { kind = response[1], channel = response[2], payload = response[3], } end if string.match(message.kind, '^p?subscribe$') then subscriptions = subscriptions + 1 end if string.match(message.kind, '^p?unsubscribe$') then subscriptions = subscriptions - 1 end if aborting and subscriptions == 0 then break end coroutine.yield(message, abort) end end) end client_prototype.pubsub = function(client, subscriptions) if type(subscriptions) == 'table' then if subscriptions.subscribe then subscribe(client, channels(subscriptions.subscribe)) end if subscriptions.psubscribe then psubscribe(client, channels(subscriptions.psubscribe)) end end return consumer_loop(client) end end -- Redis transactions (MULTI/EXEC) do local function identity(...) return ... end local emptytable = {} local function initialize_transaction(client, options, block, queued_parsers) local table_insert = table.insert local coro = coroutine.create(block) if options.watch then local watch_keys = {} for _, key in pairs(options.watch) do table_insert(watch_keys, key) end if #watch_keys > 0 then client:watch(unpack(watch_keys)) end end local transaction_client = setmetatable({}, {__index=client}) transaction_client.exec = function(...) client.error('cannot use EXEC inside a transaction block') end transaction_client.multi = function(...) coroutine.yield() end transaction_client.commands_queued = function() return #queued_parsers end assert(coroutine.resume(coro, transaction_client)) transaction_client.multi = nil transaction_client.discard = function(...) local reply = client:discard() for i, v in pairs(queued_parsers) do queued_parsers[i]=nil end coro = initialize_transaction(client, options, block, queued_parsers) return reply end transaction_client.watch = function(...) client.error('WATCH inside MULTI is not allowed') end setmetatable(transaction_client, { __index = function(t, k) local cmd = client[k] if type(cmd) == "function" then local function queuey(self, ...) local reply = cmd(client, ...) assert((reply or emptytable).queued == true, 'a QUEUED reply was expected') table_insert(queued_parsers, reply.parser or identity) return reply end t[k]=queuey return queuey else return cmd end end }) client:multi() return coro end local function transaction(client, options, coroutine_block, attempts) local queued_parsers, replies = {}, {} local retry = tonumber(attempts) or tonumber(options.retry) or 2 local coro = initialize_transaction(client, options, coroutine_block, queued_parsers) local success, retval if coroutine.status(coro) == 'suspended' then success, retval = coroutine.resume(coro) else -- do not fail if the coroutine has not been resumed (missing t:multi() with CAS) success, retval = true, 'empty transaction' end if #queued_parsers == 0 or not success then client:discard() assert(success, retval) return replies, 0 end local raw_replies = client:exec() if not raw_replies then if (retry or 0) <= 0 then client.error("MULTI/EXEC transaction aborted by the server") else --we're not quite done yet return transaction(client, options, coroutine_block, retry - 1) end end local table_insert = table.insert for i, parser in pairs(queued_parsers) do table_insert(replies, i, parser(raw_replies[i])) end return replies, #queued_parsers end client_prototype.transaction = function(client, arg1, arg2) local options, block if not arg2 then options, block = {}, arg1 elseif arg1 then --and arg2, implicitly options, block = type(arg1)=="table" and arg1 or { arg1 }, arg2 else client.error("Invalid parameters for redis transaction.") end if not options.watch then watch_keys = { } for i, v in pairs(options) do if tonumber(i) then table.insert(watch_keys, v) options[i] = nil end end options.watch = watch_keys elseif not (type(options.watch) == 'table') then options.watch = { options.watch } end if not options.cas then local tx_block = block block = function(client, ...) client:multi() return tx_block(client, ...) --can't wrap this in pcall because we're in a coroutine. end end return transaction(client, options, block) end end -- MONITOR context do local monitor_loop = function(client) local monitoring = true -- Tricky since the payload format changed starting from Redis 2.6. local pattern = '^(%d+%.%d+)( ?.- ?) ?"(%a+)" ?(.-)$' local abort = function() monitoring = false end return coroutine.wrap(function() client:monitor() while monitoring do local message, matched local response = response.read(client) local ok = response:gsub(pattern, function(time, info, cmd, args) message = { timestamp = tonumber(time), client = info:match('%d+.%d+.%d+.%d+:%d+'), database = tonumber(info:match('%d+')) or 0, command = cmd, arguments = args:match('.+'), } matched = true end) if not matched then client.error('Unable to match MONITOR payload: '..response) end coroutine.yield(message, abort) end end) end client_prototype.monitor_messages = function(client) return monitor_loop(client) end end -- ############################################################################ local function connect_tcp(socket, parameters) local host, port = parameters.host, tonumber(parameters.port) local ok, err = socket:connect(host, port) if not ok then redis.error('could not connect to '..host..':'..port..' ['..err..']') end socket:setoption('tcp-nodelay', parameters.tcp_nodelay) return socket end local function connect_unix(socket, parameters) local ok, err = socket:connect(parameters.path) if not ok then redis.error('could not connect to '..parameters.path..' ['..err..']') end return socket end local function create_connection(parameters) if parameters.socket then return parameters.socket end local perform_connection, socket if parameters.scheme == 'unix' then perform_connection, socket = connect_unix, require('socket.unix') assert(socket, 'your build of LuaSocket does not support UNIX domain sockets') else if parameters.scheme then local scheme = parameters.scheme assert(scheme == 'redis' or scheme == 'tcp', 'invalid scheme: '..scheme) end perform_connection, socket = connect_tcp, require('socket').tcp end return perform_connection(socket(), parameters) end -- ############################################################################ function redis.error(message, level) error(message, (level or 1) + 1) end function redis.connect(...) local args, parameters = {...}, nil if #args == 1 then if type(args[1]) == 'table' then parameters = args[1] else local uri = require('socket.url') parameters = uri.parse(select(1, ...)) if parameters.scheme then if parameters.query then for k, v in parameters.query:gmatch('([-_%w]+)=([-_%w]+)') do if k == 'tcp_nodelay' or k == 'tcp-nodelay' then parameters.tcp_nodelay = parse_boolean(v) end end end else parameters.host = parameters.path end end elseif #args > 1 then local host, port = unpack(args) parameters = { host = host, port = port } end local commands = redis.commands or {} if type(commands) ~= 'table' then redis.error('invalid type for the commands table') end local socket = create_connection(merge_defaults(parameters)) local client = create_client(client_prototype, socket, commands) return client end function redis.command(cmd, opts) return command(cmd, opts) end -- obsolete function redis.define_command(name, opts) define_command_impl(redis.commands, name, opts) end -- obsolete function redis.undefine_command(name) undefine_command_impl(redis.commands, name) end -- ############################################################################ -- Commands defined in this table do not take the precedence over -- methods defined in the client prototype table. redis.commands = { -- commands operating on the key space exists = command('EXISTS', { response = toboolean }), del = command('DEL'), type = command('TYPE'), rename = command('RENAME'), renamenx = command('RENAMENX', { response = toboolean }), expire = command('EXPIRE', { response = toboolean }), pexpire = command('PEXPIRE', { -- >= 2.6 response = toboolean }), expireat = command('EXPIREAT', { response = toboolean }), pexpireat = command('PEXPIREAT', { -- >= 2.6 response = toboolean }), ttl = command('TTL'), pttl = command('PTTL'), -- >= 2.6 move = command('MOVE', { response = toboolean }), dbsize = command('DBSIZE'), persist = command('PERSIST', { -- >= 2.2 response = toboolean }), keys = command('KEYS', { response = function(response) if type(response) == 'string' then -- backwards compatibility path for Redis < 2.0 local keys = {} response:gsub('[^%s]+', function(key) table.insert(keys, key) end) response = keys end return response end }), randomkey = command('RANDOMKEY', { response = function(response) if response == '' then return nil else return response end end }), sort = command('SORT', { request = sort_request, }), -- commands operating on string values set = command('SET'), setnx = command('SETNX', { response = toboolean }), setex = command('SETEX'), -- >= 2.0 psetex = command('PSETEX'), -- >= 2.6 mset = command('MSET', { request = mset_filter_args }), msetnx = command('MSETNX', { request = mset_filter_args, response = toboolean }), get = command('GET'), mget = command('MGET'), getset = command('GETSET'), incr = command('INCR'), incrby = command('INCRBY'), incrbyfloat = command('INCRBYFLOAT', { -- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), decr = command('DECR'), decrby = command('DECRBY'), append = command('APPEND'), -- >= 2.0 substr = command('SUBSTR'), -- >= 2.0 strlen = command('STRLEN'), -- >= 2.2 setrange = command('SETRANGE'), -- >= 2.2 getrange = command('GETRANGE'), -- >= 2.2 setbit = command('SETBIT'), -- >= 2.2 getbit = command('GETBIT'), -- >= 2.2 -- commands operating on lists rpush = command('RPUSH'), lpush = command('LPUSH'), llen = command('LLEN'), lrange = command('LRANGE'), ltrim = command('LTRIM'), lindex = command('LINDEX'), lset = command('LSET'), lrem = command('LREM'), lpop = command('LPOP'), rpop = command('RPOP'), rpoplpush = command('RPOPLPUSH'), blpop = command('BLPOP'), -- >= 2.0 brpop = command('BRPOP'), -- >= 2.0 rpushx = command('RPUSHX'), -- >= 2.2 lpushx = command('LPUSHX'), -- >= 2.2 linsert = command('LINSERT'), -- >= 2.2 brpoplpush = command('BRPOPLPUSH'), -- >= 2.2 -- commands operating on sets sadd = command('SADD'), srem = command('SREM'), spop = command('SPOP'), smove = command('SMOVE', { response = toboolean }), scard = command('SCARD'), sismember = command('SISMEMBER', { response = toboolean }), sinter = command('SINTER'), sinterstore = command('SINTERSTORE'), sunion = command('SUNION'), sunionstore = command('SUNIONSTORE'), sdiff = command('SDIFF'), sdiffstore = command('SDIFFSTORE'), smembers = command('SMEMBERS'), srandmember = command('SRANDMEMBER'), -- commands operating on sorted sets zadd = command('ZADD'), zincrby = command('ZINCRBY'), zrem = command('ZREM'), zrange = command('ZRANGE', { request = zset_range_request, response = zset_range_reply, }), zrevrange = command('ZREVRANGE', { request = zset_range_request, response = zset_range_reply, }), zrangebyscore = command('ZRANGEBYSCORE', { request = zset_range_byscore_request, response = zset_range_reply, }), zrevrangebyscore = command('ZREVRANGEBYSCORE', { -- >= 2.2 request = zset_range_byscore_request, response = zset_range_reply, }), zunionstore = command('ZUNIONSTORE', { -- >= 2.0 request = zset_store_request }), zinterstore = command('ZINTERSTORE', { -- >= 2.0 request = zset_store_request }), zcount = command('ZCOUNT'), zcard = command('ZCARD'), zscore = command('ZSCORE'), zremrangebyscore = command('ZREMRANGEBYSCORE'), zrank = command('ZRANK'), -- >= 2.0 zrevrank = command('ZREVRANK'), -- >= 2.0 zremrangebyrank = command('ZREMRANGEBYRANK'), -- >= 2.0 -- commands operating on hashes hset = command('HSET', { -- >= 2.0 response = toboolean }), hsetnx = command('HSETNX', { -- >= 2.0 response = toboolean }), hmset = command('HMSET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, k) table.insert(args, v) end), }), hincrby = command('HINCRBY'), -- >= 2.0 hincrbyfloat = command('HINCRBYFLOAT', {-- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), hget = command('HGET'), -- >= 2.0 hmget = command('HMGET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, v) end), }), hdel = command('HDEL'), -- >= 2.0 hexists = command('HEXISTS', { -- >= 2.0 response = toboolean }), hlen = command('HLEN'), -- >= 2.0 hkeys = command('HKEYS'), -- >= 2.0 hvals = command('HVALS'), -- >= 2.0 hgetall = command('HGETALL', { -- >= 2.0 response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }), -- connection related commands ping = command('PING', { response = function(response) return response == 'PONG' end }), echo = command('ECHO'), auth = command('AUTH'), select = command('SELECT'), -- transactions multi = command('MULTI'), -- >= 2.0 exec = command('EXEC'), -- >= 2.0 discard = command('DISCARD'), -- >= 2.0 watch = command('WATCH'), -- >= 2.2 unwatch = command('UNWATCH'), -- >= 2.2 -- publish - subscribe subscribe = command('SUBSCRIBE'), -- >= 2.0 unsubscribe = command('UNSUBSCRIBE'), -- >= 2.0 psubscribe = command('PSUBSCRIBE'), -- >= 2.0 punsubscribe = command('PUNSUBSCRIBE'), -- >= 2.0 publish = command('PUBLISH'), -- >= 2.0 -- redis scripting eval = command('EVAL'), -- >= 2.6 evalsha = command('EVALSHA'), -- >= 2.6 script = command('SCRIPT'), -- >= 2.6 -- remote server control commands bgrewriteaof = command('BGREWRITEAOF'), config = command('CONFIG', { -- >= 2.0 response = function(reply, command, ...) if (type(reply) == 'table') then local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end return reply end }), client = command('CLIENT'), -- >= 2.4 slaveof = command('SLAVEOF'), save = command('SAVE'), bgsave = command('BGSAVE'), lastsave = command('LASTSAVE'), flushdb = command('FLUSHDB'), flushall = command('FLUSHALL'), monitor = command('MONITOR'), time = command('TIME'), -- >= 2.6 slowlog = command('SLOWLOG', { -- >= 2.2.13 response = function(reply, command, ...) if (type(reply) == 'table') then local structured = { } for index, entry in ipairs(reply) do structured[index] = { id = tonumber(entry[1]), timestamp = tonumber(entry[2]), duration = tonumber(entry[3]), command = entry[4], } end return structured end return reply end }), info = command('INFO', { response = parse_info, }), } -- ############################################################################ return redis -- کد های پایین در ربات نشان داده نمیشوند -- @smsgolbarg1
gpl-3.0
xincun/nginx-openresty-windows
lua-resty-core-0.1.1/lib/resty/core/ctx.lua
9
1870
-- Copyright (C) Yichun Zhang (agentzh) local ffi = require 'ffi' local debug = require 'debug' local base = require "resty.core.base" local misc = require "resty.core.misc" local register_getter = misc.register_ngx_magic_key_getter local register_setter = misc.register_ngx_magic_key_setter local registry = debug.getregistry() local new_tab = base.new_tab local ref_in_table = base.ref_in_table local getfenv = getfenv local C = ffi.C local FFI_NO_REQ_CTX = base.FFI_NO_REQ_CTX local FFI_OK = base.FFI_OK ffi.cdef[[ int ngx_http_lua_ffi_get_ctx_ref(ngx_http_request_t *r); int ngx_http_lua_ffi_set_ctx_ref(ngx_http_request_t *r, int ref); ]] local _M = { _VERSION = base.version } local function get_ctx_table() local r = getfenv(0).__ngx_req if not r then return error("no request found") end local ctx_ref = C.ngx_http_lua_ffi_get_ctx_ref(r) if ctx_ref == FFI_NO_REQ_CTX then return error("no request ctx found") end local ctxs = registry.ngx_lua_ctx_tables if ctx_ref < 0 then local ctx = new_tab(0, 4) ctx_ref = ref_in_table(ctxs, ctx) if C.ngx_http_lua_ffi_set_ctx_ref(r, ctx_ref) ~= FFI_OK then return nil end return ctx end return ctxs[ctx_ref] end register_getter("ctx", get_ctx_table) local function set_ctx_table(ctx) local r = getfenv(0).__ngx_req if not r then return error("no request found") end local ctx_ref = C.ngx_http_lua_ffi_get_ctx_ref(r) if ctx_ref == FFI_NO_REQ_CTX then return error("no request ctx found") end local ctxs = registry.ngx_lua_ctx_tables if ctx_ref < 0 then ctx_ref = ref_in_table(ctxs, ctx) C.ngx_http_lua_ffi_set_ctx_ref(r, ctx_ref) return end ctxs[ctx_ref] = ctx end register_setter("ctx", set_ctx_table) return _M
bsd-2-clause
Kyklas/luci-proto-hso
modules/base/luasrc/dispatcher.lua
6
23596
--[[ LuCI - Dispatcher Description: The request dispatcher and module dispatcher generators FileId: $Id$ License: Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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. ]]-- --- LuCI web dispatcher. local fs = require "nixio.fs" local sys = require "luci.sys" local init = require "luci.init" local util = require "luci.util" local http = require "luci.http" local nixio = require "nixio", require "nixio.util" module("luci.dispatcher", package.seeall) context = util.threadlocal() uci = require "luci.model.uci" i18n = require "luci.i18n" _M.fs = fs authenticator = {} -- Index table local index = nil -- Fastindex local fi --- Build the URL relative to the server webroot from given virtual path. -- @param ... Virtual path -- @return Relative URL function build_url(...) local path = {...} local url = { http.getenv("SCRIPT_NAME") or "" } local k, v for k, v in pairs(context.urltoken) do url[#url+1] = "/;" url[#url+1] = http.urlencode(k) url[#url+1] = "=" url[#url+1] = http.urlencode(v) end local p for _, p in ipairs(path) do if p:match("^[a-zA-Z0-9_%-%.%%/,;]+$") then url[#url+1] = "/" url[#url+1] = p end end return table.concat(url, "") end --- Check whether a dispatch node shall be visible -- @param node Dispatch node -- @return Boolean indicating whether the node should be visible function node_visible(node) if node then return not ( (not node.title or #node.title == 0) or (not node.target or node.hidden == true) or (type(node.target) == "table" and node.target.type == "firstchild" and (type(node.nodes) ~= "table" or not next(node.nodes))) ) end return false end --- Return a sorted table of visible childs within a given node -- @param node Dispatch node -- @return Ordered table of child node names function node_childs(node) local rv = { } if node then local k, v for k, v in util.spairs(node.nodes, function(a, b) return (node.nodes[a].order or 100) < (node.nodes[b].order or 100) end) do if node_visible(v) then rv[#rv+1] = k end end end return rv end --- Send a 404 error code and render the "error404" template if available. -- @param message Custom error message (optional) -- @return false function error404(message) luci.http.status(404, "Not Found") message = message or "Not Found" require("luci.template") if not luci.util.copcall(luci.template.render, "error404") then luci.http.prepare_content("text/plain") luci.http.write(message) end return false end --- Send a 500 error code and render the "error500" template if available. -- @param message Custom error message (optional)# -- @return false function error500(message) luci.util.perror(message) if not context.template_header_sent then luci.http.status(500, "Internal Server Error") luci.http.prepare_content("text/plain") luci.http.write(message) else require("luci.template") if not luci.util.copcall(luci.template.render, "error500", {message=message}) then luci.http.prepare_content("text/plain") luci.http.write(message) end end return false end function authenticator.htmlauth(validator, accs, default) local user = luci.http.formvalue("luci_username") local pass = luci.http.formvalue("luci_password") if user and validator(user, pass) then return user end require("luci.i18n") require("luci.template") context.path = {} luci.template.render("sysauth", {duser=default, fuser=user}) return false end --- Dispatch an HTTP request. -- @param request LuCI HTTP Request object function httpdispatch(request, prefix) luci.http.context.request = request local r = {} context.request = r context.urltoken = {} local pathinfo = http.urldecode(request:getenv("PATH_INFO") or "", true) if prefix then for _, node in ipairs(prefix) do r[#r+1] = node end end local tokensok = true for node in pathinfo:gmatch("[^/]+") do local tkey, tval if tokensok then tkey, tval = node:match(";(%w+)=([a-fA-F0-9]*)") end if tkey then context.urltoken[tkey] = tval else tokensok = false r[#r+1] = node end end local stat, err = util.coxpcall(function() dispatch(context.request) end, error500) luci.http.close() --context._disable_memtrace() end --- Dispatches a LuCI virtual path. -- @param request Virtual path function dispatch(request) --context._disable_memtrace = require "luci.debug".trap_memtrace("l") local ctx = context ctx.path = request local conf = require "luci.config" assert(conf.main, "/etc/config/luci seems to be corrupt, unable to find section 'main'") local lang = conf.main.lang or "auto" if lang == "auto" then local aclang = http.getenv("HTTP_ACCEPT_LANGUAGE") or "" for lpat in aclang:gmatch("[%w-]+") do lpat = lpat and lpat:gsub("-", "_") if conf.languages[lpat] then lang = lpat break end end end require "luci.i18n".setlanguage(lang) local c = ctx.tree local stat if not c then c = createtree() end local track = {} local args = {} ctx.args = args ctx.requestargs = ctx.requestargs or args local n local token = ctx.urltoken local preq = {} local freq = {} for i, s in ipairs(request) do preq[#preq+1] = s freq[#freq+1] = s c = c.nodes[s] n = i if not c then break end util.update(track, c) if c.leaf then break end end if c and c.leaf then for j=n+1, #request do args[#args+1] = request[j] freq[#freq+1] = request[j] end end ctx.requestpath = ctx.requestpath or freq ctx.path = preq if track.i18n then i18n.loadc(track.i18n) end -- Init template engine if (c and c.index) or not track.notemplate then local tpl = require("luci.template") local media = track.mediaurlbase or luci.config.main.mediaurlbase if not pcall(tpl.Template, "themes/%s/header" % fs.basename(media)) then media = nil for name, theme in pairs(luci.config.themes) do if name:sub(1,1) ~= "." and pcall(tpl.Template, "themes/%s/header" % fs.basename(theme)) then media = theme end end assert(media, "No valid theme found") end local function _ifattr(cond, key, val) if cond then local env = getfenv(3) local scope = (type(env.self) == "table") and env.self return string.format( ' %s="%s"', tostring(key), luci.util.pcdata(tostring( val or (type(env[key]) ~= "function" and env[key]) or (scope and type(scope[key]) ~= "function" and scope[key]) or "" )) ) else return '' end end tpl.context.viewns = setmetatable({ write = luci.http.write; include = function(name) tpl.Template(name):render(getfenv(2)) end; translate = i18n.translate; translatef = i18n.translatef; export = function(k, v) if tpl.context.viewns[k] == nil then tpl.context.viewns[k] = v end end; striptags = util.striptags; pcdata = util.pcdata; media = media; theme = fs.basename(media); resource = luci.config.main.resourcebase; ifattr = function(...) return _ifattr(...) end; attr = function(...) return _ifattr(true, ...) end; }, {__index=function(table, key) if key == "controller" then return build_url() elseif key == "REQUEST_URI" then return build_url(unpack(ctx.requestpath)) else return rawget(table, key) or _G[key] end end}) end track.dependent = (track.dependent ~= false) assert(not track.dependent or not track.auto, "Access Violation\nThe page at '" .. table.concat(request, "/") .. "/' " .. "has no parent node so the access to this location has been denied.\n" .. "This is a software bug, please report this message at " .. "http://luci.subsignal.org/trac/newticket" ) if track.sysauth then local sauth = require "luci.sauth" local authen = type(track.sysauth_authenticator) == "function" and track.sysauth_authenticator or authenticator[track.sysauth_authenticator] local def = (type(track.sysauth) == "string") and track.sysauth local accs = def and {track.sysauth} or track.sysauth local sess = ctx.authsession local verifytoken = false if not sess then sess = luci.http.getcookie("sysauth") sess = sess and sess:match("^[a-f0-9]*$") verifytoken = true end local sdat = sauth.read(sess) local user if sdat then if not verifytoken or ctx.urltoken.stok == sdat.token then user = sdat.user end else local eu = http.getenv("HTTP_AUTH_USER") local ep = http.getenv("HTTP_AUTH_PASS") if eu and ep and luci.sys.user.checkpasswd(eu, ep) then authen = function() return eu end end end if not util.contains(accs, user) then if authen then ctx.urltoken.stok = nil local user, sess = authen(luci.sys.user.checkpasswd, accs, def) if not user or not util.contains(accs, user) then return else local sid = sess or luci.sys.uniqueid(16) if not sess then local token = luci.sys.uniqueid(16) sauth.reap() sauth.write(sid, { user=user, token=token, secret=luci.sys.uniqueid(16) }) ctx.urltoken.stok = token end luci.http.header("Set-Cookie", "sysauth=" .. sid.."; path="..build_url()) ctx.authsession = sid ctx.authuser = user end else luci.http.status(403, "Forbidden") return end else ctx.authsession = sess ctx.authuser = user end end if track.setgroup then luci.sys.process.setgroup(track.setgroup) end if track.setuser then luci.sys.process.setuser(track.setuser) end local target = nil if c then if type(c.target) == "function" then target = c.target elseif type(c.target) == "table" then target = c.target.target end end if c and (c.index or type(target) == "function") then ctx.dispatched = c ctx.requested = ctx.requested or ctx.dispatched end if c and c.index then local tpl = require "luci.template" if util.copcall(tpl.render, "indexer", {}) then return true end end if type(target) == "function" then util.copcall(function() local oldenv = getfenv(target) local module = require(c.module) local env = setmetatable({}, {__index= function(tbl, key) return rawget(tbl, key) or module[key] or oldenv[key] end}) setfenv(target, env) end) local ok, err if type(c.target) == "table" then ok, err = util.copcall(target, c.target, unpack(args)) else ok, err = util.copcall(target, unpack(args)) end assert(ok, "Failed to execute " .. (type(c.target) == "function" and "function" or c.target.type or "unknown") .. " dispatcher target for entry '/" .. table.concat(request, "/") .. "'.\n" .. "The called action terminated with an exception:\n" .. tostring(err or "(unknown)")) else local root = node() if not root or not root.target then error404("No root node was registered, this usually happens if no module was installed.\n" .. "Install luci-mod-admin-full and retry. " .. "If the module is already installed, try removing the /tmp/luci-indexcache file.") else error404("No page is registered at '/" .. table.concat(request, "/") .. "'.\n" .. "If this url belongs to an extension, make sure it is properly installed.\n" .. "If the extension was recently installed, try removing the /tmp/luci-indexcache file.") end end end --- Generate the dispatching index using the best possible strategy. function createindex() local path = luci.util.libpath() .. "/controller/" local suff = { ".lua", ".lua.gz" } if luci.util.copcall(require, "luci.fastindex") then createindex_fastindex(path, suff) else createindex_plain(path, suff) end end --- Generate the dispatching index using the fastindex C-indexer. -- @param path Controller base directory -- @param suffixes Controller file suffixes function createindex_fastindex(path, suffixes) index = {} if not fi then fi = luci.fastindex.new("index") for _, suffix in ipairs(suffixes) do fi.add(path .. "*" .. suffix) fi.add(path .. "*/*" .. suffix) end end fi.scan() for k, v in pairs(fi.indexes) do index[v[2]] = v[1] end end --- Generate the dispatching index using the native file-cache based strategy. -- @param path Controller base directory -- @param suffixes Controller file suffixes function createindex_plain(path, suffixes) local controllers = { } for _, suffix in ipairs(suffixes) do nixio.util.consume((fs.glob(path .. "*" .. suffix)), controllers) nixio.util.consume((fs.glob(path .. "*/*" .. suffix)), controllers) end if indexcache then local cachedate = fs.stat(indexcache, "mtime") if cachedate then local realdate = 0 for _, obj in ipairs(controllers) do local omtime = fs.stat(obj, "mtime") realdate = (omtime and omtime > realdate) and omtime or realdate end if cachedate > realdate then assert( sys.process.info("uid") == fs.stat(indexcache, "uid") and fs.stat(indexcache, "modestr") == "rw-------", "Fatal: Indexcache is not sane!" ) index = loadfile(indexcache)() return index end end end index = {} for i,c in ipairs(controllers) do local modname = "luci.controller." .. c:sub(#path+1, #c):gsub("/", ".") for _, suffix in ipairs(suffixes) do modname = modname:gsub(suffix.."$", "") end local mod = require(modname) assert(mod ~= true, "Invalid controller file found\n" .. "The file '" .. c .. "' contains an invalid module line.\n" .. "Please verify whether the module name is set to '" .. modname .. "' - It must correspond to the file path!") local idx = mod.index assert(type(idx) == "function", "Invalid controller file found\n" .. "The file '" .. c .. "' contains no index() function.\n" .. "Please make sure that the controller contains a valid " .. "index function and verify the spelling!") index[modname] = idx end if indexcache then local f = nixio.open(indexcache, "w", 600) f:writeall(util.get_bytecode(index)) f:close() end end --- Create the dispatching tree from the index. -- Build the index before if it does not exist yet. function createtree() if not index then createindex() end local ctx = context local tree = {nodes={}, inreq=true} local modi = {} ctx.treecache = setmetatable({}, {__mode="v"}) ctx.tree = tree ctx.modifiers = modi -- Load default translation require "luci.i18n".loadc("base") local scope = setmetatable({}, {__index = luci.dispatcher}) for k, v in pairs(index) do scope._NAME = k setfenv(v, scope) v() end local function modisort(a,b) return modi[a].order < modi[b].order end for _, v in util.spairs(modi, modisort) do scope._NAME = v.module setfenv(v.func, scope) v.func() end return tree end --- Register a tree modifier. -- @param func Modifier function -- @param order Modifier order value (optional) function modifier(func, order) context.modifiers[#context.modifiers+1] = { func = func, order = order or 0, module = getfenv(2)._NAME } end --- Clone a node of the dispatching tree to another position. -- @param path Virtual path destination -- @param clone Virtual path source -- @param title Destination node title (optional) -- @param order Destination node order value (optional) -- @return Dispatching tree node function assign(path, clone, title, order) local obj = node(unpack(path)) obj.nodes = nil obj.module = nil obj.title = title obj.order = order setmetatable(obj, {__index = _create_node(clone)}) return obj end --- Create a new dispatching node and define common parameters. -- @param path Virtual path -- @param target Target function to call when dispatched. -- @param title Destination node title -- @param order Destination node order value (optional) -- @return Dispatching tree node function entry(path, target, title, order) local c = node(unpack(path)) c.target = target c.title = title c.order = order c.module = getfenv(2)._NAME return c end --- Fetch or create a dispatching node without setting the target module or -- enabling the node. -- @param ... Virtual path -- @return Dispatching tree node function get(...) return _create_node({...}) end --- Fetch or create a new dispatching node. -- @param ... Virtual path -- @return Dispatching tree node function node(...) local c = _create_node({...}) c.module = getfenv(2)._NAME c.auto = nil return c end function _create_node(path) if #path == 0 then return context.tree end local name = table.concat(path, ".") local c = context.treecache[name] if not c then local last = table.remove(path) local parent = _create_node(path) c = {nodes={}, auto=true} -- the node is "in request" if the request path matches -- at least up to the length of the node path if parent.inreq and context.path[#path+1] == last then c.inreq = true end parent.nodes[last] = c context.treecache[name] = c end return c end -- Subdispatchers -- function _firstchild() local path = { unpack(context.path) } local name = table.concat(path, ".") local node = context.treecache[name] local lowest if node and node.nodes and next(node.nodes) then local k, v for k, v in pairs(node.nodes) do if not lowest or (v.order or 100) < (node.nodes[lowest].order or 100) then lowest = k end end end assert(lowest ~= nil, "The requested node contains no childs, unable to redispatch") path[#path+1] = lowest dispatch(path) end --- Alias the first (lowest order) page automatically function firstchild() return { type = "firstchild", target = _firstchild } end --- Create a redirect to another dispatching node. -- @param ... Virtual path destination function alias(...) local req = {...} return function(...) for _, r in ipairs({...}) do req[#req+1] = r end dispatch(req) end end --- Rewrite the first x path values of the request. -- @param n Number of path values to replace -- @param ... Virtual path to replace removed path values with function rewrite(n, ...) local req = {...} return function(...) local dispatched = util.clone(context.dispatched) for i=1,n do table.remove(dispatched, 1) end for i, r in ipairs(req) do table.insert(dispatched, i, r) end for _, r in ipairs({...}) do dispatched[#dispatched+1] = r end dispatch(dispatched) end end local function _call(self, ...) local func = getfenv()[self.name] assert(func ~= nil, 'Cannot resolve function "' .. self.name .. '". Is it misspelled or local?') assert(type(func) == "function", 'The symbol "' .. self.name .. '" does not refer to a function but data ' .. 'of type "' .. type(func) .. '".') if #self.argv > 0 then return func(unpack(self.argv), ...) else return func(...) end end --- Create a function-call dispatching target. -- @param name Target function of local controller -- @param ... Additional parameters passed to the function function call(name, ...) return {type = "call", argv = {...}, name = name, target = _call} end local _template = function(self, ...) require "luci.template".render(self.view) end --- Create a template render dispatching target. -- @param name Template to be rendered function template(name) return {type = "template", view = name, target = _template} end local function _cbi(self, ...) local cbi = require "luci.cbi" local tpl = require "luci.template" local http = require "luci.http" local config = self.config or {} local maps = cbi.load(self.model, ...) local state = nil for i, res in ipairs(maps) do res.flow = config local cstate = res:parse() if cstate and (not state or cstate < state) then state = cstate end end local function _resolve_path(path) return type(path) == "table" and build_url(unpack(path)) or path end if config.on_valid_to and state and state > 0 and state < 2 then http.redirect(_resolve_path(config.on_valid_to)) return end if config.on_changed_to and state and state > 1 then http.redirect(_resolve_path(config.on_changed_to)) return end if config.on_success_to and state and state > 0 then http.redirect(_resolve_path(config.on_success_to)) return end if config.state_handler then if not config.state_handler(state, maps) then return end end http.header("X-CBI-State", state or 0) if not config.noheader then tpl.render("cbi/header", {state = state}) end local redirect local messages local applymap = false local pageaction = true local parsechain = { } for i, res in ipairs(maps) do if res.apply_needed and res.parsechain then local c for _, c in ipairs(res.parsechain) do parsechain[#parsechain+1] = c end applymap = true end if res.redirect then redirect = redirect or res.redirect end if res.pageaction == false then pageaction = false end if res.message then messages = messages or { } messages[#messages+1] = res.message end end for i, res in ipairs(maps) do res:render({ firstmap = (i == 1), applymap = applymap, redirect = redirect, messages = messages, pageaction = pageaction, parsechain = parsechain }) end if not config.nofooter then tpl.render("cbi/footer", { flow = config, pageaction = pageaction, redirect = redirect, state = state, autoapply = config.autoapply }) end end --- Create a CBI model dispatching target. -- @param model CBI model to be rendered function cbi(model, config) return {type = "cbi", config = config, model = model, target = _cbi} end local function _arcombine(self, ...) local argv = {...} local target = #argv > 0 and self.targets[2] or self.targets[1] setfenv(target.target, self.env) target:target(unpack(argv)) end --- Create a combined dispatching target for non argv and argv requests. -- @param trg1 Overview Target -- @param trg2 Detail Target function arcombine(trg1, trg2) return {type = "arcombine", env = getfenv(), target = _arcombine, targets = {trg1, trg2}} end local function _form(self, ...) local cbi = require "luci.cbi" local tpl = require "luci.template" local http = require "luci.http" local maps = luci.cbi.load(self.model, ...) local state = nil for i, res in ipairs(maps) do local cstate = res:parse() if cstate and (not state or cstate < state) then state = cstate end end http.header("X-CBI-State", state or 0) tpl.render("header") for i, res in ipairs(maps) do res:render() end tpl.render("footer") end --- Create a CBI form model dispatching target. -- @param model CBI form model tpo be rendered function form(model) return {type = "cbi", model = model, target = _form} end --- Access the luci.i18n translate() api. -- @class function -- @name translate -- @param text Text to translate translate = i18n.translate --- No-op function used to mark translation entries for menu labels. -- This function does not actually translate the given argument but -- is used by build/i18n-scan.pl to find translatable entries. function _(text) return text end
apache-2.0
devwawi/VIP-TEAM_Wawi8
plugins/Welcome.lua
1
2301
do local function vipteam1(msg,matches) if matches[1] == "chat_add_user" then local vipteam = 'Welcome 😊👋 in the group👥🔕'..'\n'..'\n' ..'⚜ψøuƦ ภค๓є🔰:'..msg.action.user.first_name..'\n' ..'⚜ψøuƦ ยรєгภค๓є🔰:: @'..(msg.action.user.username or "Not")..'\n' ..'⚜ψøuƦ 🆔 : '..msg.action.user.id..'\n' ..'📱ψøuƦ ภย๓๒єг🔰: '..(msg.action.user.phone or "Not")..'\n' ..'🔻➖🔺➖🔻➖🔺➖🔻'..'\n' ..'⚜ɠг๏ยթ ภค๓є🔰: : '..msg.to.title..'\n' ..'⚜ɠг๏ยթ 🆔 : '..msg.to.id..'\n' ..'🔻➖🔺➖🔻➖🔺➖🔻'..'\n' ..'⚜ค๔๔є๔ ภค๓є🔰: '..msg.from.print_name..'\n' ..'⚜ค๔๔є๔ ยรєг🔰:: @'..(msg.from.username or "Not")..'\n' ..'⚜ค๔๔є๔ 🆔: '..msg.from.id..'\n' ..'⚜ค๔๔є๔ ภย๓๒єг🔰 : '..(msg.from.phone or "Not")..'\n' ..'🔻➖🔺➖🔻➖🔺➖🔻'..'\n' ..'📅 Date : '..os.date('!%A, %B %d, %Y*\n', timestamp) ..'🌐 Chaneel :@vipteam1'..'\n' return reply_msg(msg.id, vipteam, ok_cb, false) end if matches[1] == "chat_add_user_link" then local vipteam1 = 'Welcome 😊👋 in the group👥🔕'..'\n'..'\n' ..'⚜ψøuƦ ภค๓є🔰: '..msg.action.user.first_name..'\n' ..'⚜ψøuƦ ยรєгภค๓є🔰: @'..(msg.action.user.username or "Not")..'\n' ..'⚜ψøuƦ 🆔 : '..msg.action.user.id..'\n' ..'📱ψøuƦ ภย๓๒єг🔰: '..(msg.action.user.phone or "Not")..'\n' ..'🔻➖🔺➖🔻➖🔺➖🔻'..'\n' ..'⚜ɠг๏ยթ ภค๓є🔰: '..msg.to.title..'\n' ..'⚜ɠг๏ยթ 🆔 : '..msg.to.id..'\n' ..'🔻➖🔺➖🔻➖🔺➖🔻'..'\n' ..'📅 Date : '..os.date('!%A, %B %d, %Y*\n', timestamp) ..'🌐 Chaneel : @vipteam1'..'\n' return reply_msg(msg.id, vipteam1, ok_cb, false) end if matches[1] == "chat_del_user" then local bye_name = msg.action.user.first_name return '🚀🚏 bye my dear'..bye_name end end return { patterns = { "^!!tgservice (chat_add_user)$", "^!!tgservice (chat_add_user_link)$", "^!!tgservice (chat_del_user)$", }, run = vipteam1 } end
agpl-3.0
LORDMEHDI/testertard
plugins/owners.lua
1467
12478
local function lock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function show_group_settingsmod(msg, data, target) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function set_rules(target, rules) local data = load_data(_config.moderation.data) local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function set_description(target, about) local data = load_data(_config.moderation.data) local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function run(msg, matches) if msg.to.type ~= 'chat' then local chat_id = matches[1] local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) if matches[2] == 'ban' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't ban yourself" end ban_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3]) return 'User '..user_id..' banned' end if matches[2] == 'unban' then if tonumber(matches[3]) == tonumber(our_id) then return false end local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't unban yourself" end local hash = 'banned:'..matches[1] redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3]) return 'User '..user_id..' unbanned' end if matches[2] == 'kick' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't kick yourself" end kick_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3]) return 'User '..user_id..' kicked' end if matches[2] == 'clean' then if matches[3] == 'modlist' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end for k,v in pairs(data[tostring(matches[1])]['moderators']) do data[tostring(matches[1])]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist") end if matches[3] == 'rules' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'rules' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules") end if matches[3] == 'about' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'description' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] cleaned about") end end if matches[2] == "setflood" then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[3] data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]") return 'Group flood has been set to '..matches[3] end if matches[2] == 'lock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end end if matches[2] == 'unlock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] if matches[3] == 'name' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[3] == 'member' then local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end end if matches[2] == 'new' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local function callback (extra , success, result) local receiver = 'chat#'..matches[1] vardump(result) data[tostring(matches[1])]['settings']['set_link'] = result save_data(_config.moderation.data, data) return end local receiver = 'chat#'..matches[1] local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ") export_chat_link(receiver, callback, true) return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link" end end if matches[2] == 'get' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local group_link = data[tostring(matches[1])]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end end if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then local target = matches[2] local about = matches[3] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_description(target, about) end if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then local rules = matches[3] local target = matches[2] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rules(target, rules) end if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] local name = user_print_name(msg.from) savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]") rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then savelog(matches[2], "------") send_document("user#id".. msg.from.id,"./groups/logs/"..matches[2].."log.txt", ok_cb, false) end end end return { patterns = { "^[!/]owners (%d+) ([^%s]+) (.*)$", "^[!/]owners (%d+) ([^%s]+)$", "^[!/](changeabout) (%d+) (.*)$", "^[!/](changerules) (%d+) (.*)$", "^[!/](changename) (%d+) (.*)$", "^[!/](loggroup) (%d+)$" }, run = run }
gpl-2.0
tempbottle/tundra
examples/static-shared/tundra.lua
7
1119
Build { Env = { CPPDEFS = { { "SHARED"; Config = "*-*-*-shared" } }, }, Units = function () local lib_static = StaticLibrary { Name = "foo_static", Config = "*-*-*-static", Sources = { "lib.c" }, } local lib_shared = SharedLibrary { Name = "foo_shared", Config = "*-*-*-shared", Sources = { "lib.c" }, } local prog = Program { Name = "bar", Depends = { lib_static, lib_shared }, Sources = { "main.c" }, } Default(prog) end, Configs = { { Name = "macosx-gcc", DefaultOnHost = "macosx", Tools = { "gcc" }, }, { Name = "linux-gcc", DefaultOnHost = "linux", Tools = { "gcc" }, }, { Name = "win32-msvc", DefaultOnHost = "windows", Tools = { "msvc-vs2012" }, }, { Name = "win32-mingw", Tools = { "mingw" }, -- Link with the C++ compiler to get the C++ standard library. ReplaceEnv = { LD = "$(CXX)", }, }, }, Variants = { "debug", "release" }, SubVariants = { "static", "shared" }, }
gpl-3.0
rucas/derpfiles
neovim/lua/plugins/nvim-dap/init.lua
1
1587
local utils = require("utils") local present, dap = pcall(require, "dap") if not present then return end require("nvim-dap-virtual-text").setup() dap.adapters.python = { type = "executable", command = "/Users/lucas.rondenet/.pyenv/versions/neovim0.5/bin/python", args = { "-m", "debugpy.adapter" }, } -- TODO make better mappings for these utils.map("n", "<leader>dct", "<cmd>lua require('dap').continue()<cr>") utils.map("n", "<leader>dsv", "<cmd>lua require('dap').step_over()<cr>") utils.map("n", "<leader>dsi", "<cmd>lua require('dap').step_into()<cr>") utils.map("n", "<leader>dso", "<cmd>lua require('dap').step_out()<cr>") utils.map("n", "<leader>dtb", "<cmd>lua require('dap').toggle_breakpoint()<cr>") utils.map("n", "<leader>dsc", "<cmd>lua require('dap.ui.variables').scopes()<cr>") utils.map("n", "<leader>dhh", "<cmd>lua require('dap.ui.variables').hover()<cr>") utils.map("n", "<leader>dhv", "<cmd>lua require('dap.ui.varables').visual_hover()<cr>") utils.map("n", "<leader>duh", "<cmd>lua require('dap.ui.widgets').hover()<cr>") utils.map("n", "<leader>dsbr", '<cmd>lua require"dap".set_breakpoint(vim.fn.input("Breakpoint condition: "))<CR>') utils.map( "n", "<leader>dsbm", '<cmd>lua require"dap".set_breakpoint(nil, nil, vim.fn.input("Log point message: "))<CR>' ) utils.map("n", "<leader>dro", '<cmd>lua require"dap".repl.open()<CR>') utils.map("n", "<leader>drl", '<cmd>lua require"dap".repl.run_last()<CR>') dap.configurations.python = { { type = "python", request = "launch", name = "Launch file", program = "${workspaceFolder}/${file}", }, }
mit
Scavenge/darkstar
scripts/globals/items/piece_of_kusamochi_+1.lua
12
2086
----------------------------------------- -- ID: 6263 -- Item: kusamochi+1 -- Food Effect: 60 Min, All Races ----------------------------------------- -- HP + 30 (Pet & Master) -- Vitality + 4 (Pet & Master) -- Attack + 21% Cap: 77 (Pet & Master) Pet Cap: 120 -- Ranged Attack + 21% Cap: 77 (Pet & Master) Pet Cap: 120 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD)) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,6263); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 30) target:addMod(MOD_VIT, 4) target:addMod(MOD_FOOD_ATTP, 21) target:addMod(MOD_FOOD_ATT_CAP, 77) target:addMod(MOD_FOOD_RATTP, 21) target:addMod(MOD_FOOD_RATT_CAP, 77) target:addPetMod(MOD_HP, 30) target:addPetMod(MOD_VIT, 4) target:addPetMod(MOD_FOOD_ATTP, 21) target:addPetMod(MOD_FOOD_ATT_CAP, 120) target:addPetMod(MOD_FOOD_RATTP, 21) target:addPetMod(MOD_FOOD_RATT_CAP, 120) end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 30) target:delMod(MOD_VIT, 4) target:delMod(MOD_FOOD_ATTP, 21) target:delMod(MOD_FOOD_ATT_CAP, 77) target:delMod(MOD_FOOD_RATTP, 21) target:delMod(MOD_FOOD_RATT_CAP, 77) target:delPetMod(MOD_HP, 30) target:delPetMod(MOD_VIT, 4) target:delPetMod(MOD_FOOD_ATTP, 21) target:delPetMod(MOD_FOOD_ATT_CAP, 120) target:delPetMod(MOD_FOOD_RATTP, 21) target:delPetMod(MOD_FOOD_RATT_CAP, 120) end;
gpl-3.0
seblindfors/ConsolePort
ConsolePort_Keyboard/Components/Suggester.lua
1
1818
local Suggester, _, env = ConsolePortKeyboard.WordSuggester, ...; local widgetPool, suggestions = CreateFramePool('Button', Suggester, 'ConsolePortKeyboardWordButton'), {}; --------------------------------------------------------------- local MAX_DISPLAY_ENTRIES, WIDGET_HEIGHT = 8, 20; --------------------------------------------------------------- -- Auto correct handling --------------------------------------------------------------- local function OnSuggestionsUpdatedCallback(result, iterator) local widgets, i = wipe(suggestions), 1; for word, weight in iterator(result) do local widget, newObj = widgetPool:Acquire() widget.Text:SetText(word) widget:Show() widgets[i], i = widget, i + 1; if i > MAX_DISPLAY_ENTRIES then break end end Suggester:SetHeight(#widgets * WIDGET_HEIGHT) local prev; for i, widget in ipairs(widgets) do widget:SetPoint('TOP', prev or Suggester, prev and 'BOTTOM' or 'TOP', 0, 0) prev = widget; end Suggester:OnSuggestionsChanged(result, iterator) end function Suggester:OnWordChanged(word) widgetPool:ReleaseAll() env:GetSpellCorrectSuggestions(word, env.Dictionary, OnSuggestionsUpdatedCallback) end function Suggester:OnSuggestionsChanged(result, iterator) self.curIndex, self.maxIndex = 1, #suggestions; self:SetIndex(self.curIndex) end function Suggester:SetDelta(delta) if self.curIndex and self.maxIndex then self:SetIndex(Clamp(self.curIndex + delta, 1, self.maxIndex)) end end function Suggester:SetIndex(index) self.selectedWord, self.curIndex = nil, index; for i, widget in ipairs(suggestions) do widget.Hilite:SetAlpha(0) end local widget = suggestions[index]; if widget then widget.Hilite:SetAlpha(1) self.selectedWord = widget.Text:GetText() end end function Suggester:GetSuggestion() return self.selectedWord; end
artistic-2.0
MicroTrustRepos/microkernel
src/l4/pkg/ankh/doc/ankh.lua
2
3925
-- vi: set et package.path = "rom/?.lua"; require ("Aw"); local ldr = L4.default_loader; local ankh_vbus; local shm_morpork, shm_morping, shm_morpong; function ankh_channels() ankh_vbus = ldr:new_channel(); shm_morpork = ldr:create_namespace({}); shm_morping = ldr:create_namespace({}); shm_morpong = ldr:create_namespace({}); end function ankh_io() Aw.io({ankh = ankh_vbus}, "-vv", "rom/ankh.vbus"); end -- Start ANKH -- -- Parameters: -- iobus := an Io virtual PCI bus that contains the NIC devices -- you want to drive, may be an empty bus if you only -- want to use loopback -- nstab := a table containing (name->name) space mappings for -- the SHMC name spaces this server instance should -- have access to -- -- Returns: An Ankh service channel cap that you can then use to -- start clients. function ankh_server(iobus, nstab, ...) if type(nstab) ~= "table" then print("2nd parameter to ankh_server() must be a table!"); nstab = {}; end local ankh_chan = ldr:new_channel(); local ankh_caps = { rom = rom; -- ROM ankh_service = ankh_chan:svr(); -- Service cap vbus = iobus; -- The PCI bus }; -- and add all shm name spaces passed for k,v in pairs(nstab) do ankh_caps[k] = v; end ldr:startv({ caps = ankh_caps, log = {"ankh", "green"}, l4re_dbg = L4.Dbg.Warn }, "rom/ankh" ); return ankh_chan; end -- Start an ANKH client -- -- Parameters: -- binary := binary to start -- parameters := table of parameters to pass to the binary -- ankh_channel := service channel to open ankh session -- ankh_config := session configuration -- nstab := table of name->ns mappings this client should -- get access to (SHMC) function ankh_client(binary, parameters, env, ankh_channel, ankh_config, nstab) env.caps.ankh = ankh_channel:create(0, ankh_config); -- and add all shm name spaces passed for k,v in pairs(nstab) do env.caps[k] = v; end ldr:startv(env, binary, unpack(parameters)); end -- ================ GENERIC SETUP ==================== ankh_channels(); ankh_io(); local chan = ankh_server(ankh_vbus, {shm_morpork = shm_morpork:m("rws"), shm_morping = shm_morping:m("rws"), shm_morpong = shm_morpong:m("rws")} ); -- ================ CLIENT SETUP ==================== -- MORPORK --ankh_client("rom/morpork", -- { "shm_morpork", "16384" }, -- { caps = { rom = rom }, log = {"morpork", "cyan"} }, -- chan, -- "debug,promisc,device=eth0,shm=shm_morpork,bufsize=16384,phys_mac", -- { shm_morpork = shm_morpork:m("rws") } --); -- PINGPONG --ankh_client("rom/morping", -- { "shm_morping" }, -- { caps = { rom = rom }, log = {"morping", "Yellow"} }, -- chan, -- "debug,promisc,device=lo,shm=shm_morping,bufsize=2048", -- { shm_morping = shm_morping:m("rws") } --); --ankh_client("rom/morpong", -- { "shm_morpong" }, -- { caps = { rom = rom }, log = {"morpong", "yellow"} }, -- chan, -- "debug,promisc,device=lo,shm=shm_morpong,bufsize=2048", -- { shm_morpong = shm_morpong:m("rws") } --); -- WGET ankh_client("rom/wget_clnt", { "--shm", "shm_morpork", "--bufsize", "16384", "-v", "http://de.archive.ubuntu.com/ubuntu-releases/lucid/ubuntu-10.04-desktop-i386.iso" }, { caps = { rom = rom }, log = {"wget", "cyan"} }, chan, "debug,promisc,device=eth0,shm=shm_morpork,bufsize=16384,phys_mac", { shm_morpork = shm_morpork:m("rws") } );
gpl-2.0
Scavenge/darkstar
scripts/globals/weaponskills/heavy_shot.lua
15
1354
----------------------------------- -- Heavy Shot -- Marksmanship weapon skill -- Skill Level: 225 -- Delivers a single-hit attack. Chance of params.critical varies with TP. -- Aligned with the Flame Gorget & Light Gorget. -- Aligned with the Flame Belt & Light Belt. -- Element: None -- Modifiers: AGI:30% -- 100%TP 200%TP 300%TP -- 3.50 3.50 3.50 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 1; params.ftp100 = 3.5; params.ftp200 = 3.5; params.ftp300 = 3.5; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.3; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.1; params.crit200 = 0.3; params.crit300 = 0.5; params.canCrit = true; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.agi_wsc = 0.7; end local damage, criticalHit, tpHits, extraHits = doRangedWeaponskill(player, target, wsID, params, tp, primary); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Scavenge/darkstar
scripts/globals/spells/silence.lua
6
1269
----------------------------------------- -- Spell: Silence ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local effectType = EFFECT_SILENCE; if (target:hasStatusEffect(effectType)) then spell:setMsg(75); -- no effect return effectType; end --Pull base stats. local dMND = (caster:getStat(MOD_MND) - target:getStat(MOD_MND)); --Duration, including resistance. May need more research. local duration = 120; if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then duration = duration * 2; end caster:delStatusEffect(EFFECT_SABOTEUR); --Resist local resist = applyResistanceEffect(caster,spell,target,dMND,35,0,EFFECT_SILENCE); if (resist >= 0.5) then --Do it! if (target:addStatusEffect(effectType,1,0,duration * resist)) then spell:setMsg(236); else spell:setMsg(75); -- no effect end else spell:setMsg(85); end return effectType; end;
gpl-3.0
BibakBangTeam/Tabchi
tdcli.lua
12
80423
--[[ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ]]-- -- Vector example form is like this: {[0] = v} or {v1, v2, v3, [0] = v} -- If false or true crashed your telegram-cli, try to change true to 1 and false to 0 -- Main Bot Framework local M = {} -- @chat_id = user, group, channel, and broadcast -- @group_id = normal group -- @channel_id = channel and broadcast local function getChatId(chat_id) local chat = {} local chat_id = tostring(chat_id) if chat_id:match('^-100') then local channel_id = chat_id:gsub('-100', '') chat = {ID = channel_id, type = 'channel'} else local group_id = chat_id:gsub('-', '') chat = {ID = group_id, type = 'group'} end return chat end local function getInputMessageContent(file, filetype, caption) if file:match('/') or file:match('.') then infile = {ID = "InputFileLocal", path_ = file} elseif file:match('^%d+$') then infile = {ID = "InputFileId", id_ = file} else infile = {ID = "InputFilePersistentId", persistent_id_ = file} end local inmsg = {} local filetype = filetype:lower() if filetype == 'animation' then inmsg = {ID = "InputMessageAnimation", animation_ = infile, caption_ = caption} elseif filetype == 'audio' then inmsg = {ID = "InputMessageAudio", audio_ = infile, caption_ = caption} elseif filetype == 'document' then inmsg = {ID = "InputMessageDocument", document_ = infile, caption_ = caption} elseif filetype == 'photo' then inmsg = {ID = "InputMessagePhoto", photo_ = infile, caption_ = caption} elseif filetype == 'sticker' then inmsg = {ID = "InputMessageSticker", sticker_ = infile, caption_ = caption} elseif filetype == 'video' then inmsg = {ID = "InputMessageVideo", video_ = infile, caption_ = caption} elseif filetype == 'voice' then inmsg = {ID = "InputMessageVoice", voice_ = infile, caption_ = caption} end return inmsg end -- User can send bold, italic, and monospace text uses HTML or Markdown format. local function getParseMode(parse_mode) if parse_mode then local mode = parse_mode:lower() if mode == 'markdown' or mode == 'md' then P = {ID = "TextParseModeMarkdown"} elseif mode == 'html' then P = {ID = "TextParseModeHTML"} end end return P end -- Returns current authorization state, offline request local function getAuthState() tdcli_function ({ ID = "GetAuthState", }, dl_cb, nil) end M.getAuthState = getAuthState -- Sets user's phone number and sends authentication code to the user. -- Works only when authGetState returns authStateWaitPhoneNumber. -- If phone number is not recognized or another error has happened, returns an error. Otherwise returns authStateWaitCode -- @phone_number User's phone number in any reasonable format -- @allow_flash_call Pass True, if code can be sent via flash call to the specified phone number -- @is_current_phone_number Pass true, if the phone number is used on the current device. Ignored if allow_flash_call is False local function setAuthPhoneNumber(phone_number, allow_flash_call, is_current_phone_number) tdcli_function ({ ID = "SetAuthPhoneNumber", phone_number_ = phone_number, allow_flash_call_ = allow_flash_call, is_current_phone_number_ = is_current_phone_number }, dl_cb, nil) end M.setAuthPhoneNumber = setAuthPhoneNumber -- Resends authentication code to the user. -- Works only when authGetState returns authStateWaitCode and next_code_type of result is not null. -- Returns authStateWaitCode on success local function resendAuthCode() tdcli_function ({ ID = "ResendAuthCode", }, dl_cb, nil) end M.resendAuthCode = resendAuthCode -- Checks authentication code. -- Works only when authGetState returns authStateWaitCode. -- Returns authStateWaitPassword or authStateOk on success -- @code Verification code from SMS, Telegram message, voice call or flash call -- @first_name User first name, if user is yet not registered, 1-255 characters @last_name Optional user last name, if user is yet not registered, 0-255 characters local function checkAuthCode(code, first_name, last_name) tdcli_function ({ ID = "CheckAuthCode", code_ = code, first_name_ = first_name, last_name_ = last_name }, dl_cb, nil) end M.checkAuthCode = checkAuthCode -- Checks password for correctness. -- Works only when authGetState returns authStateWaitPassword. -- Returns authStateOk on success @password Password to check local function checkAuthPassword(password) tdcli_function ({ ID = "CheckAuthPassword", password_ = password }, dl_cb, nil) end M.checkAuthPassword = checkAuthPassword -- Requests to send password recovery code to email. -- Works only when authGetState returns authStateWaitPassword. -- Returns authStateWaitPassword on success local function requestAuthPasswordRecovery() tdcli_function ({ ID = "RequestAuthPasswordRecovery", }, dl_cb, nil) end M.requestAuthPasswordRecovery = requestAuthPasswordRecovery -- Recovers password with recovery code sent to email. -- Works only when authGetState returns authStateWaitPassword. -- Returns authStateOk on success @recovery_code Recovery code to check local function recoverAuthPassword(recovery_code) tdcli_function ({ ID = "RecoverAuthPassword", recovery_code_ = recovery_code }, dl_cb, nil) end M.recoverAuthPassword = recoverAuthPassword -- Logs out user. -- If force == false, begins to perform soft log out, returns authStateLoggingOut after completion. -- If force == true then succeeds almost immediately without cleaning anything at the server, but returns error with code 401 and description "Unauthorized" -- @force If true, just delete all local data. Session will remain in list of active sessions local function resetAuth(force) tdcli_function ({ ID = "ResetAuth", force_ = force or nil }, dl_cb, nil) end M.resetAuth = resetAuth -- Check bot's authentication token to log in as a bot. -- Works only when authGetState returns authStateWaitPhoneNumber. -- Can be used instead of setAuthPhoneNumber and checkAuthCode to log in. -- Returns authStateOk on success @token Bot token local function checkAuthBotToken(token) tdcli_function ({ ID = "CheckAuthBotToken", token_ = token }, dl_cb, nil) end M.checkAuthBotToken = checkAuthBotToken -- Returns current state of two-step verification local function getPasswordState() tdcli_function ({ ID = "GetPasswordState", }, dl_cb, nil) end M.getPasswordState = getPasswordState -- Changes user password. -- If new recovery email is specified, then error EMAIL_UNCONFIRMED is returned and password change will not be applied until email will be confirmed. -- Application should call getPasswordState from time to time to check if email is already confirmed -- @old_password Old user password -- @new_password New user password, may be empty to remove the password -- @new_hint New password hint, can be empty -- @set_recovery_email Pass True, if recovery email should be changed -- @new_recovery_email New recovery email, may be empty local function setPassword(old_password, new_password, new_hint, set_recovery_email, new_recovery_email) tdcli_function ({ ID = "SetPassword", old_password_ = old_password, new_password_ = new_password, new_hint_ = new_hint, set_recovery_email_ = set_recovery_email, new_recovery_email_ = new_recovery_email }, dl_cb, nil) end M.setPassword = setPassword -- Returns set up recovery email -- @password Current user password local function getRecoveryEmail(password) tdcli_function ({ ID = "GetRecoveryEmail", password_ = password }, dl_cb, nil) end M.getRecoveryEmail = getRecoveryEmail -- Changes user recovery email -- @password Current user password -- @new_recovery_email New recovery email local function setRecoveryEmail(password, new_recovery_email) tdcli_function ({ ID = "SetRecoveryEmail", password_ = password, new_recovery_email_ = new_recovery_email }, dl_cb, nil) end M.setRecoveryEmail = setRecoveryEmail -- Requests to send password recovery code to email local function requestPasswordRecovery() tdcli_function ({ ID = "RequestPasswordRecovery", }, dl_cb, nil) end M.requestPasswordRecovery = requestPasswordRecovery -- Recovers password with recovery code sent to email -- @recovery_code Recovery code to check local function recoverPassword(recovery_code) tdcli_function ({ ID = "RecoverPassword", recovery_code_ = tostring(recovery_code) }, dl_cb, nil) end M.recoverPassword = recoverPassword -- Returns current logged in user local function getMe() tdcli_function ({ ID = "GetMe", }, dl_cb, nil) end M.getMe = getMe -- Returns information about a user by its identifier, offline request if current user is not a bot -- @user_id User identifier local function getUser(user_id) tdcli_function ({ ID = "GetUser", user_id_ = user_id }, dl_cb, nil) end M.getUser = getUser -- Returns full information about a user by its identifier -- @user_id User identifier local function getUserFull(user_id) tdcli_function ({ ID = "GetUserFull", user_id_ = user_id }, dl_cb, nil) end M.getUserFull = getUserFull -- Returns information about a group by its identifier, offline request if current user is not a bot -- @group_id Group identifier local function getGroup(group_id) tdcli_function ({ ID = "GetGroup", group_id_ = getChatId(group_id).ID }, dl_cb, nil) end M.getGroup = getGroup -- Returns full information about a group by its identifier -- @group_id Group identifier local function getGroupFull(group_id) tdcli_function ({ ID = "GetGroupFull", group_id_ = getChatId(group_id).ID }, dl_cb, nil) end M.getGroupFull = getGroupFull -- Returns information about a channel by its identifier, offline request if current user is not a bot -- @channel_id Channel identifier local function getChannel(channel_id) tdcli_function ({ ID = "GetChannel", channel_id_ = getChatId(channel_id).ID }, dl_cb, nil) end M.getChannel = getChannel -- Returns full information about a channel by its identifier, cached for at most 1 minute -- @channel_id Channel identifier local function getChannelFull(channel_id) tdcli_function ({ ID = "GetChannelFull", channel_id_ = getChatId(channel_id).ID }, dl_cb, nil) end M.getChannelFull = getChannelFull -- Returns information about a chat by its identifier, offline request if current user is not a bot -- @chat_id Chat identifier local function getChat(chat_id) tdcli_function ({ ID = "GetChat", chat_id_ = chat_id }, dl_cb, nil) end M.getChat = getChat -- Returns information about a message -- @chat_id Identifier of the chat, message belongs to -- @message_id Identifier of the message to get local function getMessage(chat_id, message_id) tdcli_function ({ ID = "GetMessage", chat_id_ = chat_id, message_id_ = message_id }, dl_cb, nil) end M.getMessage = getMessage -- Returns information about messages. -- If message is not found, returns null on the corresponding position of the result -- @chat_id Identifier of the chat, messages belongs to -- @message_ids Identifiers of the messages to get local function getMessages(chat_id, message_ids) tdcli_function ({ ID = "GetMessages", chat_id_ = chat_id, message_ids_ = message_ids -- vector }, dl_cb, nil) end M.getMessages = getMessages -- Returns information about a file, offline request -- @file_id Identifier of the file to get local function getFile(file_id) tdcli_function ({ ID = "GetFile", file_id_ = file_id }, dl_cb, nil) end M.getFile = getFile -- Returns information about a file by its persistent id, offline request -- @persistent_file_id Persistent identifier of the file to get local function getFilePersistent(persistent_file_id) tdcli_function ({ ID = "GetFilePersistent", persistent_file_id_ = persistent_file_id }, dl_cb, nil) end M.getFilePersistent = getFilePersistent -- BAD RESULT -- Returns list of chats in the right order, chats are sorted by (order, chat_id) in decreasing order. -- For example, to get list of chats from the beginning, the offset_order should be equal 2^63 - 1 -- @offset_order Chat order to return chats from -- @offset_chat_id Chat identifier to return chats from -- @limit Maximum number of chats to be returned local function getChats(offset_order, offset_chat_id, limit) if not limit or limit > 20 then limit = 20 end tdcli_function ({ ID = "GetChats", offset_order_ = offset_order or 9223372036854775807, offset_chat_id_ = offset_chat_id or 0, limit_ = limit }, dl_cb, nil) end M.getChats = getChats -- Searches public chat by its username. -- Currently only private and channel chats can be public. -- Returns chat if found, otherwise some error is returned -- @username Username to be resolved local function searchPublicChat(username) tdcli_function ({ ID = "SearchPublicChat", username_ = username }, dl_cb, nil) end M.searchPublicChat = searchPublicChat -- Searches public chats by prefix of their username. -- Currently only private and channel (including supergroup) chats can be public. -- Returns meaningful number of results. -- Returns nothing if length of the searched username prefix is less than 5. -- Excludes private chats with contacts from the results -- @username_prefix Prefix of the username to search local function searchPublicChats(username_prefix) tdcli_function ({ ID = "SearchPublicChats", username_prefix_ = username_prefix }, dl_cb, nil) end M.searchPublicChats = searchPublicChats -- Searches for specified query in the title and username of known chats, offline request. -- Returns chats in the order of them in the chat list -- @query Query to search for, if query is empty, returns up to 20 recently found chats -- @limit Maximum number of chats to be returned local function searchChats(query, limit) if not limit or limit > 20 then limit = 20 end tdcli_function ({ ID = "SearchChats", query_ = query, limit_ = limit }, dl_cb, nil) end M.searchChats = searchChats -- Adds chat to the list of recently found chats. -- The chat is added to the beginning of the list. -- If the chat is already in the list, at first it is removed from the list -- @chat_id Identifier of the chat to add local function addRecentlyFoundChat(chat_id) tdcli_function ({ ID = "AddRecentlyFoundChat", chat_id_ = chat_id }, dl_cb, nil) end M.addRecentlyFoundChat = addRecentlyFoundChat -- Deletes chat from the list of recently found chats -- @chat_id Identifier of the chat to delete local function deleteRecentlyFoundChat(chat_id) tdcli_function ({ ID = "DeleteRecentlyFoundChat", chat_id_ = chat_id }, dl_cb, nil) end M.deleteRecentlyFoundChat = deleteRecentlyFoundChat -- Clears list of recently found chats local function deleteRecentlyFoundChats() tdcli_function ({ ID = "DeleteRecentlyFoundChats", }, dl_cb, nil) end M.deleteRecentlyFoundChats = deleteRecentlyFoundChats -- Returns list of common chats with an other given user. -- Chats are sorted by their type and creation date -- @user_id User identifier -- @offset_chat_id Chat identifier to return chats from, use 0 for the first request -- @limit Maximum number of chats to be returned, up to 100 local function getCommonChats(user_id, offset_chat_id, limit) if not limit or limit > 100 then limit = 100 end tdcli_function ({ ID = "GetCommonChats", user_id_ = user_id, offset_chat_id_ = offset_chat_id, limit_ = limit }, dl_cb, nil) end M.getCommonChats = getCommonChats -- Returns messages in a chat. -- Automatically calls openChat. -- Returns result in reverse chronological order, i.e. in order of decreasing message.message_id -- @chat_id Chat identifier -- @from_message_id Identifier of the message near which we need a history, you can use 0 to get results from the beginning, i.e. from oldest to newest -- @offset Specify 0 to get results exactly from from_message_id or negative offset to get specified message and some newer messages -- @limit Maximum number of messages to be returned, should be positive and can't be greater than 100. -- If offset is negative, limit must be greater than -offset. -- There may be less than limit messages returned even the end of the history is not reached local function getChatHistory(chat_id, from_message_id, offset, limit) if not limit or limit > 100 then limit = 100 end tdcli_function ({ ID = "GetChatHistory", chat_id_ = chat_id, from_message_id_ = from_message_id, offset_ = offset or 0, limit_ = limit }, dl_cb, nil) end M.getChatHistory = getChatHistory -- Deletes all messages in the chat. -- Can't be used for channel chats -- @chat_id Chat identifier -- @remove_from_chat_list Pass true, if chat should be removed from the chat list local function deleteChatHistory(chat_id, remove_from_chat_list) tdcli_function ({ ID = "DeleteChatHistory", chat_id_ = chat_id, remove_from_chat_list_ = remove_from_chat_list }, dl_cb, nil) end M.deleteChatHistory = deleteChatHistory -- Searches for messages with given words in the chat. -- Returns result in reverse chronological order, i. e. in order of decreasimg message_id. -- Doesn't work in secret chats -- @chat_id Chat identifier to search in -- @query Query to search for @from_message_id Identifier of the message from which we need a history, you can use 0 to get results from beginning -- @limit Maximum number of messages to be returned, can't be greater than 100 -- @filter Filter for content of searched messages -- filter = Empty|Animation|Audio|Document|Photo|Video|Voice|PhotoAndVideo|Url|ChatPhoto local function searchChatMessages(chat_id, query, from_message_id, limit, filter) if not limit or limit > 100 then limit = 100 end tdcli_function ({ ID = "SearchChatMessages", chat_id_ = chat_id, query_ = query, from_message_id_ = from_message_id, limit_ = limit, filter_ = { ID = 'SearchMessagesFilter' .. filter }, }, dl_cb, nil) end M.searchChatMessages = searchChatMessages -- Searches for messages in all chats except secret. -- Returns result in reverse chronological order, i. e. in order of decreasing (date, chat_id, message_id) -- @query Query to search for -- @offset_date Date of the message to search from, you can use 0 or any date in the future to get results from the beginning -- @offset_chat_id Chat identifier of the last found message or 0 for the first request -- @offset_message_id Message identifier of the last found message or 0 for the first request -- @limit Maximum number of messages to be returned, can't be greater than 100 local function searchMessages(query, offset_date, offset_chat_id, offset_message_id, limit) if not limit or limit > 100 then limit = 100 end tdcli_function ({ ID = "SearchMessages", query_ = query, offset_date_ = offset_date, offset_chat_id_ = offset_chat_id, offset_message_id_ = offset_message_id, limit_ = limit }, dl_cb, nil) end M.searchMessages = searchMessages -- Sends a message. -- Returns sent message. -- UpdateChatTopMessage will not be sent, so returned message should be used to update chat top message -- @chat_id Chat to send message -- @reply_to_message_id Identifier of a message to reply to or 0 -- @disable_notification Pass true, to disable notification about the message -- @from_background Pass true, if the message is sent from background -- @reply_markup Bots only. Markup for replying to message -- @input_message_content Content of a message to send local function sendMessage(chat_id, reply_to_message_id, disable_notification, text, disable_web_page_preview, parse_mode) local TextParseMode = getParseMode(parse_mode) tdcli_function ({ ID = "SendMessage", chat_id_ = chat_id, reply_to_message_id_ = reply_to_message_id, disable_notification_ = disable_notification, from_background_ = 1, reply_markup_ = nil, input_message_content_ = { ID = "InputMessageText", text_ = text, disable_web_page_preview_ = disable_web_page_preview, clear_draft_ = 0, entities_ = {}, parse_mode_ = TextParseMode, }, }, dl_cb, nil) end M.sendMessage = sendMessage -- Invites bot to a chat (if it is not in the chat) and send /start to it. -- Bot can't be invited to a private chat other than chat with the bot. -- Bots can't be invited to broadcast channel chats. -- Returns sent message. -- UpdateChatTopMessage will not be sent, so returned message should be used to update chat top message -- @bot_user_id Identifier of the bot -- @chat_id Identifier of the chat -- @parameter Hidden parameter sent to bot for deep linking (https://api.telegram.org/bots#deep-linking) -- parameter=start|startgroup or custom as defined by bot creator local function sendBotStartMessage(bot_user_id, chat_id, parameter) tdcli_function ({ ID = "SendBotStartMessage", bot_user_id_ = bot_user_id, chat_id_ = chat_id, parameter_ = parameter }, dl_cb, nil) end M.sendBotStartMessage = sendBotStartMessage -- Sends result of the inline query as a message. -- Returns sent message. -- UpdateChatTopMessage will not be sent, so returned message should be used to update chat top message. -- Always clears chat draft message -- @chat_id Chat to send message -- @reply_to_message_id Identifier of a message to reply to or 0 -- @disable_notification Pass true, to disable notification about the message -- @from_background Pass true, if the message is sent from background -- @query_id Identifier of the inline query -- @result_id Identifier of the inline result local function sendInlineQueryResultMessage(chat_id, reply_to_message_id, disable_notification, from_background, query_id, result_id) tdcli_function ({ ID = "SendInlineQueryResultMessage", chat_id_ = chat_id, reply_to_message_id_ = reply_to_message_id, disable_notification_ = disable_notification, from_background_ = from_background, query_id_ = query_id, result_id_ = result_id }, dl_cb, nil) end M.sendInlineQueryResultMessage = sendInlineQueryResultMessage -- Forwards previously sent messages. -- Returns forwarded messages in the same order as message identifiers passed in message_ids. -- If message can't be forwarded, null will be returned instead of the message. -- UpdateChatTopMessage will not be sent, so returned messages should be used to update chat top message -- @chat_id Identifier of a chat to forward messages -- @from_chat_id Identifier of a chat to forward from -- @message_ids Identifiers of messages to forward -- @disable_notification Pass true, to disable notification about the message -- @from_background Pass true, if the message is sent from background local function forwardMessages(chat_id, from_chat_id, message_ids, disable_notification) tdcli_function ({ ID = "ForwardMessages", chat_id_ = chat_id, from_chat_id_ = from_chat_id, message_ids_ = message_ids, -- vector disable_notification_ = disable_notification, from_background_ = 1 }, dl_cb, nil) end M.forwardMessages = forwardMessages -- Deletes messages. -- UpdateDeleteMessages will not be sent for messages deleted through that function -- @chat_id Chat identifier -- @message_ids Identifiers of messages to delete local function deleteMessages(chat_id, message_ids) tdcli_function ({ ID = "DeleteMessages", chat_id_ = chat_id, message_ids_ = message_ids -- vector }, dl_cb, nil) end M.deleteMessages = deleteMessages -- Edits text of text or game message. -- Non-bots can edit message in a limited period of time. -- Returns edited message after edit is complete server side -- @chat_id Chat the message belongs to -- @message_id Identifier of the message -- @reply_markup Bots only. New message reply markup -- @input_message_content New text content of the message. Should be of type InputMessageText local function editMessageText(chat_id, message_id, reply_markup, text, disable_web_page_preview, parse_mode) local TextParseMode = getParseMode(parse_mode) tdcli_function ({ ID = "EditMessageText", chat_id_ = chat_id, message_id_ = message_id, reply_markup_ = reply_markup, -- reply_markup:ReplyMarkup input_message_content_ = { ID = "InputMessageText", text_ = text, disable_web_page_preview_ = disable_web_page_preview, clear_draft_ = 0, entities_ = {}, parse_mode_ = TextParseMode, }, }, dl_cb, nil) end M.editMessageText = editMessageText -- Edits message content caption. Non-bots can edit message in a limited period of time. Returns edited message after edit is complete server side -- @chat_id Chat the message belongs to @message_id Identifier of the message @reply_markup Bots only. New message reply markup @caption New message content caption, 0-200 characters local function editMessageCaption(chat_id, message_id, reply_markup, caption) tdcli_function ({ ID = "EditMessageCaption", chat_id_ = chat_id, message_id_ = message_id, reply_markup_ = reply_markup, -- reply_markup:ReplyMarkup caption_ = caption }, dl_cb, nil) end M.editMessageCaption = editMessageCaption -- Bots only. -- Edits message reply markup. -- Returns edited message after edit is complete server side -- @chat_id Chat the message belongs to -- @message_id Identifier of the message -- @reply_markup New message reply markup local function editMessageReplyMarkup(inline_message_id, reply_markup, caption) tdcli_function ({ ID = "EditInlineMessageCaption", inline_message_id_ = inline_message_id, reply_markup_ = reply_markup, -- reply_markup:ReplyMarkup caption_ = caption }, dl_cb, nil) end M.editMessageReplyMarkup = editMessageReplyMarkup -- Bots only. -- Edits text of an inline text or game message sent via bot -- @inline_message_id Inline message identifier -- @reply_markup New message reply markup -- @input_message_content New text content of the message. Should be of type InputMessageText local function editInlineMessageText(inline_message_id, reply_markup, text, disable_web_page_preview) tdcli_function ({ ID = "EditInlineMessageText", inline_message_id_ = inline_message_id, reply_markup_ = reply_markup, -- reply_markup:ReplyMarkup input_message_content_ = { ID = "InputMessageText", text_ = text, disable_web_page_preview_ = disable_web_page_preview, clear_draft_ = 0, entities_ = {} }, }, dl_cb, nil) end M.editInlineMessageText = editInlineMessageText -- Bots only. Edits caption of an inline message content sent via bot @inline_message_id Inline message identifier @reply_markup New message reply markup @caption New message content caption, 0-200 characters local function editInlineMessageCaption(inline_message_id, reply_markup, caption) tdcli_function ({ ID = "EditInlineMessageCaption", inline_message_id_ = inline_message_id, reply_markup_ = reply_markup, -- reply_markup:ReplyMarkup caption_ = caption }, dl_cb, nil) end M.editInlineMessageCaption = editInlineMessageCaption -- Bots only. -- Edits reply markup of an inline message sent via bot -- @inline_message_id Inline message identifier -- @reply_markup New message reply markup local function editInlineMessageReplyMarkup(inline_message_id, reply_markup) tdcli_function ({ ID = "EditInlineMessageReplyMarkup", inline_message_id_ = inline_message_id, reply_markup_ = reply_markup -- reply_markup:ReplyMarkup }, dl_cb, nil) end M.editInlineMessageReplyMarkup = editInlineMessageReplyMarkup -- Sends inline query to a bot and returns its results. -- Unavailable for bots -- @bot_user_id Identifier of the bot send query to -- @chat_id Identifier of the chat, where the query is sent -- @user_location User location, only if needed @query Text of the query -- @offset Offset of the first entry to return local function getInlineQueryResults(bot_user_id, chat_id, latitude, longitude, query, offset) tdcli_function ({ ID = "GetInlineQueryResults", bot_user_id_ = bot_user_id, chat_id_ = chat_id, user_location_ = { ID = "Location", latitude_ = latitude, longitude_ = longitude }, query_ = query, offset_ = offset }, dl_cb, nil) end M.getInlineQueryResults = getInlineQueryResults -- Bots only. -- Sets result of the inline query -- @inline_query_id Identifier of the inline query -- @is_personal Does result of the query can be cached only for specified user -- @results Results of the query @cache_time Allowed time to cache results of the query in seconds -- @next_offset Offset for the next inline query, pass empty string if there is no more results -- @switch_pm_text If non-empty, this text should be shown on the button, which opens private chat with the bot and sends bot start message with parameter switch_pm_parameter -- @switch_pm_parameter Parameter for the bot start message local function answerInlineQuery(inline_query_id, is_personal, cache_time, next_offset, switch_pm_text, switch_pm_parameter) tdcli_function ({ ID = "AnswerInlineQuery", inline_query_id_ = inline_query_id, is_personal_ = is_personal, results_ = results, --vector<InputInlineQueryResult>, cache_time_ = cache_time, next_offset_ = next_offset, switch_pm_text_ = switch_pm_text, switch_pm_parameter_ = switch_pm_parameter }, dl_cb, nil) end M.answerInlineQuery = answerInlineQuery -- Sends callback query to a bot and returns answer to it. -- Unavailable for bots -- @chat_id Identifier of the chat with a message -- @message_id Identifier of the message, from which the query is originated -- @payload Query payload local function getCallbackQueryAnswer(chat_id, message_id, text, show_alert, url) tdcli_function ({ ID = "GetCallbackQueryAnswer", chat_id_ = chat_id, message_id_ = message_id, payload_ = { ID = "CallbackQueryAnswer", text_ = text, show_alert_ = show_alert, url_ = url }, }, dl_cb, nil) end M.getCallbackQueryAnswer = getCallbackQueryAnswer -- Bots only. -- Sets result of the callback query -- @callback_query_id Identifier of the callback query -- @text Text of the answer -- @show_alert If true, an alert should be shown to the user instead of a toast -- @url Url to be opened -- @cache_time Allowed time to cache result of the query in seconds local function answerCallbackQuery(callback_query_id, text, show_alert, url, cache_time) tdcli_function ({ ID = "AnswerCallbackQuery", callback_query_id_ = callback_query_id, text_ = text, show_alert_ = show_alert, url_ = url, cache_time_ = cache_time }, dl_cb, nil) end M.answerCallbackQuery = answerCallbackQuery -- Bots only. -- Updates game score of the specified user in the game -- @chat_id Chat a message with the game belongs to -- @message_id Identifier of the message -- @edit_message True, if message should be edited -- @user_id User identifier -- @score New score -- @force Pass True to update the score even if it decreases. If score is 0, user will be deleted from the high scores table local function setGameScore(chat_id, message_id, edit_message, user_id, score, force) tdcli_function ({ ID = "SetGameScore", chat_id_ = chat_id, message_id_ = message_id, edit_message_ = edit_message, user_id_ = user_id, score_ = score, force_ = force }, dl_cb, nil) end M.setGameScore = setGameScore -- Bots only. -- Updates game score of the specified user in the game -- @inline_message_id Inline message identifier -- @edit_message True, if message should be edited -- @user_id User identifier -- @score New score -- @force Pass True to update the score even if it decreases. If score is 0, user will be deleted from the high scores table local function setInlineGameScore(inline_message_id, edit_message, user_id, score, force) tdcli_function ({ ID = "SetInlineGameScore", inline_message_id_ = inline_message_id, edit_message_ = edit_message, user_id_ = user_id, score_ = score, force_ = force }, dl_cb, nil) end M.setInlineGameScore = setInlineGameScore -- Bots only. -- Returns game high scores and some part of the score table around of the specified user in the game -- @chat_id Chat a message with the game belongs to -- @message_id Identifier of the message -- @user_id User identifie local function getGameHighScores(chat_id, message_id, user_id) tdcli_function ({ ID = "GetGameHighScores", chat_id_ = chat_id, message_id_ = message_id, user_id_ = user_id }, dl_cb, nil) end M.getGameHighScores = getGameHighScores -- Bots only. -- Returns game high scores and some part of the score table around of the specified user in the game -- @inline_message_id Inline message identifier -- @user_id User identifier local function getInlineGameHighScores(inline_message_id, user_id) tdcli_function ({ ID = "GetInlineGameHighScores", inline_message_id_ = inline_message_id, user_id_ = user_id }, dl_cb, nil) end M.getInlineGameHighScores = getInlineGameHighScores -- Deletes default reply markup from chat. -- This method needs to be called after one-time keyboard or ForceReply reply markup has been used. -- UpdateChatReplyMarkup will be send if reply markup will be changed -- @chat_id Chat identifier -- @message_id Message identifier of used keyboard local function deleteChatReplyMarkup(chat_id, message_id) tdcli_function ({ ID = "DeleteChatReplyMarkup", chat_id_ = chat_id, message_id_ = message_id }, dl_cb, nil) end M.deleteChatReplyMarkup = deleteChatReplyMarkup -- Sends notification about user activity in a chat -- @chat_id Chat identifier -- @action Action description -- action = Typing|Cancel|RecordVideo|UploadVideo|RecordVoice|UploadVoice|UploadPhoto|UploadDocument|GeoLocation|ChooseContact|StartPlayGame local function sendChatAction(chat_id, action, progress) tdcli_function ({ ID = "SendChatAction", chat_id_ = chat_id, action_ = { ID = "SendMessage" .. action .. "Action", progress_ = progress or 100 } }, dl_cb, nil) end M.sendChatAction = sendChatAction -- Chat is opened by the user. -- Many useful activities depends on chat being opened or closed. For example, in channels all updates are received only for opened chats -- @chat_id Chat identifier local function openChat(chat_id) tdcli_function ({ ID = "OpenChat", chat_id_ = chat_id }, dl_cb, nil) end M.openChat = openChat -- Chat is closed by the user. -- Many useful activities depends on chat being opened or closed. -- @chat_id Chat identifier local function closeChat(chat_id) tdcli_function ({ ID = "CloseChat", chat_id_ = chat_id }, dl_cb, nil) end M.closeChat = closeChat -- Messages are viewed by the user. -- Many useful activities depends on message being viewed. For example, marking messages as read, incrementing of view counter, updating of view counter, removing of deleted messages in channels -- @chat_id Chat identifier -- @message_ids Identifiers of viewed messages local function viewMessages(chat_id, message_ids) tdcli_function ({ ID = "ViewMessages", chat_id_ = chat_id, message_ids_ = message_ids -- vector }, dl_cb, nil) end M.viewMessages = viewMessages -- Message content is opened, for example the user has opened a photo, a video, a document, a location or a venue or have listened to an audio or a voice message -- @chat_id Chat identifier of the message -- @message_id Identifier of the message with opened content local function openMessageContent(chat_id, message_id) tdcli_function ({ ID = "OpenMessageContent", chat_id_ = chat_id, message_id_ = message_id }, dl_cb, nil) end M.openMessageContent = openMessageContent -- Returns existing chat corresponding to the given user -- @user_id User identifier local function createPrivateChat(user_id) tdcli_function ({ ID = "CreatePrivateChat", user_id_ = user_id }, dl_cb, nil) end M.createPrivateChat = createPrivateChat -- Returns existing chat corresponding to the known group -- @group_id Group identifier local function createGroupChat(group_id) tdcli_function ({ ID = "CreateGroupChat", group_id_ = getChatId(group_id).ID }, dl_cb, nil) end M.createGroupChat = createGroupChat -- Returns existing chat corresponding to the known channel -- @channel_id Channel identifier local function createChannelChat(channel_id) tdcli_function ({ ID = "CreateChannelChat", channel_id_ = getChatId(channel_id).ID }, dl_cb, nil) end M.createChannelChat = createChannelChat -- Returns existing chat corresponding to the known secret chat -- @secret_chat_id SecretChat identifier local function createSecretChat(secret_chat_id) tdcli_function ({ ID = "CreateSecretChat", secret_chat_id_ = secret_chat_id }, dl_cb, nil) end M.createSecretChat = createSecretChat -- Creates new group chat and send corresponding messageGroupChatCreate, returns created chat -- @user_ids Identifiers of users to add to the group -- @title Title of new group chat, 0-255 characters local function createNewGroupChat(user_ids, title) tdcli_function ({ ID = "CreateNewGroupChat", user_ids_ = user_ids, -- vector title_ = title }, dl_cb, nil) end M.createNewGroupChat = createNewGroupChat -- Creates new channel chat and send corresponding messageChannelChatCreate, returns created chat -- @title Title of new channel chat, 0-255 characters -- @is_supergroup True, if supergroup chat should be created -- @about Information about the channel, 0-255 characters local function createNewChannelChat(title, is_supergroup, about) tdcli_function ({ ID = "CreateNewChannelChat", title_ = title, is_supergroup_ = is_supergroup, about_ = about }, dl_cb, nil) end M.createNewChannelChat = createNewChannelChat -- Creates new secret chat, returns created chat -- @user_id Identifier of a user to create secret chat with local function createNewSecretChat(user_id) tdcli_function ({ ID = "CreateNewSecretChat", user_id_ = user_id }, dl_cb, nil) end M.createNewSecretChat = createNewSecretChat -- Creates new channel supergroup chat from existing group chat and send corresponding messageChatMigrateTo and messageChatMigrateFrom. Deactivates group -- @chat_id Group chat identifier local function migrateGroupChatToChannelChat(chat_id) tdcli_function ({ ID = "MigrateGroupChatToChannelChat", chat_id_ = chat_id }, dl_cb, nil) end M.migrateGroupChatToChannelChat = migrateGroupChatToChannelChat -- Changes chat title. -- Title can't be changed for private chats. -- Title will not change until change will be synchronized with the server. -- Title will not be changed if application is killed before it can send request to the server. -- There will be update about change of the title on success. Otherwise error will be returned -- @chat_id Chat identifier -- @title New title of a chat, 0-255 characters local function changeChatTitle(chat_id, title) tdcli_function ({ ID = "ChangeChatTitle", chat_id_ = chat_id, title_ = title }, dl_cb, nil) end M.changeChatTitle = changeChatTitle -- Changes chat photo. -- Photo can't be changed for private chats. -- Photo will not change until change will be synchronized with the server. -- Photo will not be changed if application is killed before it can send request to the server. -- There will be update about change of the photo on success. Otherwise error will be returned @chat_id Chat identifier -- @photo New chat photo. You can use zero InputFileId to delete photo. Files accessible only by HTTP URL are not acceptable local function changeChatPhoto(chat_id, file) tdcli_function ({ ID = "ChangeChatPhoto", chat_id_ = chat_id, photo_ = { ID = "InputFileLocal", path_ = file } }, dl_cb, nil) end M.changeChatPhoto = changeChatPhoto -- Changes chat draft message -- @chat_id Chat identifier -- @draft_message New draft message, nullable local function changeChatDraftMessage(chat_id, reply_to_message_id, text, disable_web_page_preview, clear_draft, parse_mode) local TextParseMode = getParseMode(parse_mode) tdcli_function ({ ID = "ChangeChatDraftMessage", chat_id_ = chat_id, draft_message_ = { ID = "DraftMessage", reply_to_message_id_ = reply_to_message_id, input_message_text_ = { ID = "InputMessageText", text_ = text, disable_web_page_preview_ = disable_web_page_preview, clear_draft_ = clear_draft, entities_ = {}, parse_mode_ = TextParseMode, }, }, }, dl_cb, nil) end M.changeChatDraftMessage = changeChatDraftMessage -- Adds new member to chat. -- Members can't be added to private or secret chats. -- Member will not be added until chat state will be synchronized with the server. -- Member will not be added if application is killed before it can send request to the server -- @chat_id Chat identifier -- @user_id Identifier of the user to add -- @forward_limit Number of previous messages from chat to forward to new member, ignored for channel chats local function addChatMember(chat_id, user_id, forward_limit) tdcli_function ({ ID = "AddChatMember", chat_id_ = chat_id, user_id_ = user_id, forward_limit_ = forward_limit or 50 }, dl_cb, nil) end M.addChatMember = addChatMember -- Adds many new members to the chat. -- Currently, available only for channels. -- Can't be used to join the channel. -- Member will not be added until chat state will be synchronized with the server. -- Member will not be added if application is killed before it can send request to the server -- @chat_id Chat identifier -- @user_ids Identifiers of the users to add local function addChatMembers(chat_id, user_ids) tdcli_function ({ ID = "AddChatMembers", chat_id_ = chat_id, user_ids_ = user_ids -- vector }, dl_cb, nil) end M.addChatMembers = addChatMembers -- Changes status of the chat member, need appropriate privileges. -- In channel chats, user will be added to chat members if he is yet not a member and there is less than 200 members in the channel. -- Status will not be changed until chat state will be synchronized with the server. -- Status will not be changed if application is killed before it can send request to the server -- @chat_id Chat identifier -- @user_id Identifier of the user to edit status, bots can be editors in the channel chats -- @status New status of the member in the chat -- status = Creator|Editor|Moderator|Member|Left|Kicked local function changeChatMemberStatus(chat_id, user_id, status) tdcli_function ({ ID = "ChangeChatMemberStatus", chat_id_ = chat_id, user_id_ = user_id, status_ = { ID = "ChatMemberStatus" .. status }, }, dl_cb, nil) end M.changeChatMemberStatus = changeChatMemberStatus -- Returns information about one participant of the chat -- @chat_id Chat identifier -- @user_id User identifier local function getChatMember(chat_id, user_id) tdcli_function ({ ID = "GetChatMember", chat_id_ = chat_id, user_id_ = user_id }, dl_cb, nil) end M.getChatMember = getChatMember -- Asynchronously downloads file from cloud. -- Updates updateFileProgress will notify about download progress. -- Update updateFile will notify about successful download -- @file_id Identifier of file to download local function downloadFile(file_id) tdcli_function ({ ID = "DownloadFile", file_id_ = file_id }, dl_cb, nil) end M.downloadFile = downloadFile -- Stops file downloading. -- If file already downloaded do nothing. -- @file_id Identifier of file to cancel download local function cancelDownloadFile(file_id) tdcli_function ({ ID = "CancelDownloadFile", file_id_ = file_id }, dl_cb, nil) end M.cancelDownloadFile = cancelDownloadFile -- Generates new chat invite link, previously generated link is revoked. -- Available for group and channel chats. -- Only creator of the chat can export chat invite link -- @chat_id Chat identifier local function exportChatInviteLink(chat_id) tdcli_function ({ ID = "ExportChatInviteLink", chat_id_ = chat_id }, dl_cb, nil) end M.exportChatInviteLink = exportChatInviteLink -- Checks chat invite link for validness and returns information about the corresponding chat -- @invite_link Invite link to check. Should begin with "https://telegram.me/joinchat/" local function checkChatInviteLink(link) tdcli_function ({ ID = "CheckChatInviteLink", invite_link_ = link }, dl_cb, nil) end M.checkChatInviteLink = checkChatInviteLink -- Imports chat invite link, adds current user to a chat if possible. -- Member will not be added until chat state will be synchronized with the server. -- Member will not be added if application is killed before it can send request to the server -- @invite_link Invite link to import. Should begin with "https://telegram.me/joinchat/" local function importChatInviteLink(invite_link) tdcli_function ({ ID = "ImportChatInviteLink", invite_link_ = invite_link }, dl_cb, nil) end M.importChatInviteLink = importChatInviteLink -- Adds user to black list -- @user_id User identifier local function blockUser(user_id) tdcli_function ({ ID = "BlockUser", user_id_ = user_id }, dl_cb, nil) end M.blockUser = blockUser -- Removes user from black list -- @user_id User identifier local function unblockUser(user_id) tdcli_function ({ ID = "UnblockUser", user_id_ = user_id }, dl_cb, nil) end M.unblockUser = unblockUser -- Returns users blocked by the current user -- @offset Number of users to skip in result, must be non-negative -- @limit Maximum number of users to return, can't be greater than 100 local function getBlockedUsers(offset, limit) tdcli_function ({ ID = "GetBlockedUsers", offset_ = offset, limit_ = limit }, dl_cb, nil) end M.getBlockedUsers = getBlockedUsers -- Adds new contacts/edits existing contacts, contacts user identifiers are ignored. -- Returns list of corresponding users in the same order as input contacts. -- If contact doesn't registered in Telegram, user with id == 0 will be returned -- @contacts List of contacts to import/edit local function importContacts(phone_number, first_name, last_name, user_id) tdcli_function ({ ID = "ImportContacts", contacts_ = {[0] = { phone_number_ = tostring(phone_number), first_name_ = tostring(first_name), last_name_ = tostring(last_name), user_id_ = user_id }, }, }, dl_cb, nil) end M.importContacts = importContacts -- Searches for specified query in the first name, last name and username of the known user contacts -- @query Query to search for, can be empty to return all contacts -- @limit Maximum number of users to be returned local function searchContacts(query, limit) tdcli_function ({ ID = "SearchContacts", query_ = query, limit_ = limit }, dl_cb, nil) end M.searchContacts = searchContacts -- Deletes users from contacts list -- @user_ids Identifiers of users to be deleted local function deleteContacts(user_ids) tdcli_function ({ ID = "DeleteContacts", user_ids_ = user_ids -- vector }, dl_cb, nil) end M.deleteContacts = deleteContacts -- Returns profile photos of the user. -- Result of this query can't be invalidated, so it must be used with care -- @user_id User identifier -- @offset Photos to skip, must be non-negative -- @limit Maximum number of photos to be returned, can't be greater than 100 local function getUserProfilePhotos(user_id, offset, limit) tdcli_function ({ ID = "GetUserProfilePhotos", user_id_ = user_id, offset_ = offset, limit_ = limit }, dl_cb, nil) end M.getUserProfilePhotos = getUserProfilePhotos -- Returns stickers corresponding to given emoji -- @emoji String representation of emoji. If empty, returns all known stickers local function getStickers(emoji) tdcli_function ({ ID = "GetStickers", emoji_ = emoji }, dl_cb, nil) end M.getStickers = getStickers -- Returns list of installed sticker sets -- @only_enabled If true, returns only enabled sticker sets local function getStickerSets(only_enabled) tdcli_function ({ ID = "GetStickerSets", only_enabled_ = only_enabled }, dl_cb, nil) end M.getStickerSets = getStickerSets -- Returns information about sticker set by its identifier -- @set_id Identifier of the sticker set local function getStickerSet(set_id) tdcli_function ({ ID = "GetStickerSet", set_id_ = set_id }, dl_cb, nil) end M.getStickerSet = getStickerSet -- Searches sticker set by its short name -- @name Name of the sticker set local function searchStickerSet(name) tdcli_function ({ ID = "SearchStickerSet", name_ = name }, dl_cb, nil) end M.searchStickerSet = searchStickerSet -- Installs/uninstalls or enables/archives sticker set. -- Official sticker set can't be uninstalled, but it can be archived -- @set_id Identifier of the sticker set -- @is_installed New value of is_installed -- @is_enabled New value of is_enabled local function updateStickerSet(set_id, is_installed, is_enabled) tdcli_function ({ ID = "UpdateStickerSet", set_id_ = set_id, is_installed_ = is_installed, is_enabled_ = is_enabled }, dl_cb, nil) end M.updateStickerSet = updateStickerSet -- Returns saved animations local function getSavedAnimations() tdcli_function ({ ID = "GetSavedAnimations", }, dl_cb, nil) end M.getSavedAnimations = getSavedAnimations -- Manually adds new animation to the list of saved animations. -- New animation is added to the beginning of the list. -- If the animation is already in the list, at first it is removed from the list. -- Only video animations with MIME type "video/mp4" can be added to the list -- @animation Animation file to add. Only known to server animations (i. e. successfully sent via message) can be added to the list local function addSavedAnimation(id) tdcli_function ({ ID = "AddSavedAnimation", animation_ = { ID = "InputFileId", id_ = id }, }, dl_cb, nil) end M.addSavedAnimation = addSavedAnimation -- Removes animation from the list of saved animations -- @animation Animation file to delete local function deleteSavedAnimation(id) tdcli_function ({ ID = "DeleteSavedAnimation", animation_ = { ID = "InputFileId", id_ = id }, }, dl_cb, nil) end M.deleteSavedAnimation = deleteSavedAnimation -- Returns up to 20 recently used inline bots in the order of the last usage local function getRecentInlineBots() tdcli_function ({ ID = "GetRecentInlineBots", }, dl_cb, nil) end M.getRecentInlineBots = getRecentInlineBots -- Get web page preview by text of the message. -- Do not call this function to often -- @message_text Message text local function getWebPagePreview(message_text) tdcli_function ({ ID = "GetWebPagePreview", message_text_ = message_text }, dl_cb, nil) end M.getWebPagePreview = getWebPagePreview -- Returns notification settings for given scope -- @scope Scope to return information about notification settings -- scope = Chat(chat_id)|PrivateChats|GroupChats|AllChats| local function getNotificationSettings(scope, chat_id) tdcli_function ({ ID = "GetNotificationSettings", scope_ = { ID = 'NotificationSettingsFor' .. scope, chat_id_ = chat_id or nil }, }, dl_cb, nil) end M.getNotificationSettings = getNotificationSettings -- Changes notification settings for given scope -- @scope Scope to change notification settings -- @notification_settings New notification settings for given scope -- scope = Chat(chat_id)|PrivateChats|GroupChats|AllChats| local function setNotificationSettings(scope, chat_id, mute_for, show_preview) tdcli_function ({ ID = "SetNotificationSettings", scope_ = { ID = 'NotificationSettingsFor' .. scope, chat_id_ = chat_id or nil }, notification_settings_ = { ID = "NotificationSettings", mute_for_ = mute_for, sound_ = "default", show_preview_ = show_preview } }, dl_cb, nil) end M.setNotificationSettings = setNotificationSettings -- Uploads new profile photo for logged in user. -- Photo will not change until change will be synchronized with the server. -- Photo will not be changed if application is killed before it can send request to the server. -- If something changes, updateUser will be sent -- @photo_path Path to new profile photo local function setProfilePhoto(photo_path) tdcli_function ({ ID = "SetProfilePhoto", photo_path_ = photo_path }, dl_cb, nil) end M.setProfilePhoto = setProfilePhoto -- Deletes profile photo. -- If something changes, updateUser will be sent -- @profile_photo_id Identifier of profile photo to delete local function deleteProfilePhoto(profile_photo_id) tdcli_function ({ ID = "DeleteProfilePhoto", profile_photo_id_ = profile_photo_id }, dl_cb, nil) end M.deleteProfilePhoto = deleteProfilePhoto -- Changes first and last names of logged in user. -- If something changes, updateUser will be sent -- @first_name New value of user first name, 1-255 characters -- @last_name New value of optional user last name, 0-255 characters local function changeName(first_name, last_name) tdcli_function ({ ID = "ChangeName", first_name_ = first_name, last_name_ = last_name }, dl_cb, nil) end M.changeName = changeName -- Changes about information of logged in user -- @about New value of userFull.about, 0-255 characters local function changeAbout(about) tdcli_function ({ ID = "ChangeAbout", about_ = about }, dl_cb, nil) end M.changeAbout = changeAbout -- Changes username of logged in user. -- If something changes, updateUser will be sent -- @username New value of username. Use empty string to remove username local function changeUsername(username) tdcli_function ({ ID = "ChangeUsername", username_ = username }, dl_cb, nil) end M.changeUsername = changeUsername -- Changes user's phone number and sends authentication code to the new user's phone number. -- Returns authStateWaitCode with information about sent code on success -- @phone_number New user's phone number in any reasonable format -- @allow_flash_call Pass True, if code can be sent via flash call to the specified phone number -- @is_current_phone_number Pass true, if the phone number is used on the current device. Ignored if allow_flash_call is False local function changePhoneNumber(phone_number, allow_flash_call, is_current_phone_number) tdcli_function ({ ID = "ChangePhoneNumber", phone_number_ = phone_number, allow_flash_call_ = allow_flash_call, is_current_phone_number_ = is_current_phone_number }, dl_cb, nil) end M.changePhoneNumber = changePhoneNumber -- Resends authentication code sent to change user's phone number. -- Works only if in previously received authStateWaitCode next_code_type was not null. -- Returns authStateWaitCode on success local function resendChangePhoneNumberCode() tdcli_function ({ ID = "ResendChangePhoneNumberCode", }, dl_cb, nil) end M.resendChangePhoneNumberCode = resendChangePhoneNumberCode -- Checks authentication code sent to change user's phone number. -- Returns authStateOk on success -- @code Verification code from SMS, voice call or flash call local function checkChangePhoneNumberCode(code) tdcli_function ({ ID = "CheckChangePhoneNumberCode", code_ = code }, dl_cb, nil) end M.checkChangePhoneNumberCode = checkChangePhoneNumberCode -- Returns all active sessions of logged in user local function getActiveSessions() tdcli_function ({ ID = "GetActiveSessions", }, dl_cb, nil) end M.getActiveSessions = getActiveSessions -- Terminates another session of logged in user -- @session_id Session identifier local function terminateSession(session_id) tdcli_function ({ ID = "TerminateSession", session_id_ = session_id }, dl_cb, nil) end M.terminateSession = terminateSession -- Terminates all other sessions of logged in user local function terminateAllOtherSessions() tdcli_function ({ ID = "TerminateAllOtherSessions", }, dl_cb, nil) end M.terminateAllOtherSessions = terminateAllOtherSessions -- Gives or revokes all members of the group editor rights. -- Needs creator privileges in the group -- @group_id Identifier of the group -- @anyone_can_edit New value of anyone_can_edit local function toggleGroupEditors(group_id, anyone_can_edit) tdcli_function ({ ID = "ToggleGroupEditors", group_id_ = getChatId(group_id).ID, anyone_can_edit_ = anyone_can_edit }, dl_cb, nil) end M.toggleGroupEditors = toggleGroupEditors -- Changes username of the channel. -- Needs creator privileges in the channel -- @channel_id Identifier of the channel -- @username New value of username. Use empty string to remove username local function changeChannelUsername(channel_id, username) tdcli_function ({ ID = "ChangeChannelUsername", channel_id_ = getChatId(channel_id).ID, username_ = username }, dl_cb, nil) end M.changeChannelUsername = changeChannelUsername -- Gives or revokes right to invite new members to all current members of the channel. -- Needs creator privileges in the channel. -- Available only for supergroups -- @channel_id Identifier of the channel -- @anyone_can_invite New value of anyone_can_invite local function toggleChannelInvites(channel_id, anyone_can_invite) tdcli_function ({ ID = "ToggleChannelInvites", channel_id_ = getChatId(channel_id).ID, anyone_can_invite_ = anyone_can_invite }, dl_cb, nil) end M.toggleChannelInvites = toggleChannelInvites -- Enables or disables sender signature on sent messages in the channel. -- Needs creator privileges in the channel. -- Not available for supergroups -- @channel_id Identifier of the channel -- @sign_messages New value of sign_messages local function toggleChannelSignMessages(channel_id, sign_messages) tdcli_function ({ ID = "ToggleChannelSignMessages", channel_id_ = getChatId(channel_id).ID, sign_messages_ = sign_messages }, dl_cb, nil) end M.toggleChannelSignMessages = toggleChannelSignMessages -- Changes information about the channel. -- Needs creator privileges in the broadcast channel or editor privileges in the supergroup channel -- @channel_id Identifier of the channel -- @about New value of about, 0-255 characters local function changeChannelAbout(channel_id, about) tdcli_function ({ ID = "ChangeChannelAbout", channel_id_ = getChatId(channel_id).ID, about_ = about }, dl_cb, nil) end M.changeChannelAbout = changeChannelAbout -- Pins a message in a supergroup channel chat. -- Needs editor privileges in the channel -- @channel_id Identifier of the channel -- @message_id Identifier of the new pinned message -- @disable_notification True, if there should be no notification about the pinned message local function pinChannelMessage(channel_id, message_id, disable_notification) tdcli_function ({ ID = "PinChannelMessage", channel_id_ = getChatId(channel_id).ID, message_id_ = message_id, disable_notification_ = disable_notification }, dl_cb, nil) end M.pinChannelMessage = pinChannelMessage -- Removes pinned message in the supergroup channel. -- Needs editor privileges in the channel -- @channel_id Identifier of the channel local function unpinChannelMessage(channel_id) tdcli_function ({ ID = "UnpinChannelMessage", channel_id_ = getChatId(channel_id).ID }, dl_cb, nil) end M.unpinChannelMessage = unpinChannelMessage -- Reports some supergroup channel messages from a user as spam messages -- @channel_id Channel identifier -- @user_id User identifier -- @message_ids Identifiers of messages sent in the supergroup by the user, the list should be non-empty local function reportChannelSpam(channel_id, user_id, message_ids) tdcli_function ({ ID = "ReportChannelSpam", channel_id_ = getChatId(channel_id).ID, user_id_ = user_id, message_ids_ = message_ids -- vector }, dl_cb, nil) end M.reportChannelSpam = reportChannelSpam -- Returns information about channel members or kicked from channel users. -- Can be used only if channel_full->can_get_members == true -- @channel_id Identifier of the channel -- @filter Kind of channel users to return, defaults to channelMembersRecent -- @offset Number of channel users to skip -- @limit Maximum number of users be returned, can't be greater than 200 -- filter = Recent|Administrators|Kicked|Bots local function getChannelMembers(channel_id, offset, filter, limit) if not limit or limit > 200 then limit = 200 end tdcli_function ({ ID = "GetChannelMembers", channel_id_ = getChatId(channel_id).ID, filter_ = { ID = "ChannelMembers" .. filter }, offset_ = offset, limit_ = limit }, dl_cb, nil) end M.getChannelMembers = getChannelMembers -- Deletes channel along with all messages in corresponding chat. -- Releases channel username and removes all members. -- Needs creator privileges in the channel. -- Channels with more than 1000 members can't be deleted -- @channel_id Identifier of the channel local function deleteChannel(channel_id) tdcli_function ({ ID = "DeleteChannel", channel_id_ = getChatId(channel_id).ID }, dl_cb, nil) end M.deleteChannel = deleteChannel -- Returns user that can be contacted to get support local function getSupportUser() tdcli_function ({ ID = "GetSupportUser", }, dl_cb, nil) end M.getSupportUser = getSupportUser -- Returns background wallpapers local function getWallpapers() tdcli_function ({ ID = "GetWallpapers", }, dl_cb, nil) end M.getWallpapers = getWallpapers local function registerDevice() tdcli_function ({ ID = "RegisterDevice", }, dl_cb, nil) end M.registerDevice = registerDevice local function getDeviceTokens() tdcli_function ({ ID = "GetDeviceTokens", }, dl_cb, nil) end M.getDeviceTokens = getDeviceTokens -- Changes privacy settings -- @key Privacy key -- @rules New privacy rules -- key = UserStatus|ChatInvite -- rules = AllowAll|AllowContacts|AllowUsers(user_ids)|DisallowAll|DisallowContacts|DisallowUsers(user_ids) local function setPrivacy(key, rules, user_ids) if user_ids and rules:match('Allow') then rule = 'AllowUsers' elseif user_ids and rules:match('Disallow') then rule = 'DisallowUsers' end tdcli_function ({ ID = "SetPrivacy", key_ = { ID = 'PrivacyKey' .. key, }, rules_ = { ID = 'PrivacyRules', rules_ = { [0] = { ID = 'PrivacyRule' .. rules, }, { ID = 'PrivacyRule' .. rule, user_ids_ = user_ids }, }, }, }, dl_cb, nil) end M.setPrivacy = setPrivacy -- Returns current privacy settings -- @key Privacy key -- key = UserStatus|ChatInvite local function getPrivacy(key) tdcli_function ({ ID = "GetPrivacy", key_ = { ID = "PrivacyKey" .. key }, }, dl_cb, nil) end M.getPrivacy = getPrivacy -- Returns value of an option by its name. -- See list of available options on https://core.telegram.org/tdlib/options -- @name Name of the option local function getOption(name) tdcli_function ({ ID = "GetOption", name_ = name }, dl_cb, nil) end M.getOption = getOption -- Sets value of an option. -- See list of available options on https://core.telegram.org/tdlib/options. -- Only writable options can be set -- @name Name of the option -- @value New value of the option local function setOption(name, option, value) tdcli_function ({ ID = "SetOption", name_ = name, value_ = { ID = 'Option' .. option, value_ = value }, }, dl_cb, nil) end M.setOption = setOption -- Changes period of inactivity, after which the account of currently logged in user will be automatically deleted -- @ttl New account TTL local function changeAccountTtl(days) tdcli_function ({ ID = "ChangeAccountTtl", ttl_ = { ID = "AccountTtl", days_ = days }, }, dl_cb, nil) end M.changeAccountTtl = changeAccountTtl -- Returns period of inactivity, after which the account of currently logged in user will be automatically deleted local function getAccountTtl() tdcli_function ({ ID = "GetAccountTtl", }, dl_cb, nil) end M.getAccountTtl = getAccountTtl -- Deletes the account of currently logged in user, deleting from the server all information associated with it. -- Account's phone number can be used to create new account, but only once in two weeks -- @reason Optional reason of account deletion local function deleteAccount(reason) tdcli_function ({ ID = "DeleteAccount", reason_ = reason }, dl_cb, nil) end M.deleteAccount = deleteAccount -- Returns current chat report spam state -- @chat_id Chat identifier local function getChatReportSpamState(chat_id) tdcli_function ({ ID = "GetChatReportSpamState", chat_id_ = chat_id }, dl_cb, nil) end M.getChatReportSpamState = getChatReportSpamState -- Reports chat as a spam chat or as not a spam chat. -- Can be used only if ChatReportSpamState.can_report_spam is true. -- After this request ChatReportSpamState.can_report_spam became false forever -- @chat_id Chat identifier -- @is_spam_chat If true, chat will be reported as a spam chat, otherwise it will be marked as not a spam chat local function changeChatReportSpamState(chat_id, is_spam_chat) tdcli_function ({ ID = "ChangeChatReportSpamState", chat_id_ = chat_id, is_spam_chat_ = is_spam_chat }, dl_cb, nil) end M.changeChatReportSpamState = changeChatReportSpamState -- Bots only. -- Informs server about number of pending bot updates if they aren't processed for a long time -- @pending_update_count Number of pending updates -- @error_message Last error's message local function setBotUpdatesStatus(pending_update_count, error_message) tdcli_function ({ ID = "SetBotUpdatesStatus", pending_update_count_ = pending_update_count, error_message_ = error_message }, dl_cb, nil) end M.setBotUpdatesStatus = setBotUpdatesStatus -- Returns Ok after specified amount of the time passed -- @seconds Number of seconds before that function returns local function setAlarm(seconds) tdcli_function ({ ID = "SetAlarm", seconds_ = seconds }, dl_cb, nil) end M.setAlarm = setAlarm -- These functions below are an effort to mimic telegram-cli console commands -- -- Sets profile username local function account_change_username(username) changeUsername(username) end M.account_change_username = account_change_username -- Sets profile name local function account_change_name(first_name, last_name) changeName(first_name, last_name) end M.account_change_name = account_change_name -- Sets profile photo. Photo will be cropped to square local function account_change_photo(photo_path) setProfilePhoto(photo_path) end M.account_change_photo = account_change_photo -- Tries to add user to contact list local function add_contact(phone, first_name, last_name, user_id) importContacts(phone, first_name, last_name, user_id) end M.add_contact = add_contact -- Blocks user local function block_user(user_id) blockUser(user_id) end M.block_user = block_user -- Gets channel admins local function channel_get_admins(channel_id) getChannelMembers(channel_id, 0, 'Administrators') end M.channel_get_admins = channel_get_admins -- Gets channel bots local function channel_get_bots(channel_id) getChannelMembers(channel_id, 0, 'Bots') end M.channel_get_bots = channel_get_bots -- Gets channel kicked members local function channel_get_kicked(channel_id) getChannelMembers(channel_id, 0, 'Kicked') end M.channel_get_kicked = channel_get_kicked -- Gets channel recent members local function channel_get_members(channel_id) getChannelMembers(channel_id, 0, 'Recent') end M.channel_get_members = channel_get_members -- Changes channel username local function channel_change_about(channel_id, about) changeChannelAbout(channel_id, about) end M.channel_change_about = channel_change_about -- Changes channel about info local function channel_change_username(channel_id, username) changeChannelUsername(channel_id, username) end M.channel_change_username = channel_change_username -- changes value of basic channel parameters. -- param=sign|invites local function channel_edit(channel_id, param, enabled) if param:lower() == 'sign' then toggleChannelSignMessages(channel_id, enabled) elseif param:lower() == 'invites' then toggleChannelInvites(channel_id, enabled) end end M.channel_edit = channel_edit -- Adds user to chat. -- Sends him last msgs_to_forward messages (only for group chats) from this chat local function chat_add_user(chat_id, user_id, msgs_to_forward) addChatMember(chat_id, user_id, msgs_to_forward) end M.chat_add_user = chat_add_user -- Changes chat photo. Photo will be cropped to square local function chat_change_photo(chat_id, file) changeChatPhoto(chat_id, file) end M.chat_change_photo = chat_change_photo -- Renames chat local function chat_change_title(chat_id, title) changeChatTitle(chat_id, title) end M.chat_change_title = chat_change_title -- changes user's role in chat. -- role=Creator|Editor|Moderator|Member|Left|Kicked local function chat_change_role(chat_id, user_id, role) changeChatMemberStatus(chat_id, user_id, role) end M.chat_change_role = chat_change_role -- Deletes user from chat local function chat_del_user(chat_id, user_id) changeChatMemberStatus(chat_id, user_id, 'Kicked') end M.chat_del_user = chat_del_user -- Prints info about chat local function chat_info(chat_id) getChat(chat_id) end M.chat_info = chat_info -- Joins to chat (by invite link) local function chat_join(invite_link) importChatInviteLink(invite_link) end M.chat_join = chat_join -- Leaves chat local function chat_leave(chat_id, user_id) changeChatMemberStatus(chat_id, user_id, "Left") end M.chat_leave = chat_leave -- Print info about chat by link local function chat_check_invite_link(invite_link) checkChatInviteLink(invite_link) end M.chat_check_invite_link = chat_check_invite_link -- Creates broadcast channel local function chat_create_broadcast(title, about) createNewChannelChat(title, 0, about) end M.chat_create_broadcast = chat_create_broadcast -- Creates group chat local function chat_create_group(title, user_ids) createNewGroupChat(title, user_ids) end M.chat_create_group = chat_create_group -- Creates supergroup channel local function chat_create_supergroup(title, about) createNewChannelChat(title, 1, about) end M.chat_create_supergroup = chat_create_supergroup -- Exports new invite link (and invalidates previous) local function chat_export_invite_link(chat_id) exportChatInviteLink(chat_id) end M.chat_export_invite_link = chat_export_invite_link -- Get chat by invite link and joins if possible local function chat_import_invite_link(invite_link) importChatInviteLink(invite_link) end M.chat_import_invite_link = chat_import_invite_link -- Prints contact list local function contact_list(limit) searchContacts("", limit) end M.contact_list = contact_list -- Deletes user from contact list local function contact_delete(user_ids) deleteContacts(user_ids) end M.contact_delete = contact_delete -- Deletes message local function delete_msg(chat_id, message_ids) deleteMessages(chat_id, message_ids) end M.delete_msg = delete_msg -- List of last conversations local function dialog_list(limit) searchChats('', limit) end M.dialog_list = dialog_list -- Forwards message to peer. Forward to secret chats is forbidden local function fwd(chat_id, from_chat_id, message_ids) forwardMessages(chat_id, from_chat_id, message_ids, 0) end M.fwd = fwd -- Get message by id local function get_message(chat_id, message_id) getMessage(chat_id, message_id) end M.get_message = get_message -- Upgrades group to supergroup local function group_upgrade(chat_id) migrateGroupChatToChannelChat(chat_id) end M.group_upgrade = group_upgrade -- Prints messages with this peer. Also marks messages as read local function history(chat_id, limit, offset) getChatHistory(chat_id, 0, offset, limit) end M.history = history -- Marks messages with peer as read local function mark_read(chat_id, message_ids) viewMessages(chat_id, message_ids) end M.mark_read = mark_read -- Sends text message to peer local function msg(chat_id, text) sendMessage(chat_id, 0, 0, text, 1) end M.msg = msg -- mutes chat for specified number of seconds (default 60) local function mute(chat_id, mute_for) setNotificationSettings('Chat', chat_id, mute_for or 60, 0) end M.mute = mute -- local function pin_message(channel_id, message_id, disable_notification) pinChannelMessage(channel_id, message_id, disable_notification) end M.pin_message = pin_message -- Tries to push inline button local function push_button(message, button_id) end M.push_button = push_button -- Find chat by username local function resolve_username(username) tdcli.searchChats(username, 20) end M.resolve_username = resolve_username -- Sends text message to peer local function reply(chat_id, msg_id, text) sendMessage(chat_id, msg_id, 0, text, 1) end M.reply = reply -- Replies to peer with file -- type = Animation|Audio|Document|Photo|Sticker|Video|Voice local function reply_file(chat_id, msg_id, type, file, caption) tdcli_function ({ ID = "SendMessage", chat_id_ = chat_id, reply_to_message_id_ = msg_id, disable_notification_ = 0, from_background_ = 1, reply_markup_ = nil, input_message_content_ = getInputMessageContent(file, type, caption), }, dl_cb, nil) end M.reply_file = reply_file -- Forwards message to peer. Forward to secret chats is forbidden local function reply_fwd(msg_id, fwd_id) end M.reply_fwd = reply_fwd -- Sends geo location local function reply_location(chat_id, msg_id, latitude, longitude) tdcli_function ({ ID="SendMessage", chat_id_=chat_id, reply_to_message_id_=msg_id, disable_notification_=0, from_background_=1, reply_markup_=nil, input_message_content_={ ID="InputMessageLocation", location_={ ID = "Location", latitude_ = latitude, longitude_ = longitude }, }, }, dl_cb, nil) end M.reply_location = reply_location -- Search for pattern in messages from date from to date to (unixtime) in messages with peer (if peer not present, in all messages) local function search(chat_id, query, from_message_id, limit, filter) searchChatMessages(chat_id, query, from_message_id, limit, filter) end M.search = search -- Sends file to peer -- type = Animation|Audio|Document|Photo|Sticker|Video|Voice local function send_file(chat_id, type, file, caption) tdcli_function ({ ID = "SendMessage", chat_id_ = chat_id, reply_to_message_id_ = 0, disable_notification_ = 0, from_background_ = 1, reply_markup_ = nil, input_message_content_ = getInputMessageContent(file, type, caption), }, dl_cb, nil) end M.send_file = send_file -- Sends geo location local function send_location(chat_id, latitude, longitude) tdcli_function ({ ID = "SendMessage", chat_id_ = chat_id, reply_to_message_id_ = 0, disable_notification_ = 0, from_background_ = 1, reply_markup_ = nil, input_message_content_ = { ID = "InputMessageLocation", location_ = { ID = "Location", latitude_ = latitude, longitude_ = longitude }, }, }, dl_cb, nil) end M.send_location = send_location -- Sends typing action. -- action = Typing|Cancel|RecordVideo|UploadVideo|RecordVoice|UploadVoice|UploadPhoto|UploadDocument|GeoLocation|ChooseContact|StartPlayGame local function send_typing(chat_id, action, progress) sendChatAction(chat_id, action, progress) end M.send_typing = send_typing -- Adds bot to chat local function start_bot(user_id, chat_id, data) sendBotStartMessage(user_id, chat_id, 'start') end M.start_bot = start_bot -- sets timer (in seconds) local function timer(timeout) setAlarm(timeout) end M.timer = timer -- Unblock user local function unblock_user(user_id) unblockUser(user_id) end M.unblock_user = unblock_user -- unmutes chat local function unmute(chat_id) setNotificationSettings('Chat', chat_id, 0, 1) end M.unmute = unmute -- Message with a game -- @bot_user_id User identifier of a bot owned the game -- @game_short_name Game short name local function sendGame(chat_id, reply_to_message_id, disable_notification, from_background, reply_markup, bot_user_id, game_short_name) tdcli_function ({ ID = "SendMessage", chat_id_ = chat_id, reply_to_message_id_ = reply_to_message_id, disable_notification_ = disable_notification, from_background_ = from_background, reply_markup_ = reply_markup, input_message_content_ = { ID = "InputMessageGame", bot_user_id_ = bot_user_id, game_short_name_ = game_short_name }, }, dl_cb, nil) end M.sendGame = sendGame return M
gpl-3.0
Scavenge/darkstar
scripts/globals/items/homura_+1.lua
41
1068
----------------------------------------- -- ID: 16986 -- Item: Homura +1 -- Additional Effect: Fire Damage ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 10; if (math.random(0,99) >= chance) then return 0,0,0; else local dmg = math.random(6,23); local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(player, ELE_FIRE, target, dmg, params); dmg = dmg * applyResistanceAddEffect(player,target,ELE_FIRE,0); dmg = adjustForTarget(target,dmg,ELE_FIRE); dmg = finalMagicNonSpellAdjustments(player,target,ELE_FIRE,dmg); local message = MSGBASIC_ADD_EFFECT_DMG; if (dmg < 0) then message = MSGBASIC_ADD_EFFECT_HEAL; end return SUBEFFECT_FIRE_DAMAGE,message,dmg; end end;
gpl-3.0
caranicas/ThreeJS-Boilerplate
components/ammo.js/bullet/Demos/premake4.lua
5
3084
function createDemos( demos, incdirs, linknames) for _, name in ipairs(demos) do project ( "App_" .. name ) kind "ConsoleApp" targetdir ".." includedirs {incdirs} configuration { "Windows" } defines { "GLEW_STATIC"} links { "opengl32" } includedirs{ "../Glut" } libdirs {"../Glut"} files { "../build/bullet.rc" } configuration {"Windows", "x32"} links {"glew32s","glut32"} configuration {"Windows", "x64"} links {"glew64s", "glut64"} configuration {"MacOSX"} --print "hello" linkoptions { "-framework Carbon -framework OpenGL -framework AGL -framework Glut" } configuration {"not Windows", "not MacOSX"} links {"GL","GLU","glut"} configuration{} links { linknames } files { "./" .. name .. "/*.cpp" , "./" .. name .. "/*.h" } end end -- "CharacterDemo", fixme: it includes BspDemo files local localdemos = { "BasicDemo", "Box2dDemo", "BspDemo", "CcdPhysicsDemo", "CollisionDemo", "CollisionInterfaceDemo", "ConcaveConvexcastDemo", "ConcaveDemo", "ConcaveRaycastDemo", "ConstraintDemo", "ContinuousConvexCollision", "ConvexHullDistance", "DynamicControlDemo", "EPAPenDepthDemo", "ForkLiftDemo", "FeatherstoneMultiBodyDemo", "FractureDemo", "GenericJointDemo", "GimpactTestDemo", "GjkConvexCastDemo", "GyroscopicDemo", "InternalEdgeDemo", "MovingConcaveDemo", "MultiMaterialDemo", "RagdollDemo", "Raytracer", "RaytestDemo", "RollingFrictionDemo", "SimplexDemo", "SliderConstraintDemo", "TerrainDemo", "UserCollisionAlgorithm", "VehicleDemo", "VoronoiFractureDemo" } -- the following demos require custom include or link settings createDemos({"HelloWorld"},{"../src"},{"BulletDynamics","BulletCollision","LinearMath"}) createDemos(localdemos,{"../src","OpenGL"},{"OpenGLSupport","BulletDynamics", "BulletCollision", "LinearMath"}) createDemos({"ConvexDecompositionDemo"},{"../Extras/HACD","../Extras/ConvexDecomposition","../src","OpenGL"},{"OpenGLSupport","BulletDynamics", "BulletCollision", "LinearMath","HACD","ConvexDecomposition"}) createDemos({"SoftDemo"},{"../src","OpenGL"}, {"OpenGLSupport","BulletSoftBody", "BulletDynamics", "BulletCollision", "LinearMath"}) createDemos({"SerializeDemo"},{"../Extras/Serialize/BulletFileLoader","../Extras/Serialize/BulletWorldImporter","../src","OpenGL"},{"OpenGLSupport","BulletWorldImporter", "BulletFileLoader", "BulletSoftBody", "BulletDynamics", "BulletCollision", "LinearMath"}) createDemos({"BulletXmlImportDemo"},{"../Extras/Serialize/BulletFileLoader","../Extras/Serialize/BulletXmlWorldImporter", "../Extras/Serialize/BulletWorldImporter","../src","OpenGL"},{"OpenGLSupport","BulletXmlWorldImporter","BulletWorldImporter", "BulletFileLoader", "BulletSoftBody", "BulletDynamics", "BulletCollision", "LinearMath"}) include "OpenGL"
mit
Scavenge/darkstar
scripts/zones/Nashmau/npcs/HomePoint#1.lua
27
1255
----------------------------------- -- Area: Nashmau -- NPC: HomePoint#1 -- @pos -19.860 0.001 -25.441 53 ----------------------------------- package.loaded["scripts/zones/Nashmau/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Nashmau/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 66); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x21fc) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
Scavenge/darkstar
scripts/globals/items/plate_of_ratatouille.lua
12
1501
----------------------------------------- -- ID: 5731 -- Item: plate_of_ratatouille -- Food Effect: 3Hrs, All Races ----------------------------------------- -- Agility 5 -- Evasion 5 -- HP recovered while healing 2 -- MP recovered while healing 2 -- Undead Killer 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5731); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 5); target:addMod(MOD_EVA, 5); target:addMod(MOD_HPHEAL, 2); target:addMod(MOD_MPHEAL, 2); target:addMod(MOD_UNDEAD_KILLER, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 5); target:delMod(MOD_EVA, 5); target:delMod(MOD_HPHEAL, 2); target:delMod(MOD_MPHEAL, 2); target:delMod(MOD_UNDEAD_KILLER, 5); end;
gpl-3.0
Zero-K-Experiments/Zero-K-Experiments
gamedata/modularcomms/weapons/shotgun.lua
6
1494
local name = "commweapon_shotgun" local weaponDef = { name = [[Shotgun]], areaOfEffect = 32, burst = 3, burstRate = 0.03, coreThickness = 0.5, craterBoost = 0, craterMult = 0, customParams = { slot = [[5]], muzzleEffectFire = [[custom:HEAVY_CANNON_MUZZLE]], miscEffectFire = [[custom:RIOT_SHELL_L]], altforms = { green = { explosionGenerator = [[custom:BEAMWEAPON_HIT_GREEN]], rgbColor = [[0 1 0]], }, }, light_camera_height = 2000, light_color = [[0.3 0.3 0.05]], light_radius = 120, }, damage = { default = 32, subs = 1.6, }, duration = 0.02, explosionGenerator = [[custom:BEAMWEAPON_HIT_YELLOW]], fireStarter = 50, heightMod = 1, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 1, projectiles = 4, range = 290, reloadtime = 2, rgbColor = [[1 1 0]], soundHit = [[impacts/shotgun_impactv5]], soundStart = [[weapon/shotgun_firev4]], soundStartVolume = 0.6, soundTrigger = true, sprayangle = 1600, thickness = 2, tolerance = 10000, turret = true, weaponType = [[LaserCannon]], weaponVelocity = 880, } return name, weaponDef
gpl-2.0
roboplus12/roboplus
plugins/translate.lua
674
1637
--[[ -- Translate text using Google Translate. -- http://translate.google.com/translate_a/single?client=t&ie=UTF-8&oe=UTF-8&hl=en&dt=t&tl=en&sl=auto&text=hello --]] do function translate(source_lang, target_lang, text) local path = "http://translate.google.com/translate_a/single" -- URL query parameters local params = { client = "t", ie = "UTF-8", oe = "UTF-8", hl = "en", dt = "t", tl = target_lang or "en", sl = source_lang or "auto", text = URL.escape(text) } local query = format_http_params(params, true) local url = path..query local res, code = https.request(url) -- Return nil if error if code > 200 then return nil end local trans = res:gmatch("%[%[%[\"(.*)\"")():gsub("\"(.*)", "") return trans end function run(msg, matches) -- Third pattern if #matches == 1 then print("First") local text = matches[1] return translate(nil, nil, text) end -- Second pattern if #matches == 2 then print("Second") local target = matches[1] local text = matches[2] return translate(nil, target, text) end -- First pattern if #matches == 3 then print("Third") local source = matches[1] local target = matches[2] local text = matches[3] return translate(source, target, text) end end return { description = "Translate some text", usage = { "!translate text. Translate the text to English.", "!translate target_lang text.", "!translate source,target text", }, patterns = { "^!translate ([%w]+),([%a]+) (.+)", "^!translate ([%w]+) (.+)", "^!translate (.+)", }, run = run } end
gpl-2.0
purebn/secure
plugins/translate.lua
674
1637
--[[ -- Translate text using Google Translate. -- http://translate.google.com/translate_a/single?client=t&ie=UTF-8&oe=UTF-8&hl=en&dt=t&tl=en&sl=auto&text=hello --]] do function translate(source_lang, target_lang, text) local path = "http://translate.google.com/translate_a/single" -- URL query parameters local params = { client = "t", ie = "UTF-8", oe = "UTF-8", hl = "en", dt = "t", tl = target_lang or "en", sl = source_lang or "auto", text = URL.escape(text) } local query = format_http_params(params, true) local url = path..query local res, code = https.request(url) -- Return nil if error if code > 200 then return nil end local trans = res:gmatch("%[%[%[\"(.*)\"")():gsub("\"(.*)", "") return trans end function run(msg, matches) -- Third pattern if #matches == 1 then print("First") local text = matches[1] return translate(nil, nil, text) end -- Second pattern if #matches == 2 then print("Second") local target = matches[1] local text = matches[2] return translate(nil, target, text) end -- First pattern if #matches == 3 then print("Third") local source = matches[1] local target = matches[2] local text = matches[3] return translate(source, target, text) end end return { description = "Translate some text", usage = { "!translate text. Translate the text to English.", "!translate target_lang text.", "!translate source,target text", }, patterns = { "^!translate ([%w]+),([%a]+) (.+)", "^!translate ([%w]+) (.+)", "^!translate (.+)", }, run = run } end
gpl-2.0
Zero-K-Experiments/Zero-K-Experiments
scripts/panther.lua
9
5949
-- linear constant 65536 include "constants.lua" local main, nose, nosefan1, nosefan2, turret, sleeve, barrel1, flare1, barrel2, flare2, sparkcenter, sparkcenter2, door1, door2, rud1, rud2, mainfan1, mainfan2, wheels1, wheels2, wheels3, wheels4, wheels5, wheels6, wheels7, tracks1, tracks2, tracks3, tracks4 = piece('main', 'nose', 'nosefan1', 'nosefan2', 'turret', 'sleeve', 'barrel1', 'flare1', 'barrel2', 'flare2', 'sparkcenter', 'sparkcenter2', 'door1', 'door2', 'rud1', 'rud2', 'mainfan1', 'mainfan2', 'wheels1', 'wheels2', 'wheels3', 'wheels4', 'wheels5', 'wheels6', 'wheels7', 'tracks1', 'tracks2', 'tracks3', 'tracks4') local moving, once, animCount = false,true,0 -- Signal definitions local SIG_Walk = 2 local SIG_Restore = 1 local SIG_AIM1 = 1 local ANIM_SPEED = 50 local RESTORE_DELAY = 3000 local TURRET_TURN_SPEED = 500 local GUN_TURN_SPEED = 150 local WHEEL_TURN_SPEED1 = 480 local WHEEL_TURN_SPEED1_ACCELERATION = 75 local WHEEL_TURN_SPEED1_DECELERATION = 200 local smokePiece = {main, turret} local function RestoreAfterDelay() Signal(SIG_Restore) SetSignalMask(SIG_Restore) Sleep(RESTORE_DELAY) Turn(turret, y_axis, math.rad(0), math.rad(TURRET_TURN_SPEED/2)) Turn(sleeve, x_axis, math.rad(0), math.rad(TURRET_TURN_SPEED/2)) end function AnimationControl() local current_tracks = 0 while true do EmitSfx(sparkcenter, 1024) Move(sparkcenter, z_axis, 2, 1) WaitForMove(sparkcenter, z_axis) Move(sparkcenter, z_axis, 0, 1) WaitForMove(sparkcenter, z_axis) if moving or once then if current_tracks == 0 then Show(tracks1) Hide(tracks4) current_tracks = current_tracks + 1 elseif current_tracks == 1 then Show(tracks2) Hide(tracks1) current_tracks = current_tracks + 1 elseif current_tracks == 2 then Show(tracks3) Hide(tracks2) current_tracks = current_tracks + 1 elseif current_tracks == 3 then Show(tracks4) Hide(tracks3) current_tracks = 0 end once = false end animCount = animCount + 1 Sleep(ANIM_SPEED) end end local function Moving() Signal(SIG_Walk) SetSignalMask(SIG_Walk) Spin(wheels1, x_axis, WHEEL_TURN_SPEED1, WHEEL_TURN_SPEED1_ACCELERATION) Spin(wheels2, x_axis, WHEEL_TURN_SPEED1, WHEEL_TURN_SPEED1_ACCELERATION) Spin(wheels3, x_axis, WHEEL_TURN_SPEED1, WHEEL_TURN_SPEED1_ACCELERATION) Spin(wheels4, x_axis, WHEEL_TURN_SPEED1, WHEEL_TURN_SPEED1_ACCELERATION) Spin(wheels5, x_axis, WHEEL_TURN_SPEED1, WHEEL_TURN_SPEED1_ACCELERATION) Spin(wheels6, x_axis, WHEEL_TURN_SPEED1, WHEEL_TURN_SPEED1_ACCELERATION) Spin(wheels7, x_axis, WHEEL_TURN_SPEED1, WHEEL_TURN_SPEED1_ACCELERATION) end local function Stopping() Signal(SIG_Walk) SetSignalMask(SIG_Walk) -- I don't like insta braking. It's not perfect but works for most cases. -- Probably looks goofy when the unit is turtling,, i.e. does not become faster as time increases.. once = animCount*ANIM_SPEED/1000 StopSpin(wheels1, x_axis, WHEEL_TURN_SPEED1_DECELERATION) StopSpin(wheels2, x_axis, WHEEL_TURN_SPEED1_DECELERATION) StopSpin(wheels3, x_axis, WHEEL_TURN_SPEED1_DECELERATION) StopSpin(wheels4, x_axis, WHEEL_TURN_SPEED1_DECELERATION) StopSpin(wheels5, x_axis, WHEEL_TURN_SPEED1_DECELERATION) StopSpin(wheels6, x_axis, WHEEL_TURN_SPEED1_DECELERATION) StopSpin(wheels7, x_axis, WHEEL_TURN_SPEED1_DECELERATION) end function script.StartMoving() moving = true animCount = 0 StartThread(Moving) end function script.StopMoving() moving = false StartThread(Stopping) end -- Weapons function script.AimFromWeapon1() return turret end function script.QueryWeapon1() return sparkcenter2 end function script.AimWeapon1(heading, pitch) Signal(SIG_AIM1) SetSignalMask(SIG_AIM1) Turn(turret, y_axis, heading, math.rad(TURRET_TURN_SPEED)) Turn(sleeve, x_axis, -pitch, math.rad(GUN_TURN_SPEED)) WaitForTurn(turret, y_axis) WaitForTurn(sleeve, x_axis) StartThread(RestoreAfterDelay) return true --[[ local fx, _, fz = Spring.GetUnitPiecePosition(unitID, firepoint) local tx, _, tz = Spring.GetUnitPiecePosition(unitID, turret) local pieceHeading = math.pi * Spring.GetHeadingFromVector(fx-tx,fz-tz) * 2^-15 local headingDiff = math.abs((heading+pieceHeading)%(math.pi*2) - math.pi) if headingDiff > 2.6 then Turn(turret, y_axis, heading) Turn(sleeve, x_axis, -pitch) StartThread(RestoreAfterDelay) -- EmitSfx works if the turret takes no time to turn and there is no waitForTurn return true else Turn(turret, y_axis, heading, math.rad(TURRET_TURN_SPEED)) Turn(sleeve, x_axis, -pitch, math.rad(GUN_TURN_SPEED)) StartThread(RestoreAfterDelay) return false end --]] end local function Recoil() Move(barrel1, z_axis, -3.5) Move(barrel2, z_axis, -3.5) Sleep(150) Move(barrel1, z_axis, 0, 10) Move(barrel2, z_axis, 0, 10) end function script.Shot(num) --[[ Turn(firepoint, y_axis, math.rad(25)) EmitSfx(firepoint, FIRE_W2) Turn(firepoint, y_axis, - math.rad(25)) EmitSfx(firepoint, FIRE_W2) Turn(firepoint, y_axis, 0) --]] StartThread(Recoil) end function script.Killed(severity, maxHealth) severity = severity / maxHealth if severity <= 0.25 then corpsetype = 1 Explode(main, sfxNone) Explode(turret, sfxNone) return 1 end if severity <= 0.50 then corpsetype = 1 Explode(main, sfxNone) Explode(turret,sfxNone) Explode(barrel1, sfxFall + sfxSmoke + sfxFire) return 1 else corpsetype = 2 Explode(main, sfxNone) Explode(turret, sfxNone) Explode(barrel2, sfxFall + sfxSmoke + sfxFire) Explode(tracks1, sfxShatter + sfxSmoke + sfxFire) Hide(tracks2) Hide(tracks3) Hide(tracks4) return 2 end return corpsetype end function script.Create() moving = false Turn(sparkcenter2, x_axis, math.rad(7)) Hide(tracks1) Hide(tracks2) Hide(tracks3) while select(5, Spring.GetUnitHealth(unitID)) < 1 do Sleep(250) end StartThread(AnimationControl) StartThread(SmokeUnit, smokePiece) end
gpl-2.0
Scavenge/darkstar
scripts/globals/items/rolanberry.lua
12
1184
----------------------------------------- -- ID: 4365 -- Item: rolanberry -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility -4 -- Intelligence 2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4365); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, -4); target:addMod(MOD_INT, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, -4); target:delMod(MOD_INT, 2); end;
gpl-3.0
OpenPrograms/mpmxyz-Programs
usr/lib/mpm/values.lua
3
4526
----------------------------------------------------- --name : lib/mpm/hashset.lua --description: allows using raw values or getters for the same property --author : mpmxyz --github page: https://github.com/mpmxyz/ocprograms --forum page : none ----------------------------------------------------- local values = {} --type sets used to extract values values.types_callable = { ["function"] = true, --due to component wrappers: ["table"] = true, } values.types_indexable = { ["table"] = true, } --values.get(value, forceCall, key, ...) -> value --If the given value is a primitive value, it is simply returned. --If it is a function it is called with the parameters (key, ...) and the first result is returned. --If it is a table it is called as a function if forceCall is true. --Else it will be indexed using key. The other parameters are applied recursively if they aren't nil. function values.get(value, forceCall, key, ...) local typ = type(value) if values.types_indexable[typ] and key ~= nil and not forceCall then value = value[key] --if (...) ~= nil then --multidimensional keys: applied recursively return values.get(value, false, ...) --end elseif values.types_callable[typ] then return (value(key, ...)) end return value end function values.set(target, value, forceCall, key, ...) local typ = type(target) if values.types_indexable[typ] and key ~= nil and not forceCall then if (...) ~= nil then --multidimensional keys: applied recursively return values.set(target[key], value, false, ...) else target[key] = value return true end elseif values.types_callable[typ] then if key == nil then target(value) else --TODO: better format? target(value, key, ...) end return true end return false end --type sets used to check value types values.types_number = { --raw ["number"] = true, --via callable or indexable object ["function"] = true, ["table"] = true, } values.types_string = { --raw ["string"] = true, --via callable or indexable object ["function"] = true, ["table"] = true, } values.types_table = { --raw ["table"] = true, --via callable object ["function"] = true, } values.types_raw_number = { --raw only ["number"] = true, } values.types_raw_string = { --raw only ["string"] = true, } values.types_raw_table = { --raw only ["table"] = true, } --values.check(value, name, permitted_types, wrongTypeText, default) -> value or default --This function checks if the given value has a valid type. It returns the value or the given default value if the value is nil. --'value' is the value being checked. --'name' is a name used for error descriptions. --'permitted_types' is a table with type strings as keys. All 'true' values mark a valid type. --'wrongTypeText' is a string appended to the name to get the error message if the value type isn't valid. --'default' is used as the output value if the input value is nil. Throws an error if both the value and 'default' are nil. function values.check(value, name, permittedTypes, wrongTypeText, default) if not permittedTypes[type(value)] then if value == nil then if default == nil then error("'" .. name .. "' is missing!") end return default else error("'" .. name .. "' " .. wrongTypeText) end end return value end local checkTables = { checkNumber = values.types_number, checkString = values.types_string, checkTable = values.types_table, checkRawNumber = values.types_raw_number, checkRawString = values.types_raw_string, checkRawTable = values.types_raw_table, checkCallable = values.types_callable, } local checkMessages = { checkNumber = "has to be a number or a callable object!", checkString = "has to be a string or a callable object!", checkTable = "has to be a table or a callable object!", checkRawNumber = "has to be a number!", checkRawString = "has to be a string!", checkRawTable = "has to be a table!", checkCallable = "has to be a callable object!", } for name, permittedTypes in pairs(checkTables) do local msg = checkMessages[name] --Asserts that the given value has the correct type or can be converted to one by using values.get(). --(throws an error using the given name otherwise) values[name] = function(value, name, default) return values.check(value, name, permittedTypes, msg, default) end end return values
mit
Scavenge/darkstar
scripts/zones/Yorcia_Weald_U/Zone.lua
17
1097
----------------------------------- -- -- Zone: Yorcia Weald U -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Yorcia_Weald_U/TextIDs"] = nil; require("scripts/zones/Yorcia_Weald_U/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Western_Adoulin/npcs/Oka_Qhantari.lua
14
1311
----------------------------------- -- Area: Western Adoulin -- NPC: Oka Qhantari -- Type: Standard NPC and Quest NPC -- Involved With Quest: 'Order Up' -- @zone 256 -- @pos -30 3 -6 ----------------------------------- require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local Order_Up = player:getQuestStatus(ADOULIN, ORDER_UP); local Order_Oka_Qhantari = player:getMaskBit(player:getVar("Order_Up_NPCs"), 9); if ((Order_Up == QUEST_ACCEPTED) and (not Order_Oka_Qhantari)) then -- Progresses Quest: 'Order Up' player:startEvent(0x0047); else -- Standard Dialogue player:startEvent(0x01FF); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid == 0x0047) then -- Progresses Quest: 'Order Up' player:setMaskBit("Order_Up_NPCs", 9, true); end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Lower_Jeuno/npcs/Guttrix.lua
13
4107
----------------------------------- -- Area: Lower Jeuno -- NPC: Guttrix -- Starts and Finishes Quest: The Goblin Tailor -- @zone 245 -- @pos -36.010 4.499 -139.714 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Lower_Jeuno/TextIDs"); --[[----------------------------------------------- Description: rse = race, { [1] body, [2] hands, [3] legs, [4] feet } --]]----------------------------------------------- local rse_map = { 1,{12654,12761,12871,13015}, -- Male Hume 2,{12655,12762,12872,13016}, -- Female Hume 3,{12656,12763,12873,13017}, -- Male Elvaan 4,{12657,12764,12874,13018}, -- Female Elvaan 5,{12658,12765,12875,13019}, -- Male Taru-Taru 6,{12658,12765,12875,13019}, -- Female Taru-Taru 7,{12659,12766,12876,13020}, -- Mithra 8,{12660,12767,12877,13021}};-- Galka function hasRSE(player) local rse = 0; local race = player:getRace(); for raceindex = 1, #rse_map, 2 do if (race == rse_map[raceindex]) then --matched race for rseindex = 1, #rse_map[raceindex + 1], 1 do --loop rse for this race if (player:hasItem(rse_map[raceindex+1][rseindex])) then rse = rse + (2 ^ (rseindex - 1)); end end end end return rse; end; function getRSE(player, option) local race = player:getRace(); for raceindex = 1, #rse_map, 2 do if (race == rse_map[raceindex]) then --matched race return rse_map[raceindex+1][option]; end end return -1; end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local pFame = player:getFameLevel(JEUNO); local pRace = player:getRace(); local pLevel = player:getMainLvl(); local questStatus = player:getQuestStatus(JEUNO,THE_GOBLIN_TAILOR); local rseGear = hasRSE(player); local rseRace = VanadielRSERace(); local rseLocation = VanadielRSELocation(); if (pLevel >= 10 and pFame >= 3) then if (rseGear < 15 ) then if (questStatus == QUEST_AVAILABLE) then player:startEvent(0x2720,rseLocation,rseRace); elseif (questStatus >= QUEST_ACCEPTED and player:hasKeyItem(MAGICAL_PATTERN) and rseRace == pRace) then player:startEvent(0x2722,rseGear); else player:startEvent(0x2721,rseLocation,rseRace); end else player:startEvent(0x2723); end else player:startEvent(0x2724); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local questStatus = player:getQuestStatus(JEUNO,THE_GOBLIN_TAILOR); if (csid == 0x2720) then player:addQuest(JEUNO,THE_GOBLIN_TAILOR); elseif (csid == 0x2722 and option >= 1 and option <= 4) then local rseGear = getRSE(player,option); if (player:getFreeSlotsCount() < 1) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,rseGear); else if (questStatus == QUEST_ACCEPTED) then player:addFame(JEUNO, 30); player:completeQuest(JEUNO,THE_GOBLIN_TAILOR); end player:delKeyItem(MAGICAL_PATTERN); player:addItem(rseGear); player:messageSpecial(ITEM_OBTAINED,rseGear); end end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Temenos/mobs/Earth_Elemental.lua
28
1790
----------------------------------- -- Area: Temenos E T -- NPC: Earth_Elemental ----------------------------------- package.loaded["scripts/zones/Temenos/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Temenos/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) local mobID = mob:getID(); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); switch (mobID): caseof { -- 100 a 106 inclut (Temenos -Northern Tower ) [16928867] = function (x) GetNPCByID(16928768+182):setPos(mobX,mobY,mobZ); GetNPCByID(16928768+182):setStatus(STATUS_NORMAL); end , [16928868] = function (x) GetNPCByID(16928768+236):setPos(mobX,mobY,mobZ); GetNPCByID(16928768+236):setStatus(STATUS_NORMAL); end , [16928869] = function (x) GetNPCByID(16928768+360):setPos(mobX,mobY,mobZ); GetNPCByID(16928768+360):setStatus(STATUS_NORMAL); end , [16928870] = function (x) GetNPCByID(16928768+47):setPos(mobX,mobY,mobZ); GetNPCByID(16928768+47):setStatus(STATUS_NORMAL); end , [16929036] = function (x) if (IsMobDead(16929037)==false) then DespawnMob(16929037); SpawnMob(16929043); end end , } end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Windurst_Woods/npcs/HomePoint#2.lua
27
1266
----------------------------------- -- Area: Windurst Woods -- NPC: HomePoint#2 -- @pos 107 -5 -56 241 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Windurst_Woods/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fd, 26); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x21fd) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
rm-code/lofivi
src/graph/File.lua
1
4597
local File = {}; -- ------------------------------------------------ -- Constants -- ------------------------------------------------ local ANIM_TIMER = 3.5; -- ------------------------------------------------ -- Constructor -- ------------------------------------------------ --- -- Creates a new File object. -- @param parentX (number) The position of the file's parent node along the x-axis. -- @param parentY (number) The position of the file's parent node along the y-axis. -- @param color (table) A table containing the RGB values for this file type. -- @param extension (string) The file's extension. -- @return (File) A new file instance. -- function File.new( parentX, parentY, color, extension ) local self = {}; -- The target and the current offset from the parent node's position. -- This is used to arrange the files around a node. local targetOffsetX, targetOffsetY = 0, 0; local currentOffsetX, currentOffsetY = 0, 0; -- ------------------------------------------------ -- Private Functions -- ------------------------------------------------ --- -- Linear interpolation between a and b. -- @param a (number) The current value. -- @param b (number) The target value. -- @param t (number) The time value. -- @return (number) The interpolated value. -- local function lerp( a, b, t ) return a + ( b - a ) * t; end --- -- Lerps the file from its current offset position to the target offset. -- This adds a nice animation effect when files are rearranged around their -- parent nodes. -- @param dt (number) The delta time between frames. -- @param tarX (number) The target offset on the x-axis. -- @param tarY (number) The target offset on the y-axis. -- local function animate( dt, tarX, tarY ) currentOffsetX = lerp( currentOffsetX, tarX, dt * ANIM_TIMER ); currentOffsetY = lerp( currentOffsetY, tarY, dt * ANIM_TIMER ); end -- ------------------------------------------------ -- Public Functions -- ------------------------------------------------ --- -- If the file is marked as modified the color will be lerped from the -- modified color to the default file color. -- @param dt (number) The delta time between frames. -- function self:update( dt ) animate( dt, targetOffsetX, targetOffsetY ); end -- ------------------------------------------------ -- Getters -- ------------------------------------------------ --- -- Returns the real position of the node on the x-axis. -- This is the sum of the parent-node's position and the offset of the file. -- @return (number) The position of the file along the x-axis. -- function self:getX() return parentX + currentOffsetX; end --- -- Returns the real position of the node on the y-axis. -- This is the sum of the parent-node's position and the offset of the file. -- @return (number) The position of the file along the y-axis. -- function self:getY() return parentY + currentOffsetY; end --- -- Returns the current color of the file. The table uses rgba keys to store -- the color. -- @return (table) A table containing the RGB values of the file. -- function self:getColor() return color; end --- -- Returns the extension of the file as a string. -- @return (string) The extension of the file. -- function self:getExtension() return extension; end -- ------------------------------------------------ -- Setters -- ------------------------------------------------ --- -- Sets the target offset of the file from its parent node. -- This distance is used to plot all the files in a circle around the node. -- @param ox (number) The offset from the parent along the x-axis. -- @param oy (number) The offset from the parent along the y-axis. -- function self:setOffset( ox, oy ) targetOffsetX, targetOffsetY = ox, oy; end --- -- Sets the position of the parent node on which the file is located. -- @param nx (number) The position of the parent along the x-axis. -- @param ny (number) The position of the parent along the y-axis. -- function self:setPosition( nx, ny ) parentX, parentY = nx, ny; end return self; end -- ------------------------------------------------ -- Return Module -- ------------------------------------------------ return File;
mit
Zero-K-Experiments/Zero-K-Experiments
scripts/amphfloater.lua
9
8887
--linear constant 65536 include "constants.lua" local base, head, body, barrel, firepoint = piece('base', 'head', 'body', 'barrel', 'firepoint') local rthigh, rshin, rfoot, lthigh, lshin, lfoot = piece('rthigh', 'rshin', 'rfoot', 'lthigh', 'lshin', 'lfoot') local vent1, vent2, vent3 = piece('vent1', 'vent2', 'vent3') local smokePiece = {body} -------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------- local PACE = 2 local THIGH_FRONT_ANGLE = -math.rad(50) local THIGH_FRONT_SPEED = math.rad(60) * PACE local THIGH_BACK_ANGLE = math.rad(30) local THIGH_BACK_SPEED = math.rad(60) * PACE local SHIN_FRONT_ANGLE = math.rad(45) local SHIN_FRONT_SPEED = math.rad(90) * PACE local SHIN_BACK_ANGLE = math.rad(10) local SHIN_BACK_SPEED = math.rad(90) * PACE local ARM_FRONT_ANGLE = -math.rad(20) local ARM_FRONT_SPEED = math.rad(22.5) * PACE local ARM_BACK_ANGLE = math.rad(10) local ARM_BACK_SPEED = math.rad(22.5) * PACE local FOREARM_FRONT_ANGLE = -math.rad(40) local FOREARM_FRONT_SPEED = math.rad(45) * PACE local FOREARM_BACK_ANGLE = math.rad(10) local FOREARM_BACK_SPEED = math.rad(45) * PACE local SIG_WALK = 1 local SIG_AIM1 = 2 local SIG_AIM2 = 4 local SIG_RESTORE = 8 local SIG_BOB = 16 local SIG_FLOAT = 32 local SIG_UNPACK = 64 local wd = UnitDefs[unitDefID].weapons[1] and UnitDefs[unitDefID].weapons[1].weaponDef local PROJECTILE_SPEED = WeaponDefs[wd].projectilespeed local UNPACK_TIME = 1/3 -------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------- local bUnpacked = false local gun_1 = 1 -------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------- -- Swim functions local function Bob() Signal(SIG_BOB) SetSignalMask(SIG_BOB) while true do Turn(base, x_axis, math.rad(math.random(-3,3)), math.rad(math.random(1,2))) Turn(base, z_axis, math.rad(math.random(-3,3)), math.rad(math.random(1,2))) Move(base, y_axis, math.rad(math.random(0,6)), math.rad(math.random(2,6))) Sleep(2000) Turn(base, x_axis, math.rad(math.random(-3,3)), math.rad(math.random(1,2))) Turn(base, z_axis, math.rad(math.random(-3,3)), math.rad(math.random(1,2))) Move(base, y_axis, math.rad(math.random(-6,0)), math.rad(math.random(2,6))) Sleep(2000) end end local function SinkBubbles() SetSignalMask(SIG_FLOAT) while true do EmitSfx(vent1, SFX.BUBBLE) EmitSfx(vent2, SFX.BUBBLE) EmitSfx(vent3, SFX.BUBBLE) Sleep(66) end end local function dustBottom() local x,y,z = Spring.GetUnitPiecePosDir(unitID,rfoot) Spring.SpawnCEG("uw_vindiback", x, y+5, z, 0, 0, 0, 0) local x,y,z = Spring.GetUnitPiecePosDir(unitID,lfoot) Spring.SpawnCEG("uw_vindiback", x, y+5, z, 0, 0, 0, 0) end -------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------- -- Swim gadget callins function Float_startFromFloor() dustBottom() Signal(SIG_WALK) Signal(SIG_FLOAT) StartThread(Bob) end function Float_stopOnFloor() dustBottom() Signal(SIG_BOB) Signal(SIG_FLOAT) end function Float_rising() Signal(SIG_FLOAT) end function Float_sinking() Signal(SIG_FLOAT) StartThread(SinkBubbles) end function Float_crossWaterline(speed) --Signal(SIG_FLOAT) end function Float_stationaryOnSurface() Signal(SIG_FLOAT) bUnpacked = true end function unit_teleported(position) return GG.Floating_UnitTeleported(unitID, position) end -------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------- local function Walk() Signal(SIG_WALK) SetSignalMask(SIG_WALK) Turn(base, x_axis, 0, math.rad(20)) Turn(base, z_axis, 0, math.rad(20)) Move(base, y_axis, 0, 10) while true do --left leg up, right leg back Turn(lthigh, x_axis, THIGH_FRONT_ANGLE, THIGH_FRONT_SPEED) Turn(lshin, x_axis, SHIN_FRONT_ANGLE, SHIN_FRONT_SPEED) Turn(rthigh, x_axis, THIGH_BACK_ANGLE, THIGH_BACK_SPEED) Turn(rshin, x_axis, SHIN_BACK_ANGLE, SHIN_BACK_SPEED) WaitForTurn(lthigh, x_axis) Sleep(0) --right leg up, left leg back Turn(lthigh, x_axis, THIGH_BACK_ANGLE, THIGH_BACK_SPEED) Turn(lshin, x_axis, SHIN_BACK_ANGLE, SHIN_BACK_SPEED) Turn(rthigh, x_axis, THIGH_FRONT_ANGLE, THIGH_FRONT_SPEED) Turn(rshin, x_axis, SHIN_FRONT_ANGLE, SHIN_FRONT_SPEED) WaitForTurn(rthigh, x_axis) Sleep(0) end end function script.StartMoving() --Move(lthigh, y_axis, 0, 12) --Move(rthigh, y_axis, 0, 12) Signal(SIG_UNPACK) bUnpacked = false StartThread(Walk) end local function Unpack() Signal(SIG_UNPACK) SetSignalMask(SIG_UNPACK) Sleep(UNPACK_TIME) bUnpacked = true end local function Stopping() Signal(SIG_WALK) SetSignalMask(SIG_WALK) Turn(rthigh, x_axis, 0, math.rad(80)*PACE) Turn(rshin, x_axis, 0, math.rad(120)*PACE) Turn(rfoot, x_axis, 0, math.rad(80)*PACE) Turn(lthigh, x_axis, 0, math.rad(80)*PACE) Turn(lshin, x_axis, 0, math.rad(80)*PACE) Turn(lfoot, x_axis, 0, math.rad(80)*PACE) --Move(lthigh, y_axis, 4, 12) --Move(rthigh, y_axis, 4, 12) GG.Floating_StopMoving(unitID) StartThread(Unpack) end function script.StopMoving() StartThread(Stopping) end -------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------- local function WeaponRangeUpdate() while true do local height = select(2, Spring.GetUnitPosition(unitID)) if height < -20 then Spring.SetUnitWeaponState(unitID, 2, {range = 400-height}) else Spring.SetUnitWeaponState(unitID, 2, {range = 450}) end Sleep(500) end end function script.Create() StartThread(SmokeUnit, smokePiece) StartThread(WeaponRangeUpdate) end -------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------- local function RestoreAfterDelay() Signal(SIG_RESTORE) SetSignalMask(SIG_RESTORE) Sleep(5000) Turn(head, y_axis, 0, math.rad(65)) Turn(barrel, x_axis, 0, math.rad(65)) end function script.AimFromWeapon() --Spring.Echo(Spring.GetUnitWeaponState(unitID, 1, "projectileSpeed")) --Spring.Echo(PROJECTILE_SPEED) local height = select(2, Spring.GetUnitBasePosition(unitID)) if height < -130 then Spring.SetUnitWeaponState(unitID,2,{projectileSpeed = 200}) else Spring.SetUnitWeaponState(unitID,2,{projectileSpeed = PROJECTILE_SPEED}) end return barrel end function script.AimWeapon(num, heading, pitch) if num == 1 then Signal(SIG_AIM1) SetSignalMask(SIG_AIM1) Turn(head, y_axis, heading, math.rad(360)) Turn(barrel, x_axis, -pitch, math.rad(180)) WaitForTurn(head, y_axis) WaitForTurn(barrel, x_axis) StartThread(RestoreAfterDelay) return true elseif num == 2 then GG.Floating_AimWeapon(unitID) return false end end function script.QueryWeapon(num) return barrel end function script.BlockShot(num, targetID) if Spring.ValidUnitID(targetID) then local distMult = (Spring.GetUnitSeparation(unitID, targetID) or 0)/450 return GG.OverkillPrevention_CheckBlock(unitID, targetID, 150.1, 35 * distMult, false, false, true) end return false end function script.Killed(recentDamage, maxHealth) local severity = recentDamage/maxHealth if severity <= .25 then Explode(lfoot, sfxNone) Explode(lshin, sfxNone) Explode(lthigh, sfxNone) Explode(rfoot, sfxNone) Explode(rshin, sfxNone) Explode(rthigh, sfxNone) Explode(body, sfxNone) return 1 elseif severity <= .50 then Explode(lfoot, sfxFall) Explode(lshin, sfxFall) Explode(lthigh, sfxFall) Explode(rfoot, sfxFall) Explode(rshin, sfxFall) Explode(rthigh, sfxFall) Explode(body, sfxShatter) return 1 elseif severity <= .99 then Explode(lfoot, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(lshin, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(lthigh, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(rfoot, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(rshin, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(rthigh, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(body, sfxShatter) return 2 else Explode(lfoot, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(lshin, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(lthigh, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(rfoot, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(rshin, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(rthigh, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(body, sfxShatter + sfxExplode) return 2 end end
gpl-2.0
Scavenge/darkstar
scripts/zones/Port_Bastok/npcs/Hilda.lua
26
5026
----------------------------------- -- Area: Port Bastok -- NPC: Hilda -- Involved in Quest: Cid's Secret, Riding on the Clouds -- Starts & Finishes: The Usual -- @pos -163 -8 13 236 ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:getGil() == 0 and trade:getItemCount() == 1) then if (trade:hasItemQty(4530,1) and player:getVar("CidsSecret_Event") == 1 and player:hasKeyItem(UNFINISHED_LETTER) == false) then -- Trade Rollanberry player:startEvent(0x0085); elseif (trade:hasItemQty(4386,1) and player:getQuestStatus(BASTOK,THE_USUAL) == QUEST_ACCEPTED) then -- Trade King Truffle player:startEvent(0x0087); end end if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_2") == 5) then if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal player:setVar("ridingOnTheClouds_2",0); player:tradeComplete(); player:addKeyItem(SMILING_STONE); player:messageSpecial(KEYITEM_OBTAINED,SMILING_STONE); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatBastok = player:getVar("WildcatBastok"); if (player:getCurrentMission(BASTOK) == ON_MY_WAY) and (player:getVar("MissionStatus") == 1) then player:startEvent(0x00ff); elseif (player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok,3) == false) then player:startEvent(0x0164); elseif (player:getQuestStatus(BASTOK,THE_USUAL) ~= QUEST_COMPLETED) then if (player:getQuestStatus(BASTOK,CID_S_SECRET) == QUEST_ACCEPTED) then player:startEvent(0x0084); if (player:getVar("CidsSecret_Event") ~= 1) then player:setVar("CidsSecret_Event",1); end elseif (player:getFameLevel(BASTOK) >= 5 and player:getQuestStatus(BASTOK,CID_S_SECRET) == QUEST_COMPLETED) then if (player:getVar("TheUsual_Event") == 1) then player:startEvent(0x0088); elseif (player:getQuestStatus(BASTOK,THE_USUAL) == QUEST_ACCEPTED) then player:startEvent(0x0031); --Hilda thanks the player for all the help; there is no reminder dialogue for this quest else player:startEvent(0x0086); end else player:startEvent(0x0030); --Standard dialogue if fame isn't high enough to start The Usual and Cid's Secret is not active end elseif (player:getQuestStatus(BASTOK,THE_USUAL) == QUEST_COMPLETED and player:getQuestStatus(BASTOK,CID_S_SECRET) == QUEST_COMPLETED) then player:startEvent(0x0031); --Hilda thanks the player for all the help else player:startEvent(0x0030); --Standard dialogue if no quests are active or available end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0085) then player:tradeComplete(); player:addKeyItem(UNFINISHED_LETTER); player:messageSpecial(KEYITEM_OBTAINED,UNFINISHED_LETTER); elseif (csid == 0x0086 and option == 0) then if (player:getQuestStatus(BASTOK,THE_USUAL) == QUEST_AVAILABLE) then player:addQuest(BASTOK,THE_USUAL); end elseif (csid == 0x0087) then player:tradeComplete(); player:addKeyItem(STEAMING_SHEEP_INVITATION); player:messageSpecial(KEYITEM_OBTAINED,STEAMING_SHEEP_INVITATION); elseif (csid == 0x0088) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17170); else player:addTitle(STEAMING_SHEEP_REGULAR); player:delKeyItem(STEAMING_SHEEP_INVITATION); player:setVar("TheUsual_Event",0); player:addItem(17170); player:messageSpecial(ITEM_OBTAINED,17170); -- Speed Bow player:addFame(BASTOK,30); player:completeQuest(BASTOK,THE_USUAL); end elseif (csid == 0x00ff) then player:setVar("MissionStatus",2); elseif (csid == 0x0164) then player:setMaskBit(player:getVar("WildcatBastok"),"WildcatBastok",3,true); end end;
gpl-3.0
Scavenge/darkstar
scripts/globals/items/beef_stewpot.lua
12
1752
----------------------------------------- -- ID: 5547 -- Item: Beef Stewpot -- Food Effect: 3 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP +10% Cap 50 -- MP +10 -- HP Recoverd while healing 5 -- MP Recovered while healing 1 -- Attack +18% Cap 40 -- Evasion +5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5547); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 10); target:addMod(MOD_FOOD_HP_CAP, 50); target:addMod(MOD_MP, 10); target:addMod(MOD_HPHEAL, 5); target:addMod(MOD_MPHEAL, 1); target:addMod(MOD_FOOD_ATTP, 18); target:addMod(MOD_FOOD_ATT_CAP, 40); target:addMod(MOD_EVA, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 10); target:delMod(MOD_FOOD_HP_CAP, 50); target:delMod(MOD_MP, 10); target:delMod(MOD_HPHEAL, 5); target:delMod(MOD_MPHEAL, 1); target:delMod(MOD_FOOD_ATTP, 18); target:delMod(MOD_FOOD_ATT_CAP, 40); target:delMod(MOD_EVA, 5); end;
gpl-3.0
TingPing/plugins
HexChat/zncbuffer.lua
1
1348
-- SPDX-License-Identifier: MIT hexchat.register('ZNC Buffers', '1', 'Add menu options to manage ZNC buffers') -- Add menus hexchat.command('menu -p4 add "$TAB/ZNC"') hexchat.command('menu add "$TAB/ZNC/Clear Buffer" ".zncclearbuffer %s"') hexchat.command('menu add "$TAB/ZNC/Play Buffer" "znc playbuffer %s"') hexchat.hook_unload(function () hexchat.command('menu del "$TAB/ZNC') end) -- Ignore our own actions local recently_cleared = {} hexchat.hook_command('.zncclearbuffer', function(word, word_eol) local name = word[2] -- Ignore znc queries if name:sub(1, 1) ~= '*' then recently_cleared[name] = true hexchat.command('znc clearbuffer ' .. name) end return hexchat.EAT_ALL end) hexchat.hook_server('PRIVMSG', function(word, word_eol) local cleared_channel = word_eol[1]:match('^:%*status!znc@znc.in [^:]+:%[%d+] buffers matching %[([^%]]+)] have been cleared$') if cleared_channel and recently_cleared[cleared_channel] then recently_cleared[cleared_channel] = nil return hexchat.EAT_ALL end end) hexchat.hook_command('zncclosepm', function (word, word_eol) local id = hexchat.props.id for chan in hexchat.iterate('channels') do if chan.id == id and chan.type == 3 then hexchat.command('.zncclearbuffer ' .. chan.channel) chan.context:command('close') end end return hexchat.EAT_ALL end)
mit
Scavenge/darkstar
scripts/zones/Cloister_of_Tides/npcs/Water_Protocrystal.lua
14
1950
----------------------------------- -- Area: Cloister of Tides -- NPC: Water Protocrystal -- Involved in Quests: Trial by Water, Trial Size Trial by Water -- @pos 560 36 560 211 ----------------------------------- package.loaded["scripts/zones/Cloister_of_Tides/TextIDs"] = nil; ------------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/bcnm"); require("scripts/zones/Cloister_of_Tides/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE and player:getVar("ASA4_Cerulean") == 1) then player:startEvent(0x0002); elseif (EventTriggerBCNM(player,npc)) then return; else player:messageSpecial(PROTOCRYSTAL); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdate CSID: %u",csid); -- printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if (csid==0x0002) then player:delKeyItem(DOMINAS_CERULEAN_SEAL); player:addKeyItem(CERULEAN_COUNTERSEAL); player:messageSpecial(KEYITEM_OBTAINED,CERULEAN_COUNTERSEAL); player:setVar("ASA4_Cerulean","2"); elseif (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0