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
BlackMesaRP/NS-Black-Mesa
plugins/m9k/entities/weapons/m9k_winchester73/shared.lua
2
3523
-- Variables that are used on both client and server SWEP.Gun = ("m9k_winchester73") -- must be the name of your swep but NO CAPITALS! SWEP.Category = "M9K Assault Rifles" SWEP.Author = "" SWEP.Contact = "" SWEP.Purpose = "" SWEP.Instructions = "" SWEP.MuzzleAttachment = "1" -- Should be "1" for CSS models or "muzzle" for hl2 models SWEP.ShellEjectAttachment = "2" -- Should be "2" for CSS models or "1" for hl2 models SWEP.PrintName = "73 Winchester Carbine" -- Weapon name (Shown on HUD) SWEP.Slot = 2 -- Slot in the weapon selection menu SWEP.SlotPos = 3 -- Position in the slot SWEP.DrawAmmo = true -- Should draw the default HL2 ammo counter SWEP.DrawWeaponInfoBox = false -- Should draw the weapon info box SWEP.BounceWeaponIcon = false -- Should the weapon icon bounce? SWEP.DrawCrosshair = true -- set false if you want no crosshair SWEP.Weight = 3 -- rank relative ot other weapons. bigger is better SWEP.AutoSwitchTo = true -- Auto switch to if we pick it up SWEP.AutoSwitchFrom = true -- Auto switch from if you pick up a better weapon SWEP.HoldType = "ar2" -- how others view you carrying the weapon -- normal melee melee2 fist knife smg ar2 pistol rpg physgun grenade shotgun crossbow slam passive -- you're mostly going to use ar2, smg, shotgun or pistol. rpg and crossbow make for good sniper rifles SWEP.ViewModelFOV = 70 SWEP.ViewModelFlip = true SWEP.ViewModel = "models/weapons/v_winchester1873.mdl" -- Weapon view model SWEP.WorldModel = "models/weapons/w_winchester_1873.mdl" -- Weapon world model SWEP.Base = "bobs_shotty_base" SWEP.Spawnable = true SWEP.AdminSpawnable = true SWEP.Primary.Sound = Sound("Weapon_73.Single") -- script that calls the primary fire sound SWEP.Primary.RPM = 66 -- This is in Rounds Per Minute SWEP.Primary.ClipSize = 8 -- Size of a clip SWEP.Primary.DefaultClip = 30 -- Default number of bullets in a clip SWEP.Primary.KickUp = .2 -- Maximum up recoil (rise) SWEP.Primary.KickDown = 0 -- Maximum down recoil (skeet) SWEP.Primary.KickHorizontal = 0.1 -- Maximum up recoil (stock) SWEP.Primary.Automatic = false -- Automatic/Semi Auto SWEP.Primary.Ammo = "AirboatGun" -- pistol, 357, smg1, ar2, buckshot, slam, SniperPenetratedRound, AirboatGun -- Pistol, buckshot, and slam always ricochet. Use AirboatGun for a light metal peircing shotgun pellets SWEP.Secondary.IronFOV = 60 -- How much you 'zoom' in. Less is more! SWEP.ShellTime = .54 SWEP.data = {} --The starting firemode SWEP.data.ironsights = 1 SWEP.Primary.NumShots = 1 -- How many bullets to shoot per trigger pull, AKA pellets SWEP.Primary.Damage = 85 -- Base damage per bullet SWEP.Primary.Spread = .01 -- Define from-the-hip accuracy 1 is terrible, .0001 is exact) SWEP.Primary.IronAccuracy = .001 -- Ironsight accuracy, should be the same for shotguns -- Because irons don't magically give you less pellet spread!, but this isn't a shotgun so whatever, man! -- Enter iron sight info and bone mod info below SWEP.IronSightsPos = Vector(4.356, 0, 2.591) SWEP.IronSightsAng = Vector(0, 0, 0) SWEP.SightsPos = Vector(4.356, 0, 2.591) SWEP.SightsAng = Vector(0, 0, 0) SWEP.GSightsPos = Vector (0, 0, 0) SWEP.GSightsAng = Vector (0, 0, 0) SWEP.RunSightsPos = Vector (-2.3095, -3.0514, 2.3965) SWEP.RunSightsAng = Vector (-19.8471, -33.9181, 10) SWEP.ViewModelBoneMods = { ["shell"] = { scale = Vector(0.009, 0.009, 0.009), pos = Vector(0, 0, 0), angle = Angle(0, 0, 0) } }
gpl-3.0
czfshine/UpAndAway
code/prefabs/cumulostone.lua
2
1058
BindGlobal() local CFG = TheMod:GetConfig() local assets = { Asset("ANIM", "anim/cumulostone.zip"), Asset( "ATLAS", inventoryimage_atlas("cumulostone") ), Asset( "IMAGE", inventoryimage_texture("cumulostone") ), } local function fn(Sim) local inst = CreateEntity() inst.entity:AddTransform() inst.entity:AddAnimState() inst.entity:AddSoundEmitter() MakeInventoryPhysics(inst) inst.AnimState:SetBank("nitre") inst.AnimState:SetBuild("cumulostone") inst.AnimState:PlayAnimation("idle") ------------------------------------------------------------------------ SetupNetwork(inst) ------------------------------------------------------------------------ inst:AddComponent("inspectable") inst:AddComponent("inventoryitem") inst.components.inventoryitem.atlasname = inventoryimage_atlas("cumulostone") inst:AddComponent("stackable") inst.components.stackable.maxsize = CFG.CUMULOSTONE.STACK_SIZE return inst end return Prefab ("common/inventory/cumulostone", fn, assets)
gpl-2.0
eiffelqiu/candle
lib/candle/generators/lua/wax/lib/stdlib/luaspec/luaspec.lua
19
9172
spec = { contexts = {}, passed = 0, failed = 0, pending = 0, current = nil } Report = {} Report.__index = Report function Report:new(spec) local report = { num_passed = spec.passed, num_failed = spec.failed, num_pending = spec.pending, total = spec.passed + spec.failed + spec.pending, results = {} } report.percent = report.num_passed/report.total*100 local contexts = spec.contexts for index = 1, #contexts do report.results[index] = { name = contexts[index], spec_results = contexts[contexts[index]] } end return report end function spec:report(verbose) local report = Report:new(self) if report.num_failed ~= 0 or verbose then for i, result in pairs(report.results) do print(("\n%s\n================================"):format(result.name)) for description, r in pairs(result.spec_results) do local outcome = r.passed and 'pass' or "FAILED" if verbose or not (verbose and r.passed) then print(("%-70s [ %s ]"):format(" - " .. description, outcome)) table.foreach(r.errors, function(index, error) print(" " .. index ..". Failed expectation : " .. error.message .. "\n "..error.trace) end) end end end end local summary = [[ ========== %s ============= %s Failed %s Passed -------------------------------- %s Run, %.2f%% Success rate ]] print(summary:format(report.num_failed == 0 and "Success" or "Failure", report.num_failed, report.num_passed, report.total, report.percent)) end function spec:add_results(success, message, trace) if self.current.passed then self.current.passed = success end if success then self.passed = self.passed + 1 else table.insert(self.current.errors, { message = message, trace = trace }) self.failed = self.failed + 1 end end function spec:add_context(name) self.contexts[#self.contexts+1] = name self.contexts[name] = {} end function spec:add_spec(context_name, spec_name) local context = self.contexts[context_name] context[spec_name] = { passed = true, errors = {} } self.current = context[spec_name] end function spec:add_pending_spec(context_name, spec_name, pending_description) end -- create tables to support pending specifications local pending = {} function pending.__newindex() error("You can't set properties on pending") end function pending.__index(_, key) if key == "description" then return nil else error("You can't get properties on pending") end end function pending.__call(_, description) local o = { description = description} setmetatable(o, pending) return o end setmetatable(pending, pending) -- -- define matchers matchers = { should_be = function(value, expected) if value ~= expected then return false, "expecting "..tostring(expected)..", not ".. tostring(value) end return true end; should_not_be = function(value, expected) if value == expected then return false, "should not be "..tostring(value) end return true end; should_be_greater_than = function(value, expected) if expected >= value then return false, "got " .. tostring(value) .. " expecting value > " .. tostring(expected) end return true end; should_be_less_than = function(value, expected) if expected <= value then return false, "got " .. tostring(value) .. " expecting value < " .. tostring(expected) end return true end; should_error = function(f) if pcall(f) then return false, "expecting an error but received none" end return true end; should_match = function(value, pattern) if type(value) ~= 'string' then return false, "type error, should_match expecting target as string" end if not string.match(value, pattern) then return false, value .. "doesn't match pattern ".. pattern end return true end; should_be_kind_of = function(value, class) if type(value) == "userdata" then if not value:isKindOfClass(class) then return false, tostring(value) .. " is not a " .. tostring(class) end elseif type(value) ~= class then return false, type(value) .. " is not a " .. tostring(class) end return true end; should_exist = function(value) if not value then return false, tostring(value) .. " evaluates to false." else return true end end; should_not_exist = function(value) if value then return false, value .. " evaluates to true." else return true end end; } matchers.should_equal = matchers.should_be -- -- expect returns an empty table with a 'method missing' metatable -- which looks up the matcher. The 'method missing' function -- runs the matcher and records the result in the current spec local function expect(target) return setmetatable({}, { __index = function(_, matcher) return function(...) local success, message = matchers[matcher](target, ...) spec:add_results(success, message, debug.traceback()) end end }) end -- Context = {} Context.__index = Context function Context:new(context) for i, child in ipairs(context.children) do child.parent = context end return setmetatable(context, self) end function Context:run_befores(env) if self.parent then self.parent:run_befores(env) end if self.before then setfenv(self.before, env) self.before() end end function Context:run_afters(env) if self.after then setfenv(self.after, env) self.after() end if self.parent then self.parent:run_afters(env) end end function Context:run() -- run all specs for spec_name, spec_func in pairs(self.specs) do if getmetatable(spec_func) == pending then else spec:add_spec(self.name, spec_name) local mocks = {} -- setup the environment that the spec is run in, each spec is run in a new environment local env = { track_error = function(f) local status, err = pcall(f) return err end, expect = expect, mock = function(table, key, mock_value) mocks[{ table = table, key = key }] = table[key] -- store the old value table[key] = mock_value or Mock:new() return table[key] end } setmetatable(env, { __index = _G }) -- run each spec with proper befores and afters self:run_befores(env) setfenv(spec_func, env) local message local traceback local success = xpcall(spec_func, function(err) message = err traceback = debug.traceback("", 2) end) self:run_afters(env) if not success then io.write("x") spec:add_results(false, message, traceback) else io.write(".") end io.flush() -- restore stored values for mocks for key, old_value in pairs(mocks) do key.table[key.key] = old_value end end end for i, child in pairs(self.children) do child:run() end end -- dsl for creating contexts local function make_it_table() -- create and set metatables for 'it' local specs = {} local it = {} setmetatable(it, { -- this is called when it is assigned a function (e.g. it["spec name"] = function() ...) __newindex = function(_, spec_name, spec_function) specs[spec_name] = spec_function end }) return it, specs end local make_describe_table -- create an environment to run a context function in as well as the tables to collect -- the subcontexts and specs local function create_context_env() local it, specs = make_it_table() local describe, sub_contexts = make_describe_table() -- create an environment to run the function in local context_env = { it = it, describe = describe, pending = pending } return context_env, sub_contexts, specs end -- Note: this is declared locally earlier so it is still local function make_describe_table(auto_run) local describe = {} local contexts = {} local describe_mt = { -- This function is called when a function is assigned to a describe table -- (e.g. describe["context name"] = function() ...) __newindex = function(_, context_name, context_function) spec:add_context(context_name) local context_env, sub_contexts, specs = create_context_env() -- set the environment setfenv(context_function, context_env) -- run the context function which collects the data into context_env and sub_contexts context_function() -- store the describe function in contexts contexts[#contexts+1] = Context:new { name = context_name, before = context_env.before, after = context_env.after, specs = specs, children = sub_contexts } if auto_run then contexts[#contexts]:run() end end } setmetatable(describe, describe_mt) return describe, contexts end describe = make_describe_table(true)
mit
xdemolish/darkstar
scripts/zones/Kazham/npcs/Thali_Mhobrum.lua
19
1540
----------------------------------- -- Area: Kazham -- NPC: Thali Mhobrum -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); local path = { 55.816410, -11.000000, -43.992680, 54.761787, -11.000000, -44.046181, 51.805824, -11.000000, -44.200321, 52.922001, -11.000000, -44.186420, 51.890709, -11.000000, -44.224312, 47.689358, -11.000000, -44.374969, 52.826096, -11.000000, -44.191029, 47.709465, -11.000000, -44.374393, 52.782181, -11.000000, -44.192482, 47.469643, -11.000000, -44.383091 }; function onSpawn(npc) npc:initNpcAi(); npc:setPos(pathfind.first(path)); onPath(npc); end; function onPath(npc) pathfind.patrol(npc, path); end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00BE); npc:wait(-1); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,npc) --printf("CSID: %u",csid); --printf("RESULT: %u",option); npc:wait(0); end;
gpl-3.0
xdemolish/darkstar
scripts/zones/Norg/TextIDs.lua
4
2240
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6393; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6396; -- Obtained: <item>. GIL_OBTAINED = 6397; -- Obtained <number> gil. KEYITEM_OBTAINED = 6399; -- Obtained key item: <keyitem>. FISHING_MESSAGE_OFFSET = 6631; -- You can't fish here. HOMEPOINT_SET = 2; -- Home point set! DOOR_IS_LOCKED = 10323; -- The door is locked tight. -- Other Texts SPASIJA_DELIVERY_DIALOG = 10317; -- Hiya! I can deliver packages to anybody, anywhere, anytime. What do you say? PALEILLE_DELIVERY_DIALOG = 10318; -- We can deliver parcels to any residence in Vana'diel. -- Quest Dialog YOU_CAN_NOW_BECOME_A_SAMURAI = 10166; -- You can now become a samurai. CARRYING_TOO_MUCH_ALREADY = 10167; -- I wish to give you your reward, but you seem to be carrying too much already. Come back when you have more room in your pack. SPASIJA_DIALOG = 10317; -- Hiya! I can deliver packages to anybody, anywhere, anytime. What do you say? PALEILLE_DIALOG = 10318; -- We can deliver parcels to any residence in Vana'diel. AVATAR_UNLOCKED = 10437; -- You are now able to summon NOMAD_MOOGLE_DIALOG = 10505; -- I'm a traveling moogle, kupo. I help adventurers in the Outlands access items they have stored in a Mog House elsewhere, kupo. FOUIVA_DIALOG = 10529; -- Oi 'av naw business wi' de likes av you. -- Shop Texts JIROKICHI_SHOP_DIALOG = 10313; -- Heh-heh-heh. Feast your eyes on these beauties. You won't find stuff like this anywhere! VULIAIE_SHOP_DIALOG = 10314; -- Please, stay and have a look. You may find something you can only buy here. ACHIKA_SHOP_DIALOG = 10315; -- Can I interest you in some armor forged in the surrounding regions? CHIYO_SHOP_DIALOG = 10316; -- Magic scrolls! Magic scrolls! We've got parchment hot off the sheep! SOLBYMAHOLBY_SHOP_DIALOG = 10543; -- Hiya! My name's Solby-Maholby! I'm new here, so they put me on tooty-fruity shop duty. I'll give you a super-duper deal on unwanted items! -- conquest Base CONQUEST_BASE = 6472; -- Tallying conquest results...
gpl-3.0
chris5560/openwrt-luci
protocols/luci-proto-ppp/luasrc/model/network/proto_ppp.lua
4
2167
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local netmod = luci.model.network local _, p for _, p in ipairs({"ppp", "pptp", "pppoe", "pppoa", "l2tp", "pppossh"}) do local proto = netmod:register_protocol(p) function proto.get_i18n(self) if p == "ppp" then return luci.i18n.translate("PPP") elseif p == "pptp" then return luci.i18n.translate("PPtP") elseif p == "pppoe" then return luci.i18n.translate("PPPoE") elseif p == "pppoa" then return luci.i18n.translate("PPPoATM") elseif p == "l2tp" then return luci.i18n.translate("L2TP") elseif p == "pppossh" then return luci.i18n.translate("PPPoSSH") end end function proto.ifname(self) return p .. "-" .. self.sid end function proto.opkg_package(self) if p == "ppp" then return p elseif p == "pptp" then return "ppp-mod-pptp" elseif p == "pppoe" then return "ppp-mod-pppoe" elseif p == "pppoa" then return "ppp-mod-pppoa" elseif p == "l2tp" then return "xl2tpd" elseif p == "pppossh" then return "pppossh" end end function proto.is_installed(self) if p == "pppoa" then return (nixio.fs.glob("/usr/lib/pppd/*/pppoatm.so")() ~= nil) elseif p == "pppoe" then return (nixio.fs.glob("/usr/lib/pppd/*/rp-pppoe.so")() ~= nil) elseif p == "pptp" then return (nixio.fs.glob("/usr/lib/pppd/*/pptp.so")() ~= nil) elseif p == "l2tp" then return nixio.fs.access("/lib/netifd/proto/l2tp.sh") elseif p == "pppossh" then return nixio.fs.access("/lib/netifd/proto/pppossh.sh") else return nixio.fs.access("/lib/netifd/proto/ppp.sh") end end function proto.is_floating(self) return (p ~= "pppoe") end function proto.is_virtual(self) return true end function proto.get_interfaces(self) if self:is_floating() then return nil else return netmod.protocol.get_interfaces(self) end end function proto.contains_interface(self, ifc) if self:is_floating() then return (netmod:ifnameof(ifc) == self:ifname()) else return netmod.protocol.contains_interface(self, ifc) end end netmod:register_pattern_virtual("^%s%%-%%w" % p) end
apache-2.0
ln-zookeeper/wesnoth
data/ai/micro_ais/cas/ca_messenger_escort_move.lua
2
3437
local H = wesnoth.require "helper" local AH = wesnoth.require "ai/lua/ai_helper.lua" local LS = wesnoth.require "location_set" local MAIUV = wesnoth.require "ai/micro_ais/micro_ai_unit_variables.lua" local M = wesnoth.map local messenger_next_waypoint = wesnoth.require "ai/micro_ais/cas/ca_messenger_f_next_waypoint.lua" local function get_escorts(cfg) local escorts = AH.get_units_with_moves { side = wesnoth.current.side, { "and", H.get_child(cfg, "filter_second") } } return escorts end local ca_messenger_escort_move = {} function ca_messenger_escort_move:evaluation(cfg) -- Move escort units close to messengers, and in between messengers and enemies -- The messengers have moved at this time, so we don't need to exclude them, -- but we check that there are messengers left if (not get_escorts(cfg)[1]) then return 0 end local _, _, _, messengers = messenger_next_waypoint(cfg) if (not messengers) or (not messengers[1]) then return 0 end return cfg.ca_score end function ca_messenger_escort_move:execution(cfg) local escorts = get_escorts(cfg) local _, _, _, messengers = messenger_next_waypoint(cfg) local enemies = AH.get_attackable_enemies() local base_rating_map = LS.create() local max_rating, best_unit, best_hex = -9e99 for _,unit in ipairs(escorts) do -- Only considering hexes unoccupied by other units is good enough for this local reach_map = AH.get_reachable_unocc(unit) -- Minor rating for the fastest and strongest unit to go first local unit_rating = unit.max_moves / 100. + unit.hitpoints / 1000. reach_map:iter( function(x, y, v) local base_rating = base_rating_map:get(x, y) if (not base_rating) then base_rating = 0 -- Distance from messenger is most important; only closest messenger counts for this -- Give somewhat of a bonus for the messenger that has moved the farthest through the waypoints local max_messenger_rating = -9e99 for _,m in ipairs(messengers) do local messenger_rating = 1. / (M.distance_between(x, y, m.x, m.y) + 2.) local wp_rating = MAIUV.get_mai_unit_variables(m, cfg.ai_id, "wp_rating") messenger_rating = messenger_rating * 10. * (1. + wp_rating * 2.) if (messenger_rating > max_messenger_rating) then max_messenger_rating = messenger_rating end end base_rating = base_rating + max_messenger_rating -- Distance from (sum of) enemies is important too -- This favors placing escort units between the messenger and close enemies for _,e in ipairs(enemies) do base_rating = base_rating + 1. / (M.distance_between(x, y, e.x, e.y) + 2.) end base_rating_map:insert(x, y, base_rating) end local rating = base_rating + unit_rating if (rating > max_rating) then max_rating = rating best_unit, best_hex = unit, { x, y } end end) end -- This will always find at least the hex the unit is on -> no check necessary AH.movefull_stopunit(ai, best_unit, best_hex) end return ca_messenger_escort_move
gpl-2.0
hacker44-h44/mmmmmm
plugins/gpmanager2.lua
39
11325
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "This service is private for SUDO (@shayansoft)" end local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group '..string.gsub(group_name, '_', ' ')..' created, check messages list...' end local function set_description(msg, data) if not is_momod(msg) then return "You are NOT moderator" end local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = deskripsi save_data(_config.moderation.data, data) return 'Set this message for about=>\n\n'..deskripsi end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'Group have not about' end local about = data[tostring(msg.to.id)][data_cat] return about end local function set_rules(msg, data) if not is_momod(msg) then return "You are NOT moderator" end local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set this message for rules=>\n\n'..rules end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'Group have not rules' end local rules = data[tostring(msg.to.id)][data_cat] return rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data) if not is_momod(msg) then return "You are NOT moderator" end local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Name is already locked' else data[tostring(msg.to.id)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['set_name'] = string.gsub(msg.to.print_name, '_', ' ') save_data(_config.moderation.data, data) return 'Group name locked' end end local function unlock_group_name(msg, data) if not is_momod(msg) then return "You are NOT moderator" end local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Name is already unlocked' else data[tostring(msg.to.id)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data) if not is_momod(msg) then return "You are NOT moderator" end local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Members are already locked' else data[tostring(msg.to.id)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members locked' end local function unlock_group_member(msg, data) if not is_momod(msg) then return "You are NOT moderator" end local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Members are already unlocked' else data[tostring(msg.to.id)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data) if not is_momod(msg) then return "You are NOT moderator" end local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Photo is already locked' else data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Send group photo now' end local function unlock_group_photo(msg, data) if not is_momod(msg) then return "You are NOT moderator" end local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Photo is already unlocked' else data[tostring(msg.to.id)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo unlocked' end end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Group photo save and set', ok_cb, false) else print('Error: '..msg.id) send_large_msg(receiver, 'Failed, try again', ok_cb, false) end end -- show group settings local function show_group_settings(msg, data) if not is_momod(msg) then return "You are NOT moderator" end local settings = data[tostring(msg.to.id)]['settings'] local text = "Group Settings:\n_________________________\n> Lock Group Name : "..settings.lock_name.."\n> Lock Group Photo : "..settings.lock_photo.."\n> Lock Group Member : "..settings.lock_member.."\n> Anti Spam System : on\n> Anti Spam Mod : kick\n> Anti Spam Action : 10\n> Group Status : active\n> Group Model : free\n> Group Mod : 2\n> Supportion : yes\n> Bot Version : 1.6" return text end function run(msg, matches) --vardump(msg) if matches[1] == 'makegroup' and matches[2] then group_name = matches[2] return create_group(msg) end if not is_chat_msg(msg) then return "This is not group" end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if msg.media and is_chat_msg(msg) and is_momod(msg) then if msg.media.type == 'photo' and data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' then load_photo(msg.id, set_group_photo, msg) end end end if data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'setabout' and matches[2] then deskripsi = matches[2] return set_description(msg, data) end if matches[1] == 'about' then return get_description(msg, data) end if matches[1] == 'setrules' then rules = matches[2] return set_rules(msg, data) end if matches[1] == 'rules' then return get_rules(msg, data) end if matches[1] == 'group' and matches[2] == '+' then --group lock * if matches[3] == 'name' then return lock_group_name(msg, data) end if matches[3] == 'member' then return lock_group_member(msg, data) end if matches[3] == 'photo' then return lock_group_photo(msg, data) end end if matches[1] == 'group' and matches[2] == '-' then --group unlock * if matches[3] == 'name' then return unlock_group_name(msg, data) end if matches[3] == 'member' then return unlock_group_member(msg, data) end if matches[3] == 'photo' then return unlock_group_photo(msg, data) end end if matches[1] == 'group' and matches[2] == '?' then return show_group_settings(msg, data) end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Send new photo now' end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then chat_set_photo (receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then chat_set_photo (receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end end end return { description = "Group Manager System", usage = { "/makegroup (name) : create new group", "/about : view group about", "/rules : view group rules", "/setname (name) : set group name", "/setphoto : set group photo", "/setabout (message) : set group about", "/setrules (message) : set group rules", "/group + name : lock group name", "/group + photo : lock group photo", "/group + member : lock group member", "/group - name : unlock group name", "/group - photo : unlock group photo", "/group - member : unlock group member", "/group ? : view group settings" }, patterns = { "^[!/](makegroup) (.*)$", "^[!/](setabout) (.*)$", "^[!/](about)$", "^[!/](setrules) (.*)$", "^[!/](rules)$", "^[!/](setname) (.*)$", "^[!/](setphoto)$", "^[!/](group) (+) (.*)$", "^[!/](group) (-) (.*)$", "^[!/](group) (?)$", "^!!tgservice (.+)$", "%[(photo)%]", }, run = run, } end
gpl-2.0
xdemolish/darkstar
scripts/zones/Bastok_Markets/npcs/Yafafa.lua
36
1619
----------------------------------- -- Area: Bastok Markets -- NPC: Yafafa -- Only sells when Bastok controls Kolshushu -- -- Updated Aug-09-2013 by Zerahn, based on bgwiki and gamerescape ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RegionOwner = GetRegionOwner(KOLSHUSHU); if (RegionOwner ~= BASTOK) then player:showText(npc,YAFAFA_CLOSED_DIALOG); else player:showText(npc,YAFAFA_OPEN_DIALOG); stock = { 0x1197, 184, --Buburimu Grape 0x0460,1620, --Casablanca 0x1107, 220, --Dhalmel Meat 0x0266, 72, --Mhaura Garlic 0x115d, 40 --Yagudo Cherry } showShop(player,BASTOK,stock); 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
hsiaoyi/Melo
cocos2d/cocos/scripting/lua-bindings/auto/api/ParticleMeteor.lua
11
1380
-------------------------------- -- @module ParticleMeteor -- @extend ParticleSystemQuad -- @parent_module cc -------------------------------- -- -- @function [parent=#ParticleMeteor] init -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#ParticleMeteor] initWithTotalParticles -- @param self -- @param #int numberOfParticles -- @return bool#bool ret (return value: bool) -------------------------------- -- Create a meteor particle system.<br> -- return An autoreleased ParticleMeteor object. -- @function [parent=#ParticleMeteor] create -- @param self -- @return ParticleMeteor#ParticleMeteor ret (return value: cc.ParticleMeteor) -------------------------------- -- Create a meteor particle system withe a fixed number of particles.<br> -- param numberOfParticles A given number of particles.<br> -- return An autoreleased ParticleMeteor object.<br> -- js NA -- @function [parent=#ParticleMeteor] createWithTotalParticles -- @param self -- @param #int numberOfParticles -- @return ParticleMeteor#ParticleMeteor ret (return value: cc.ParticleMeteor) -------------------------------- -- js ctor -- @function [parent=#ParticleMeteor] ParticleMeteor -- @param self -- @return ParticleMeteor#ParticleMeteor self (return value: cc.ParticleMeteor) return nil
apache-2.0
deepmind/lab2d
dmlab2d/lib/game_scripts/levels/clean_up/avatar_list.lua
1
4487
--[[ Copyright (C) 2019 The DMLab2D Authors. 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 https://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. ]] local random = require 'system.random' local read_settings = require 'common.read_settings' local tile = require 'system.tile' local tensor = require 'system.tensor' local class = require 'common.class' local avatar = require 'avatar' local images = require 'images' local AvatarList = class.Class() function AvatarList.defaultSettings() return { bots = 0, player = read_settings.default(avatar.Avatar.defaultSettings()), } end function AvatarList:__init__(kwargs) local numAvatars = kwargs.settings.bots + kwargs.numPlayers self._simSettings = kwargs.simSettings self._numPlayers = kwargs.numPlayers self._numAvatars = numAvatars self.playerFineMatrix = tensor.Int32Tensor(numAvatars, numAvatars) self._avatarList = {} for i = 1, numAvatars do self._avatarList[i] = avatar.Avatar{ avatars = self, index = i, settings = kwargs.settings.player[i], isBot = i > kwargs.numPlayers, simSettings = kwargs.simSettings, } end end function AvatarList:addConfigs(worldConfig) table.insert(worldConfig.updateOrder, 1, 'respawn') table.insert(worldConfig.updateOrder, 2, 'move') table.insert(worldConfig.updateOrder, 3, 'fire') worldConfig.hits.direction = { layer = 'direction', sprite = 'Direction', } worldConfig.hits.clean = { layer = 'beamClean', sprite = 'BeamClean', } worldConfig.hits.fine = { layer = 'beamFine', sprite = 'BeamFine', } table.insert(worldConfig.renderOrder, 'beamClean') table.insert(worldConfig.renderOrder, 'beamFine') table.insert(worldConfig.renderOrder, 'direction') for _, av in ipairs(self._avatarList) do av:addConfigs(worldConfig) end end function AvatarList:addSprites(tileSet) tileSet:addColor('Direction', {100, 100, 100, 200}) tileSet:addColor('BeamFine', {252, 252, 106}) tileSet:addColor('BeamClean', {99, 223, 242}) for _, av in ipairs(self._avatarList) do av:addSprites(tileSet) end end function AvatarList:_startFrame() self.playerFineMatrix:fill(0) end function AvatarList:getReward(grid) local reward = 0 for _, av in ipairs(self._avatarList) do reward = reward + av:getReward(grid) end return reward end function AvatarList:discreteActionSpec() local act = {} for _, av in ipairs(self._avatarList) do av:discreteActionSpec(act) end return act end function AvatarList:discreteActions(grid, actions) for _, av in ipairs(self._avatarList) do av:discreteActions(grid, actions) end end function AvatarList:addObservations(tileSet, world, observations) local numAvatars = self._numAvatars observations[#observations + 1] = { name = 'WORLD.PLAYER_FINE_COUNT', type = 'Int32s', shape = {numAvatars, numAvatars}, func = function(grid) return self.playerFineMatrix end } for _, av in ipairs(self._avatarList) do av:addObservations(tileSet, world, observations, numAvatars) end end function AvatarList:update(grid) self:_startFrame() for _, av in ipairs(self._avatarList) do av:update(grid) end end function AvatarList:start(grid) grid:setUpdater{update = 'fire', group = 'players'} grid:setUpdater{update = 'move', group = 'players'} grid:setUpdater{update = 'respawn', group = 'players.wait', startFrame = 10} local points = grid:groupShuffledWithCount( random, 'spawnPoints', self._numAvatars) assert(#points == self._numAvatars, "Insufficient spawn points!") self.pieceToIndex = {} self.indexToPiece = {} for i, point in ipairs(points) do local avatarPiece = self._avatarList[i]:start(grid, point) self.pieceToIndex[avatarPiece] = i self.indexToPiece[i] = avatarPiece end self:_startFrame() end function AvatarList:addPlayerCallbacks(callbacks) for _, av in ipairs(self._avatarList) do av:addPlayerCallbacks(callbacks) end end return {AvatarList = AvatarList}
apache-2.0
xasw5632/-ADOLF_HITLER
tg/test.lua
210
2571
started = 0 our_id = 0 function vardump(value, depth, key) local linePrefix = "" local spaces = "" if key ~= nil then linePrefix = "["..key.."] = " end if depth == nil then depth = 0 else depth = depth + 1 for i=1, depth do spaces = spaces .. " " end end if type(value) == 'table' then mTable = getmetatable(value) if mTable == nil then print(spaces ..linePrefix.."(table) ") else print(spaces .."(metatable) ") value = mTable end for tableKey, tableValue in pairs(value) do vardump(tableValue, depth, tableKey) end elseif type(value) == 'function' or type(value) == 'thread' or type(value) == 'userdata' or value == nil then print(spaces..tostring(value)) else print(spaces..linePrefix.."("..type(value)..") "..tostring(value)) end end print ("HI, this is lua script") function ok_cb(extra, success, result) end -- Notification code {{{ function get_title (P, Q) if (Q.type == 'user') then return P.first_name .. " " .. P.last_name elseif (Q.type == 'chat') then return Q.title elseif (Q.type == 'encr_chat') then return 'Secret chat with ' .. P.first_name .. ' ' .. P.last_name else return '' end end local lgi = require ('lgi') local notify = lgi.require('Notify') notify.init ("Telegram updates") local icon = os.getenv("HOME") .. "/.telegram-cli/telegram-pics/telegram_64.png" function do_notify (user, msg) local n = notify.Notification.new(user, msg, icon) n:show () end -- }}} function on_msg_receive (msg) if started == 0 then return end if msg.out then return end do_notify (get_title (msg.from, msg.to), msg.text) if (msg.text == 'ping') then if (msg.to.id == our_id) then send_msg (msg.from.print_name, 'pong', ok_cb, false) else send_msg (msg.to.print_name, 'pong', ok_cb, false) end return end if (msg.text == 'PING') then if (msg.to.id == our_id) then fwd_msg (msg.from.print_name, msg.id, ok_cb, false) else fwd_msg (msg.to.print_name, msg.id, ok_cb, false) end return end end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) --vardump (chat) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end function cron() -- do something postpone (cron, false, 1.0) end function on_binlog_replay_end () started = 1 postpone (cron, false, 1.0) end
gpl-2.0
cmotc/awesome
lib/menubar/icon_theme.lua
1
8669
--------------------------------------------------------------------------- --- Class module for icon lookup for menubar -- -- @author Kazunobu Kuriyama -- @copyright 2015 Kazunobu Kuriyama -- @classmod menubar.icon_theme --------------------------------------------------------------------------- -- This implementation is based on the specifications: -- Icon Theme Specification 0.12 -- http://standards.freedesktop.org/icon-theme-spec/icon-theme-spec-0.12.html local beautiful = require("beautiful") local awful_util = require("awful.util") local GLib = require("lgi").GLib local index_theme = require("menubar.index_theme") local ipairs = ipairs local setmetatable = setmetatable local string = string local table = table local math = math local get_pragmatic_base_directories = function() local dirs = {} local dir = GLib.build_filenamev({GLib.get_home_dir(), ".icons"}) if awful_util.dir_readable(dir) then table.insert(dirs, dir) end dir = GLib.build_filenamev({GLib.get_user_data_dir(), "icons"}) if awful_util.dir_readable(dir) then table.insert(dirs, dir) end for _, v in ipairs(GLib.get_system_data_dirs()) do dir = GLib.build_filenamev({v, "icons"}) if awful_util.dir_readable(dir) then table.insert(dirs, dir) end end local need_usr_share_pixmaps = true for _, v in ipairs(GLib.get_system_data_dirs()) do dir = GLib.build_filenamev({v, "pixmaps"}) if awful_util.dir_readable(dir) then table.insert(dirs, dir) end if dir == "/usr/share/pixmaps" then need_usr_share_pixmaps = false end end dir = "/usr/share/pixmaps" if need_usr_share_pixmaps and awful_util.dir_readable(dir) then table.insert(dirs, dir) end return dirs end local get_default_icon_theme_name = function() local icon_theme_names = { "Adwaita", "gnome", "hicolor" } for _, dir in ipairs(get_pragmatic_base_directories()) do for _, icon_theme_name in ipairs(icon_theme_names) do local filename = string.format("%s/%s/index.theme", dir, icon_theme_name) if awful_util.file_readable(filename) then return icon_theme_name end end end return nil end local icon_theme = { mt = {} } local index_theme_cache = {} --- Class constructor of `icon_theme` -- @tparam string icon_theme_name Internal name of icon theme -- @tparam table base_directories Paths used for lookup -- @treturn table An instance of the class `icon_theme` icon_theme.new = function(icon_theme_name, base_directories) icon_theme_name = icon_theme_name or beautiful.icon_theme or get_default_icon_theme_name() base_directories = base_directories or get_pragmatic_base_directories() local self = {} self.icon_theme_name = icon_theme_name self.base_directories = base_directories self.extensions = { "png", "svg", "xpm" } -- Instantiate index_theme (cached). if not index_theme_cache[self.icon_theme_name] then index_theme_cache[self.icon_theme_name] = {} end local cache_key = table.concat(self.base_directories, ':') if not index_theme_cache[self.icon_theme_name][cache_key] then index_theme_cache[self.icon_theme_name][cache_key] = index_theme( self.icon_theme_name, self.base_directories) end self.index_theme = index_theme_cache[self.icon_theme_name][cache_key] return setmetatable(self, { __index = icon_theme }) end local directory_matches_size = function(self, subdirectory, icon_size) local kind, size, min_size, max_size, threshold = self.index_theme:get_per_directory_keys(subdirectory) if kind == "Fixed" then return icon_size == size elseif kind == "Scalable" then return icon_size >= min_size and icon_size <= max_size elseif kind == "Threshold" then return icon_size >= size - threshold and icon_size <= size + threshold end return false end local directory_size_distance = function(self, subdirectory, icon_size) local kind, size, min_size, max_size, threshold = self.index_theme:get_per_directory_keys(subdirectory) if kind == "Fixed" then return math.abs(icon_size - size) elseif kind == "Scalable" then if icon_size < min_size then return min_size - icon_size elseif icon_size > max_size then return icon_size - max_size end return 0 elseif kind == "Threshold" then if icon_size < size - threshold then return min_size - icon_size elseif icon_size > size + threshold then return icon_size - max_size end return 0 end return 0xffffffff -- Any large number will do. end local lookup_icon = function(self, icon_name, icon_size) local checked_already = {} for _, subdir in ipairs(self.index_theme:get_subdirectories()) do for _, basedir in ipairs(self.base_directories) do for _, ext in ipairs(self.extensions) do if directory_matches_size(self, subdir, icon_size) then local filename = string.format("%s/%s/%s/%s.%s", basedir, self.icon_theme_name, subdir, icon_name, ext) if awful_util.file_readable(filename) then return filename else checked_already[filename] = true end end end end end local minimal_size = 0xffffffff -- Any large number will do. local closest_filename = nil for _, subdir in ipairs(self.index_theme:get_subdirectories()) do local dist = directory_size_distance(self, subdir, icon_size) if dist < minimal_size then for _, basedir in ipairs(self.base_directories) do for _, ext in ipairs(self.extensions) do local filename = string.format("%s/%s/%s/%s.%s", basedir, self.icon_theme_name, subdir, icon_name, ext) if not checked_already[filename] then if awful_util.file_readable(filename) then closest_filename = filename minimal_size = dist end end end end end end return closest_filename end local find_icon_path_helper -- Gets called recursively. find_icon_path_helper = function(self, icon_name, icon_size) local filename = lookup_icon(self, icon_name, icon_size) if filename then return filename end for _, parent in ipairs(self.index_theme:get_inherits()) do local parent_icon_theme = icon_theme(parent, self.base_directories) filename = find_icon_path_helper(parent_icon_theme, icon_name, icon_size) if filename then return filename end end return nil end local lookup_fallback_icon = function(self, icon_name) for _, dir in ipairs(self.base_directories) do for _, ext in ipairs(self.extensions) do local filename = string.format("%s/%s.%s", dir, icon_name, ext) if awful_util.file_readable(filename) then return filename end end end return nil end --- Look up an image file based on a given icon name and/or a preferable size. -- @tparam string icon_name Icon name to be looked up -- @tparam number icon_size Prefereable icon size -- @treturn string Absolute path to the icon file, or nil if not found function icon_theme:find_icon_path(icon_name, icon_size) icon_size = icon_size or 16 if not icon_name or icon_name == "" then return nil end local filename = find_icon_path_helper(self, icon_name, icon_size) if filename then return filename end if self.icon_theme_name ~= "hicolor" then filename = find_icon_path_helper(icon_theme("hicolor", self.base_directories), icon_name, icon_size) if filename then return filename end end return lookup_fallback_icon(self, icon_name) end icon_theme.mt.__call = function(_, ...) return icon_theme.new(...) end return setmetatable(icon_theme, icon_theme.mt) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
kidanger/LD27
turret.lua
1
3455
local physic = require 'physic' local particle = require 'particle' local Turret = { range = 45, last_fire = -9, reload = 2, tick = 0, rockets = {}, } Turret.__index = Turret function Turret:on_attach() self.offangle = math.random() * math.pi * 2 self.rockets = {} end function Turret:draw() local ct = require 'content' local R = self.level.ratio local sprite = ct.sprites.turret_base local transform = { angle=0, wfactor=self.size*R / sprite.w, hfactor=self.size*R / sprite.h, } set_color(self.color) draw_sprite(sprite, self.x*R, self.y*R, transform) local sprite = ct.sprites.turret_canon set_color(255,255,255) transform.angle = self.angle draw_sprite(sprite, self.x*R, self.y*R, transform) set_color(255,255,255) for _, r in ipairs(self.rockets) do local sprite = ct.sprites.missile local x, y = r.body:get_position() local angle = r.body:get_angle() draw_sprite_rotated(sprite, x*R-sprite.w/2, y*R-sprite.h/2, angle) end end function Turret:draw2() local dx, dy = get_offset() for _, r in ipairs(self.rockets) do r.part:draw(dx, dy) end end function Turret:update(dt) local ship = require 'ship' self.tick = self.tick + dt local sx, sy = ship.body:get_position() local dx, dy = ship.body:get_linear_velocity() sx, sy = sx + dx*0.3, sy + dy*0.3 local can_see = math.sqrt((sx-self.x)^2 + (sy-self.y)^2) < self.range if can_see then local angle = math.atan2(sy - self.y, sx - self.x) self.angle = angle if self.last_fire + self.reload < self.tick then self:fire(angle + math.random()*math.pi/12-math.pi/24) end else self.angle = math.sin(self.tick + self.offangle) * math.pi end for i, r in ipairs(self.rockets) do local x, y = r.body:get_position() local R = self.level.ratio r.part:set_position(x*R, y*R) r.part:update(dt) if r.remove_me then r.body:destroy() table.remove(self.rockets, i) end end end function Turret:fire(angle) self.last_fire = self.tick local x, y = self.x + math.cos(angle)*2, self.y + math.sin(angle)*2 local w, h = 0.8, 0.3 local rocket = { x=x, y=y, w=w, h=h, part=particle.new_system(0, 0) } local shape = physic.new_shape('box', w, h) shape:set_density(0) rocket.body = physic.new_body(shape, true) rocket.body:set_position(x+w/2, y+h/2) rocket.body:set_angle(angle) local speed = 50 rocket.body:set_linear_damping(0) rocket.body:set_linear_velocity(math.cos(angle)*speed, math.sin(angle)*speed) rocket.body.is_rocket = true rocket.body.parent = rocket rocket.remove_me = false rocket.body.begin_collide = function(_, o) if not o.is_turret and not o.is_capsule and not o.is_text then rocket.remove_me = true end end local R = self.level.ratio rocket.part:set_position(x*R, y*R) rocket.part:add_size(0, 3) rocket.part:add_size(.3, 5) rocket.part:add_size(1, 1) rocket.part:add_color(0, 50, 50, 50) rocket.part:add_color(0.3, 180, 200, 50, 100, 0, 0) rocket.part:add_color(0.5, 180, 200, 100, 200, 0, 0) rocket.part:add_color(0.7, 0, 0, 0) rocket.part:add_color(1, 0, 0, 0) rocket.part:set_lifetime(0.5) rocket.part:set_emission_rate(50) rocket.part:set_initial_velocity(20) rocket.part:set_initial_acceleration(50) rocket.part:start() table.insert(self.rockets, rocket) local ct = require 'content' ct.play('fire') end function Turret:destroy() self.body:destroy() for _, r in ipairs(self.rockets) do r.body:destroy() end self.rockets = {} end return Turret
gpl-2.0
xdemolish/darkstar
scripts/zones/Silver_Sea_route_to_Nashmau/Zone.lua
17
1444
----------------------------------- -- -- Zone: Silver_Sea_route_to_Nashmau -- ----------------------------------- package.loaded["scripts/zones/Silver_Sea_route_to_Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Silver_Sea_route_to_Nashmau/TextIDs"); require("scripts/globals/settings"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; return cs; end; ----------------------------------- -- onTransportEvent ----------------------------------- function onTransportEvent(player,transport) player:startEvent(0x0401); 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 == 0x0401) then player:setPos(0,0,0,0,53); end end;
gpl-3.0
xdemolish/darkstar
scripts/zones/Inner_Horutoto_Ruins/npcs/_5c5.lua
17
1979
----------------------------------- -- Area: Inner Horutoto Ruins -- NPC: Gate: Magical Gizmo -- Involved In Mission: The Horutoto Ruins Experiment -- @pos 419 0 -27 192 ----------------------------------- package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Inner_Horutoto_Ruins/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getCurrentMission(WINDURST) == THE_HORUTOTO_RUINS_EXPERIMENT and player:getVar("MissionStatus") == 1) then player:startEvent(0x002A); else player:showText(npc,DOOR_FIRMLY_CLOSED); end return 1; 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 == 0x002A) then player:setVar("MissionStatus",2); -- Generate a random value to use for the next part of the mission -- where you have to examine 6 Magical Gizmo's, each of them having -- a number from 1 to 6 (Remember, setting 0 deletes the var) local random_value = math.random(1,6); player:setVar("MissionStatus_rv",random_value); -- 'rv' = random value player:setVar("MissionStatus_op1",1); player:setVar("MissionStatus_op2",1); player:setVar("MissionStatus_op3",1); player:setVar("MissionStatus_op4",1); player:setVar("MissionStatus_op5",1); player:setVar("MissionStatus_op6",1); end end;
gpl-3.0
peymankhanas84877/Horror_Avatar_bot
plugins/plugins.lua
325
6164
do -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function list_all_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..nsum..'. '..v..' '..status..'\n' end end local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled' return text end local function list_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..v..' '..status..'\n' end end local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.' return text end local function reload_plugins( ) plugins = {} load_plugins() return list_plugins(true) end local function enable_plugin( plugin_name ) print('checking if '..plugin_name..' exists') -- Check if plugin is enabled if plugin_enabled(plugin_name) then return 'Plugin '..plugin_name..' is enabled' end -- Checks if plugin exists if plugin_exists(plugin_name) then -- Add to the config table table.insert(_config.enabled_plugins, plugin_name) print(plugin_name..' added to _config table') save_config() -- Reload the plugins return reload_plugins( ) else return 'Plugin '..plugin_name..' does not exists' end end local function disable_plugin( name, chat ) -- Check if plugins exists if not plugin_exists(name) then return 'Plugin '..name..' does not exists' end local k = plugin_enabled(name) -- Check if plugin is enabled if not k then return 'Plugin '..name..' not enabled' end -- Disable and reload table.remove(_config.enabled_plugins, k) save_config( ) return reload_plugins(true) end local function disable_plugin_on_chat(receiver, plugin) if not plugin_exists(plugin) then return "Plugin doesn't exists" end if not _config.disabled_plugin_on_chat then _config.disabled_plugin_on_chat = {} end if not _config.disabled_plugin_on_chat[receiver] then _config.disabled_plugin_on_chat[receiver] = {} end _config.disabled_plugin_on_chat[receiver][plugin] = true save_config() return 'Plugin '..plugin..' disabled on this chat' end local function reenable_plugin_on_chat(receiver, plugin) if not _config.disabled_plugin_on_chat then return 'There aren\'t any disabled plugins' end if not _config.disabled_plugin_on_chat[receiver] then return 'There aren\'t any disabled plugins for this chat' end if not _config.disabled_plugin_on_chat[receiver][plugin] then return 'This plugin is not disabled' end _config.disabled_plugin_on_chat[receiver][plugin] = false save_config() return 'Plugin '..plugin..' is enabled again' end local function run(msg, matches) -- Show the available plugins if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo return list_all_plugins() end -- Re-enable a plugin for this chat if matches[1] == 'enable' and matches[3] == 'chat' then local receiver = get_receiver(msg) local plugin = matches[2] print("enable "..plugin..' on this chat') return reenable_plugin_on_chat(receiver, plugin) end -- Enable a plugin if matches[1] == 'enable' and is_sudo(msg) then --after changed to moderator mode, set only sudo local plugin_name = matches[2] print("enable: "..matches[2]) return enable_plugin(plugin_name) end -- Disable a plugin on a chat if matches[1] == 'disable' and matches[3] == 'chat' then local plugin = matches[2] local receiver = get_receiver(msg) print("disable "..plugin..' on this chat') return disable_plugin_on_chat(receiver, plugin) end -- Disable a plugin if matches[1] == 'disable' and is_sudo(msg) then --after changed to moderator mode, set only sudo if matches[2] == 'plugins' then return 'This plugin can\'t be disabled' end print("disable: "..matches[2]) return disable_plugin(matches[2]) end -- Reload all the plugins! if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true) end end return { description = "Plugin to manage other plugins. Enable, disable or reload.", usage = { moderator = { "!plugins disable [plugin] chat : disable plugin only this chat.", "!plugins enable [plugin] chat : enable plugin only this chat.", }, sudo = { "!plugins : list all plugins.", "!plugins enable [plugin] : enable plugin.", "!plugins disable [plugin] : disable plugin.", "!plugins reload : reloads all plugins." }, }, patterns = { "^!plugins$", "^!plugins? (enable) ([%w_%.%-]+)$", "^!plugins? (disable) ([%w_%.%-]+)$", "^!plugins? (enable) ([%w_%.%-]+) (chat)", "^!plugins? (disable) ([%w_%.%-]+) (chat)", "^!plugins? (reload)$" }, run = run, moderated = true, -- set to moderator mode --privileged = true } end
gpl-2.0
dmccuskey/dmc-events-mixin
dmc_corona/dmc_events_mix.lua
2
3816
--====================================================================-- -- dmc_corona/dmc_events_mix.lua -- -- Documentation: http://docs.davidmccuskey.com/ --====================================================================-- --[[ The MIT License (MIT) Copyright (c) 2015 David McCuskey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] --====================================================================-- --== DMC Corona Library : DMC Events Mix --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.1.0" --====================================================================-- --== DMC Corona Library Config --====================================================================-- --====================================================================-- --== Support Functions local Utils = {} -- make copying from Utils easier --== Start: copy from lua_utils ==-- -- extend() -- Copy key/values from one table to another -- Will deep copy any value from first table which is itself a table. -- -- @param fromTable the table (object) from which to take key/value pairs -- @param toTable the table (object) in which to copy key/value pairs -- @return table the table (object) that received the copied items -- function Utils.extend( fromTable, toTable ) if not fromTable or not toTable then error( "table can't be nil" ) end function _extend( fT, tT ) for k,v in pairs( fT ) do if type( fT[ k ] ) == "table" and type( tT[ k ] ) == "table" then tT[ k ] = _extend( fT[ k ], tT[ k ] ) elseif type( fT[ k ] ) == "table" then tT[ k ] = _extend( fT[ k ], {} ) else tT[ k ] = v end end return tT end return _extend( fromTable, toTable ) end --== End: copy from lua_utils ==-- --====================================================================-- --== Configuration local dmc_lib_data -- boot dmc_corona with boot script or -- setup basic defaults if it doesn't exist -- if false == pcall( function() require( 'dmc_corona_boot' ) end ) then _G.__dmc_corona = { dmc_corona={}, } end dmc_lib_data = _G.__dmc_corona --====================================================================-- --== DMC States Mix --====================================================================-- --====================================================================-- --== Configuration dmc_lib_data.dmc_events_mix = dmc_lib_data.dmc_events_mix or {} local DMC_EVENTS_MIX_DEFAULTS = { } local dmc_events_mix_data = Utils.extend( dmc_lib_data.dmc_events_mix, DMC_EVENTS_MIX_DEFAULTS ) --====================================================================-- --== Imports local EventsMixModule = require 'lib.dmc_lua.lua_events_mix' return EventsMixModule
mit
cfanzp008/skynet-note
service/service_mgr.lua
3
1386
local skynet = require "skynet" local cmd = {} local service = {} function cmd.LAUNCH(service_name, ...) local s = service[service_name] if type(s) == "number" then return s end if s == nil then s = { launch = true } service[service_name] = s elseif s.launch then assert(type(s) == "table") local co = coroutine.running() table.insert(s, co) skynet.wait() s = service[service_name] assert(type(s) == "number") return s end local handle = skynet.newservice(service_name, ...) for _,v in ipairs(s) do skynet.wakeup(v) end service[service_name] = handle return handle end function cmd.QUERY(service_name) local s = service[service_name] if type(s) == "number" then return s end if s == nil then s = {} service[service_name] = s end assert(type(s) == "table") local co = coroutine.running() table.insert(s, co) skynet.wait() s = service[service_name] assert(type(s) == "number") return s end skynet.start(function() skynet.dispatch("lua", function(session, address, command, service_name , ...) local f = cmd[command] if f == nil then skynet.ret(skynet.pack(nil)) return end local ok, r = pcall(f, service_name, ...) if ok then skynet.ret(skynet.pack(r)) else skynet.ret(skynet.pack(nil)) end end) skynet.register(".service") if skynet.getenv "standalone" then skynet.register("SERVICE") end end)
mit
czfshine/UpAndAway
code/prefabs/gnome_decor.lua
2
1248
BindGlobal() local assets = { Asset("ANIM", "anim/gnome_decor.zip"), } local function makefn(bankname, buildname, animname) local function fn(Sim) local inst = CreateEntity() local trans = inst.entity:AddTransform() local anim = inst.entity:AddAnimState() inst:AddTag("DECOR") anim:SetBank(bankname) anim:SetBuild(buildname) anim:PlayAnimation(animname) ------------------------------------------------------------------------ SetupNetwork(inst) ------------------------------------------------------------------------ return inst end return fn end return { Prefab ("forest/objects/gnomedecor/gnome_farmrock", makefn("gnome_decor", "gnome_decor", "1"), assets), Prefab ("forest/objects/gnomedecor/gnome_farmrocktall", makefn("gnome_decor", "gnome_decor", "2"), assets), Prefab ("forest/objects/gnomedecor/gnome_farmrockflat", makefn("gnome_decor", "gnome_decor", "8"), assets), Prefab ("forest/objects/gnomedecor/gnome_fencepost", makefn("gnome_decor", "gnome_decor", "5"), assets), Prefab ("forest/objects/gnomedecor/gnome_fencepostright", makefn("gnome_decor", "gnome_decor", "9"), assets), }
gpl-2.0
grmss214/SHATELTEAM
plugins/inrealm.lua
1
25481
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end 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 set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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 --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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 --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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 lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end 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 -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" 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 return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver 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 mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) 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] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^(creategroup) (.*)$", "^(createrealm) (.*)$", "^(setabout) (%d+) (.*)$", "^(setrules) (%d+) (.*)$", "^(setname) (.*)$", "^(setgpname) (%d+) (.*)$", "^(setname) (%d+) (.*)$", "^(lock) (%d+) (.*)$", "^(unlock) (%d+) (.*)$", "^(setting) (%d+)$", "^(wholist)$", "^(who)$", "^(type)$", "^(kill) (chat) (%d+)$", "^(kill) (realm) (%d+)$", "^(addadmin) (.*)$", -- sudoers only "^(removeadmin) (.*)$", -- sudoers only "^(list) (.*)$", "^(log)$", "^(help)$", "^(creategroup) (.*)$", "^(createrealm) (.*)$", "^(setabout) (%d+) (.*)$", "^(setrules) (%d+) (.*)$", "^(setname) (.*)$", "^(setgpname) (%d+) (.*)$", "^(setname) (%d+) (.*)$", "^(lock) (%d+) (.*)$", "^(unlock) (%d+) (.*)$", "^(setting) (%d+)$", "^(wholist)$", "^(who)$", "^(type)$", "^(kill) (chat) (%d+)$", "^(kill) (realm) (%d+)$", "^(addadmin) (.*)$", -- sudoers only "^(removeadmin) (.*)$", -- sudoers only "^(list) (.*)$", "^(log)$", "^(help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
xdemolish/darkstar
scripts/zones/East_Sarutabaruta/npcs/Sama_Gohjima.lua
17
1491
----------------------------------- -- Area: East Sarutabaruta -- NPC: Sama Gohjima -- Involved in Mission: The Horutoto Ruins Experiment (optional) -- @pos 377 -13 98 116 ----------------------------------- package.loaded["scripts/zones/East_Sarutabaruta/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/East_Sarutabaruta/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getCurrentMission(WINDURST) == THE_HORUTOTO_RUINS_EXPERIMENT and player:getVar("MissionStatus") == 1) then player:showText(npc,SAMA_GOHJIMA_PREDIALOG); elseif(player:getCurrentMission(WINDURST) == THE_HORUTOTO_RUINS_EXPERIMENT and player:getVar("MissionStatus") ~= 1) then player:messageSpecial(SAMA_GOHJIMA_POSTDIALOG); else player:startEvent(0x002b); 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
kaadmy/pixture
mods/default/tools.lua
1
19500
-- -- Tool definitions -- local creative_digtime = 0.15 local tool_levels = nil -- Creative mode/hand defs if minetest.settings:get_bool("creative_mode") == true then tool_levels = { wood = { crumbly = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, choppy = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, cracky = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, snappy = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, }, stone = { crumbly = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, choppy = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, cracky = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, snappy = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, }, wrought_iron = { crumbly = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, choppy = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, cracky = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, snappy = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, }, steel = { crumbly = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, choppy = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, cracky = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, snappy = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, }, carbon_steel = { crumbly = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, choppy = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, cracky = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, snappy = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, }, bronze = { crumbly = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, choppy = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, cracky = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, snappy = { [3] = creative_digtime, [2] = creative_digtime, [1] = creative_digtime, }, }, } minetest.register_item( ":", { type = "none", wield_image = "wieldhand.png", wield_scale = {x=1.0,y=1.0,z=2.0}, tool_capabilities = { full_punch_interval = 1.0, max_drop_level = 0, groupcaps = { fleshy = {times={[1]=creative_digtime, [2]=creative_digtime, [3]=creative_digtime}, uses=0, maxlevel=1}, crumbly = {times={[1]=creative_digtime, [2]=creative_digtime, [3]=creative_digtime}, uses=0, maxlevel=1}, choppy = {times={[1]=creative_digtime, [2]=creative_digtime, [3]=creative_digtime}, uses=0, maxlevel=1}, cracky = {times={[1]=creative_digtime, [2]=creative_digtime, [3]=creative_digtime}, uses=0, maxlevel=1}, snappy = {times={[1]=creative_digtime, [2]=creative_digtime, [3]=creative_digtime}, uses=0, maxlevel=1}, oddly_breakable_by_hand = {times={[1]=creative_digtime,[2]=creative_digtime,[3]=creative_digtime}, uses=0, maxlevel=3}, }, range = 3.8, damage_groups = {fleshy = 1} } }) else tool_levels = { wood = { crumbly = { [3] = 1.6, [2] = 2.0, }, choppy = { [3] = 2.6, [2] = 3.0, }, cracky = { [3] = 3.8, [2] = 4.2, }, snappy = { [3] = 0.5, [2] = 1.0, }, }, stone = { crumbly = { [3] = 1.3, [2] = 1.7, }, choppy = { [3] = 2.3, [2] = 2.7, }, cracky = { [3] = 3.3, [2] = 3.7, }, snappy = { [3] = 0.4, [2] = 0.9, }, }, wrought_iron = { crumbly = { [3] = 1.0, [2] = 1.4, }, choppy = { [3] = 2.0, [2] = 2.4, }, cracky = { [3] = 2.8, [2] = 3.2, }, snappy = { [3] = 0.3, [2] = 0.8, }, }, steel = { crumbly = { [3] = 0.9, [2] = 1.2, [1] = 3.5, }, choppy = { [3] = 1.7, [2] = 2.1, [1] = 3.2, }, cracky = { [3] = 2.3, [2] = 2.7, [1] = 3.8, }, snappy = { [3] = 0.2, [2] = 0.7, [1] = 1.2, }, }, carbon_steel = { crumbly = { [3] = 0.6, [2] = 1.0, [1] = 2.7, }, choppy = { [3] = 1.2, [2] = 1.8, [1] = 2.6, }, cracky = { [3] = 1.8, [2] = 2.3, [1] = 3.3, }, snappy = { [3] = 0.2, [2] = 0.5, [1] = 1.0, }, }, bronze = { crumbly = { [3] = 0.3, [2] = 0.7, [1] = 2.3, }, choppy = { [3] = 0.6, [2] = 1.1, [1] = 1.8, }, cracky = { [3] = 1.4, [2] = 1.9, [1] = 2.7, }, snappy = { [3] = 0.1, [2] = 0.3, [1] = 0.7, }, }, } minetest.register_item( ":", { type = "none", wield_image = "wieldhand.png", wield_scale = {x=1.0,y=1.0,z=2.0}, tool_capabilities = { full_punch_interval = 1.0, max_drop_level = 0, groupcaps = { crumbly = {times={[2]=3.2, [3]=2.1}, uses=0, maxlevel=1}, choppy = {times={[2]=3.5, [3]=3.8}, uses=0, maxlevel=1}, cracky = {times={[2]=8.5, [3]=7.0}, uses=0, maxlevel=1}, snappy = {times={[1]=2.5, [2]=2.0, [3]=1.5}, uses=0, maxlevel=1}, fleshy = {times={[2]=1.6, [3]=1.0}, uses=0, maxlevel=1}, oddly_breakable_by_hand = {times={[1]=7.0,[2]=5.5,[3]=4.0}, uses=0, maxlevel=1}, }, range = 3.8, damage_groups = {fleshy = 1} } }) end -- "Creative" Tool minetest.register_tool( "default:creative_tool", { inventory_image = "default_creative_tool.png", tool_capabilities = { full_punch_interval = 0.5, max_drop_level = 0, groupcaps = { fleshy = {times={[1]=creative_digtime, [2]=creative_digtime, [3]=creative_digtime}, uses=0, maxlevel=1}, crumbly = {times={[1]=creative_digtime, [2]=creative_digtime, [3]=creative_digtime}, uses=0, maxlevel=1}, choppy = {times={[1]=creative_digtime, [2]=creative_digtime, [3]=creative_digtime}, uses=0, maxlevel=1}, cracky = {times={[1]=creative_digtime, [2]=creative_digtime, [3]=creative_digtime}, uses=0, maxlevel=1}, snappy = {times={[1]=creative_digtime, [2]=creative_digtime, [3]=creative_digtime}, uses=0, maxlevel=1}, oddly_breakable_by_hand = {times={[1]=creative_digtime,[2]=creative_digtime,[3]=creative_digtime}, uses=0, maxlevel=3}, }, range = 20.8, damage_groups = {fleshy = 1} } }) -- Pickaxes minetest.register_tool( "default:pick_wood", { description = "Wooden Pickaxe", inventory_image = "default_pick_wood.png", tool_capabilities = { max_drop_level=0, groupcaps={ cracky={times=tool_levels.wood.cracky, uses=10, maxlevel=1} }, damage_groups = {fleshy = 2} }, }) minetest.register_tool( "default:pick_stone", { description = "Stone Pickaxe", inventory_image = "default_pick_stone.png", tool_capabilities = { max_drop_level = 0, groupcaps = { cracky = {times = tool_levels.stone.cracky, uses = 20, maxlevel = 1} }, damage_groups = {fleshy = 3} }, }) minetest.register_tool( "default:pick_wrought_iron", { description = "Wrought Iron Pickaxe", inventory_image = "default_pick_wrought_iron.png", tool_capabilities = { max_drop_level=1, groupcaps={ cracky={times=tool_levels.wrought_iron.cracky, uses=15, maxlevel=2} }, damage_groups = {fleshy = 4} }, }) minetest.register_tool( "default:pick_steel", { description = "Steel Pickaxe", inventory_image = "default_pick_steel.png", tool_capabilities = { max_drop_level=1, groupcaps={ cracky={times=tool_levels.steel.cracky, uses=30, maxlevel=2} }, damage_groups = {fleshy = 5} }, }) minetest.register_tool( "default:pick_carbon_steel", { description = "Carbon Steel Pickaxe", inventory_image = "default_pick_carbon_steel.png", tool_capabilities = { max_drop_level=1, groupcaps={ cracky={times=tool_levels.carbon_steel.cracky, uses=40, maxlevel=2} }, damage_groups = {fleshy = 5} }, }) minetest.register_tool( "default:pick_bronze", { description = "Bronze Pickaxe", inventory_image = "default_pick_bronze.png", tool_capabilities = { max_drop_level=1, groupcaps={ cracky={times=tool_levels.bronze.cracky, uses=30, maxlevel=2} }, damage_groups = {fleshy = 5} }, }) -- Shovels minetest.register_tool( "default:shovel_wood", { description = "Wooden Shovel", inventory_image = "default_shovel_wood.png", tool_capabilities = { max_drop_level=0, groupcaps={ crumbly={times=tool_levels.wood.crumbly, uses=10, maxlevel=1} }, damage_groups = {fleshy = 2} }, }) minetest.register_tool( "default:shovel_stone", { description = "Stone Shovel", inventory_image = "default_shovel_stone.png", tool_capabilities = { max_drop_level=0, groupcaps={ crumbly={times=tool_levels.stone.crumbly, uses=20, maxlevel=1} }, damage_groups = {fleshy = 3} }, }) minetest.register_tool( "default:shovel_wrought_iron", { description = "Wrought Iron Shovel", inventory_image = "default_shovel_wrought_iron.png", tool_capabilities = { max_drop_level=1, groupcaps={ crumbly={times=tool_levels.wrought_iron.crumbly, uses=15, maxlevel=2} }, damage_groups = {fleshy = 4} }, }) minetest.register_tool( "default:shovel_steel", { description = "Steel Shovel", inventory_image = "default_shovel_steel.png", tool_capabilities = { max_drop_level=1, groupcaps={ crumbly={times=tool_levels.steel.crumbly, uses=30, maxlevel=2} }, damage_groups = {fleshy = 5} }, }) minetest.register_tool( "default:shovel_carbon_steel", { description = "Carbon Steel Shovel", inventory_image = "default_shovel_carbon_steel.png", tool_capabilities = { max_drop_level=1, groupcaps={ crumbly={times=tool_levels.carbon_steel.crumbly, uses=40, maxlevel=2} }, damage_groups = {fleshy = 5} }, }) minetest.register_tool( "default:shovel_bronze", { description = "Bronze Shovel", inventory_image = "default_shovel_bronze.png", tool_capabilities = { max_drop_level=1, groupcaps={ crumbly={times=tool_levels.bronze.crumbly, uses=30, maxlevel=2} }, damage_groups = {fleshy = 5} }, }) -- Axes minetest.register_tool( "default:axe_wood", { description = "Wooden Axe", inventory_image = "default_axe_wood.png", tool_capabilities = { max_drop_level=0, groupcaps={ choppy={times=tool_levels.wood.choppy, uses=10, maxlevel=1}, fleshy={times={[2]=1.20, [3]=0.60}, uses=20, maxlevel=1} }, damage_groups = {fleshy = 3} }, }) minetest.register_tool( "default:axe_stone", { description = "Stone Axe", inventory_image = "default_axe_stone.png", tool_capabilities = { max_drop_level=0, groupcaps={ choppy={times=tool_levels.stone.choppy, uses=20, maxlevel=1}, fleshy={times={[2]=1.10, [3]=0.40}, uses=25, maxlevel=1} }, damage_groups = {fleshy = 4} }, }) minetest.register_tool( "default:axe_wrought_iron", { description = "Wrought Iron Axe", inventory_image = "default_axe_wrought_iron.png", tool_capabilities = { max_drop_level=1, groupcaps={ choppy={times=tool_levels.wrought_iron.choppy, uses=15, maxlevel=2}, fleshy={times={[2]=1.00, [3]=0.20}, uses=30, maxlevel=1} }, damage_groups = {fleshy = 5} }, }) minetest.register_tool( "default:axe_steel", { description = "Steel Axe", inventory_image = "default_axe_steel.png", tool_capabilities = { max_drop_level=1, groupcaps={ choppy={times=tool_levels.steel.choppy, uses=30, maxlevel=2}, fleshy={times={[2]=1.00, [3]=0.20}, uses=35, maxlevel=1} }, damage_groups = {fleshy = 6} }, }) minetest.register_tool( "default:axe_carbon_steel", { description = "Carbon Steel Axe", inventory_image = "default_axe_carbon_steel.png", tool_capabilities = { max_drop_level=1, groupcaps={ choppy={times=tool_levels.carbon_steel.choppy, uses=40, maxlevel=2}, fleshy={times={[2]=1.00, [3]=0.20}, uses=40, maxlevel=1} }, damage_groups = {fleshy = 6} }, }) minetest.register_tool( "default:axe_bronze", { description = "Bronze Axe", inventory_image = "default_axe_bronze.png", tool_capabilities = { max_drop_level=1, groupcaps={ choppy={times=tool_levels.bronze.choppy, uses=30, maxlevel=2}, fleshy={times={[2]=1.00, [3]=0.20}, uses=40, maxlevel=1} }, damage_groups = {fleshy = 6} }, }) -- Spears minetest.register_tool( "default:spear_wood", { description = "Wooden Spear", inventory_image = "default_spear_wood.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=0, groupcaps={ snappy={times=tool_levels.wood.snappy, uses=10, maxlevel=1}, fleshy={times={[2]=1.10, [3]=0.60}, uses=10, maxlevel=1}, }, damage_groups = {fleshy = 4} } }) minetest.register_tool( "default:spear_stone", { description = "Stone Spear", inventory_image = "default_spear_stone.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=0, groupcaps={ snappy={times=tool_levels.stone.snappy, uses=20, maxlevel=1}, fleshy={times={[2]=0.80, [3]=0.40}, uses=20, maxlevel=1}, }, damage_groups = {fleshy = 5} } }) minetest.register_tool( "default:spear_wrought_iron", { description = "Wrought Iron Spear", inventory_image = "default_spear_wrought_iron.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=1, groupcaps={ snappy={times=tool_levels.wrought_iron.snappy, uses=15, maxlevel=1}, fleshy={times={[1]=2.00, [2]=0.80, [3]=0.40}, uses=15, maxlevel=2}, }, damage_groups = {fleshy = 6} } }) minetest.register_tool( "default:spear_steel", { description = "Steel Spear", inventory_image = "default_spear_steel.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=1, groupcaps={ snappy={times=tool_levels.steel.snappy, uses=30, maxlevel=1}, fleshy={times={[1]=2.00, [2]=0.80, [3]=0.40}, uses=30, maxlevel=2}, }, damage_groups = {fleshy = 10} } }) minetest.register_tool( "default:spear_carbon_steel", { description = "Carbon Steel Spear", inventory_image = "default_spear_carbon_steel.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=1, groupcaps={ snappy={times=tool_levels.carbon_steel.snappy, uses=40, maxlevel=1}, fleshy={times={[1]=2.00, [2]=0.80, [3]=0.40}, uses=40, maxlevel=2}, }, damage_groups = {fleshy = 10} } }) minetest.register_tool( "default:spear_bronze", { description = "Bronze Spear", inventory_image = "default_spear_bronze.png", tool_capabilities = { full_punch_interval = 1.0, max_drop_level=1, groupcaps={ snappy={times=tool_levels.bronze.snappy, uses=30, maxlevel=1}, fleshy={times={[1]=2.00, [2]=0.80, [3]=0.40}, uses=30, maxlevel=2}, }, damage_groups = {fleshy = 10} } }) -- Broadsword minetest.register_tool( "default:broadsword", { description = "Broadsword", inventory_image = "default_broadsword.png", wield_image = "default_broadsword.png", wield_scale = {x = 2.0, y = 2.0, z = 1.0}, tool_capabilities = { full_punch_interval = 4.0, damage_groups = {fleshy = 12} } }) -- Other minetest.register_tool( "default:shears", { description = "Wrought Iron Shears", inventory_image = "default_shears.png", }) minetest.register_tool( "default:flint_and_steel", { description = "Flint and Steel", inventory_image = "default_flint_and_steel.png", on_use = function(itemstack, user, pointed_thing) if pointed_thing == nil then return end if pointed_thing.type ~= "node" then return end local pos = pointed_thing.under local node = minetest.get_node(pos) local nodename = node.name if nodename == "default:torch_weak" then minetest.set_node( pos, { name = "default:torch", param = node.param, param2 = node.param2 }) itemstack:add_wear(800) elseif nodename == "default:torch_dead" then minetest.set_node( pos, { name = "default:torch_weak", param = node.param, param2 = node.param2 }) itemstack:add_wear(800) elseif nodename == "tnt:tnt" then local y = minetest.registered_nodes["tnt:tnt"] if y ~= nil then y.on_punch(pos, node, user) itemstack:add_wear(800) end end return itemstack end, }) default.log("tools", "loaded")
lgpl-2.1
xdemolish/darkstar
scripts/zones/Bastok_Markets/npcs/Reinberta.lua
11
1970
----------------------------------- -- Area: Bastok Markets -- NPC: Reinberta -- Type: Goldsmithing Guild Master -- @pos -190.605 -7.814 -59.432 235 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; ----------------------------------- require("scripts/globals/crafting"); require("scripts/zones/Bastok_Markets/TextIDs"); local SKILLID = 51; -- Goldsmithing ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local newRank = tradeTestItem(player,npc,trade,SKILLID); if(newRank ~= 0) then player:setSkillRank(SKILLID,newRank); player:startEvent(0x012d,0,0,0,0,newRank); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local getNewRank = 0; local craftSkill = player:getSkillLevel(SKILLID); local testItem = getTestItem(player,npc,SKILLID); local guildMember = isGuildMember(player,6); if(guildMember == 1) then guildMember = 150995375; end if(canGetNewRank(player,craftSkill,SKILLID) == 1) then getNewRank = 100; end player:startEvent(0x012c,testItem,getNewRank,30,guildMember,44,0,0,0); end; -- 0x012c 0x012d 0x0192 ----------------------------------- -- 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 == 0x012c and option == 1) then local crystal = math.random(4096,4101); if(player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,crystal); else player:addItem(crystal); player:messageSpecial(ITEM_OBTAINED,crystal); signupGuild(player,64); end end end;
gpl-3.0
kissthink/OpenRA
mods/cnc/maps/gdi05a/gdi05a.lua
19
6681
RepairThreshold = { Easy = 0.3, Normal = 0.6, Hard = 0.9 } ActorRemovals = { Easy = { Actor167, Actor168, Actor190, Actor191, Actor193, Actor194, Actor196, Actor198, Actor200 }, Normal = { Actor167, Actor194, Actor196, Actor197 }, Hard = { }, } GdiTanks = { "mtnk", "mtnk" } GdiApc = { "apc" } GdiInfantry = { "e1", "e1", "e1", "e1", "e1", "e2", "e2", "e2", "e2", "e2" } GdiBase = { GdiNuke1, GdiNuke2, GdiProc, GdiSilo1, GdiSilo2, GdiPyle, GdiWeap, GdiHarv } NodSams = { Sam1, Sam2, Sam3, Sam4 } CoreNodBase = { NodConYard, NodRefinery, HandOfNod, Airfield } Grd1UnitTypes = { "bggy" } Grd1Path = { waypoint4.Location, waypoint5.Location, waypoint10.Location } Grd1Delay = { Easy = DateTime.Minutes(2), Normal = DateTime.Minutes(1), Hard = DateTime.Seconds(30) } Grd2UnitTypes = { "bggy" } Grd2Path = { waypoint0.Location, waypoint1.Location, waypoint2.Location } Grd3Units = { GuardTank1, GuardTank2 } Grd3Path = { waypoint4.Location, waypoint5.Location, waypoint9.Location } AttackDelayMin = { Easy = DateTime.Minutes(1), Normal = DateTime.Seconds(45), Hard = DateTime.Seconds(30) } AttackDelayMax = { Easy = DateTime.Minutes(2), Normal = DateTime.Seconds(90), Hard = DateTime.Minutes(1) } AttackUnitTypes = { Easy = { { HandOfNod, { "e1", "e1" } }, { HandOfNod, { "e1", "e3" } }, { HandOfNod, { "e1", "e1", "e3" } }, { HandOfNod, { "e1", "e3", "e3" } }, }, Normal = { { HandOfNod, { "e1", "e1", "e3" } }, { HandOfNod, { "e1", "e3", "e3" } }, { HandOfNod, { "e1", "e1", "e3", "e3" } }, { Airfield, { "bggy" } }, }, Hard = { { HandOfNod, { "e1", "e1", "e3", "e3" } }, { HandOfNod, { "e1", "e1", "e1", "e3", "e3" } }, { HandOfNod, { "e1", "e1", "e3", "e3", "e3" } }, { Airfield, { "bggy" } }, { Airfield, { "ltnk" } }, } } AttackPaths = { { waypoint0.Location, waypoint1.Location, waypoint2.Location, waypoint3.Location }, { waypoint4.Location, waypoint9.Location, waypoint7.Location, waypoint8.Location }, } Build = function(factory, units, action) if factory.IsDead or factory.Owner ~= nod then return end if not factory.Build(units, action) then Trigger.AfterDelay(DateTime.Seconds(5), function() Build(factory, units, action) end) end end Attack = function() local types = Utils.Random(AttackUnitTypes[Map.Difficulty]) local path = Utils.Random(AttackPaths) Build(types[1], types[2], function(units) Utils.Do(units, function(unit) if unit.Owner ~= nod then return end unit.Patrol(path, false) Trigger.OnIdle(unit, unit.Hunt) end) end) Trigger.AfterDelay(Utils.RandomInteger(AttackDelayMin[Map.Difficulty], AttackDelayMax[Map.Difficulty]), Attack) end Grd1Action = function() Build(Airfield, Grd1UnitTypes, function(units) Utils.Do(units, function(unit) if unit.Owner ~= nod then return end Trigger.OnKilled(unit, function() Trigger.AfterDelay(Grd1Delay[Map.Difficulty], Grd1Action) end) unit.Patrol(Grd1Path, true, DateTime.Seconds(7)) end) end) end Grd2Action = function() Build(Airfield, Grd2UnitTypes, function(units) Utils.Do(units, function(unit) if unit.Owner ~= nod then return end unit.Patrol(Grd2Path, true, DateTime.Seconds(5)) end) end) end Grd3Action = function() local unit for i, u in ipairs(Grd3Units) do if not u.IsDead then unit = u break end end if unit ~= nil then Trigger.OnKilled(unit, function() Grd3Action() end) unit.Patrol(Grd3Path, true, DateTime.Seconds(11)) end end DiscoverGdiBase = function(actor, discoverer) if baseDiscovered or not discoverer == gdi then return end Utils.Do(GdiBase, function(actor) actor.Owner = gdi end) GdiHarv.FindResources() baseDiscovered = true gdiObjective3 = gdi.AddPrimaryObjective("Eliminate all Nod forces in the area.") gdi.MarkCompletedObjective(gdiObjective1) Attack() end SetupWorld = function() Utils.Do(ActorRemovals[Map.Difficulty], function(unit) unit.Destroy() end) Media.PlaySpeechNotification(gdi, "Reinforce") Reinforcements.Reinforce(gdi, GdiTanks, { GdiTankEntry.Location, GdiTankRallyPoint.Location }, DateTime.Seconds(1), function(actor) actor.Stance = "Defend" end) Reinforcements.Reinforce(gdi, GdiApc, { GdiApcEntry.Location, GdiApcRallyPoint.Location }, DateTime.Seconds(1), function(actor) actor.Stance = "Defend" end) Reinforcements.Reinforce(gdi, GdiInfantry, { GdiInfantryEntry.Location, GdiInfantryRallyPoint.Location }, 15, function(actor) actor.Stance = "Defend" end) Trigger.OnPlayerDiscovered(gdiBase, DiscoverGdiBase) Utils.Do(Map.NamedActors, function(actor) if actor.Owner == nod and actor.HasProperty("StartBuildingRepairs") then Trigger.OnDamaged(actor, function(building) if building.Owner == nod and building.Health < RepairThreshold[Map.Difficulty] * building.MaxHealth then building.StartBuildingRepairs() end end) end end) Trigger.OnAllKilled(NodSams, function() gdi.MarkCompletedObjective(gdiObjective2) Actor.Create("airstrike.proxy", true, { Owner = gdi }) end) GdiHarv.Stop() NodHarv.FindResources() if Map.Difficulty ~= "Easy" then Trigger.OnDamaged(NodHarv, function() Utils.Do(nod.GetGroundAttackers(), function(unit) unit.AttackMove(NodHarv.Location) if Map.Difficulty == "Hard" then unit.Hunt() end end) end) end Trigger.AfterDelay(DateTime.Seconds(45), Grd1Action) Trigger.AfterDelay(DateTime.Minutes(3), Grd2Action) Grd3Action() end WorldLoaded = function() gdiBase = Player.GetPlayer("AbandonedBase") gdi = Player.GetPlayer("GDI") nod = Player.GetPlayer("Nod") Trigger.OnObjectiveAdded(gdi, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) Trigger.OnObjectiveCompleted(gdi, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(gdi, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerLost(gdi, function() Media.PlaySpeechNotification(player, "Lose") end) Trigger.OnPlayerWon(gdi, function() Media.PlaySpeechNotification(player, "Win") end) nodObjective = nod.AddPrimaryObjective("Destroy all GDI troops.") gdiObjective1 = gdi.AddPrimaryObjective("Find the GDI base.") gdiObjective2 = gdi.AddSecondaryObjective("Destroy all SAM sites to receive air support.") SetupWorld() Camera.Position = GdiTankRallyPoint.CenterPosition end Tick = function() if gdi.HasNoRequiredUnits() then if DateTime.GameTime > 2 then nod.MarkCompletedObjective(nodObjective) end end if baseDiscovered and nod.HasNoRequiredUnits() then gdi.MarkCompletedObjective(gdiObjective3) end end
gpl-3.0
xdemolish/darkstar
scripts/zones/Toraimarai_Canal/npcs/qm10.lua
23
1509
----------------------------------- -- Area: Toraimarai Canal -- NPC: ??? -- Involved In Quest: Wild Card -- @zone 169 // not accurate -- @pos 220 16 -50 // not accurate ----------------------------------- package.loaded["scripts/zones/Toraimarai_Canal/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/Toraimarai_Canal/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("rootProblem") == 2) then if(player:getVar("rootProblemQ2") <= 1) then if(player:hasStatusEffect(EFFECT_MANAFONT) == true) then player:startEvent(0x2F); else player:startEvent(0x2E); end else player:startEvent(0x2A); 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 == 0x2F) then player:setVar("rootProblemQ2",2); end end;
gpl-3.0
czfshine/UpAndAway
code/prefabs/cloud_coral.lua
2
3053
BindGlobal() local CFG = TheMod:GetConfig() local assets = { Asset("ANIM", "anim/cloud_coral.zip"), } local prefabs = CFG.CLOUD_CORAL.PREFABS local function grow(inst, dt) if inst.components.scaler.scale < 2 then local new_scale = math.min(inst.components.scaler.scale + CFG.CLOUD_CORAL.GROW_RATE*dt, 2) inst.components.scaler:SetScale(new_scale) else if inst.growtask then inst.growtask:Cancel() inst.growtask = nil end end end local function applyscale(inst, scale) inst.components.workable:SetWorkLeft(scale*CFG.CLOUD_CORAL.WORK_TIME) local function lootscaling() local lootamount = scale*0.2 inst.components.lootdropper.numrandomloot = lootamount end end local function onMined(inst, chopper) inst.components.lootdropper:DropLoot() inst:Remove() end local function OnWork(inst, worker, workleft) local pt = Point(inst.Transform:GetWorldPosition()) if workleft < CFG.CLOUD_CORAL.WORK_TIME*(1/3) then inst.AnimState:PlayAnimation("idle_low") elseif workleft < CFG.CLOUD_CORAL.WORK_TIME*(2/3) then inst.AnimState:PlayAnimation("idle_med") else inst.AnimState:PlayAnimation("idle_full") end end local function onsave(inst, data) if inst.components.scaler.scale then data.scale = inst.components.scaler.scale end end local function onload(inst, data) if data and data.scale then inst.components.scaler:SetScale(data.scale) end end local function fn(Sim) local inst = CreateEntity() inst.entity:AddTransform() inst.entity:AddAnimState() inst.entity:AddSoundEmitter() inst.AnimState:SetBank("cloud_coral") inst.AnimState:SetBuild("cloud_coral") inst.AnimState:PlayAnimation("idle_full") MakeObstaclePhysics(inst, .6) inst.Transform:SetScale(1,1,1) inst.entity:AddMiniMapEntity() inst.MiniMapEntity:SetIcon("cloud_coral.tex") ------------------------------------------------------------------------ SetupNetwork(inst) ------------------------------------------------------------------------ inst:AddComponent("inspectable") inst:AddComponent("workable") inst.components.workable:SetWorkAction(ACTIONS.MINE) inst.components.workable:SetOnFinishCallback(onMined) inst.components.workable:SetWorkLeft(CFG.CLOUD_CORAL.WORK_TIME) inst.components.workable:SetOnWorkCallback(OnWork) inst:AddComponent("scaler") inst.components.scaler.OnApplyScale = applyscale inst:AddComponent("lootdropper") inst.components.lootdropper:AddRandomLoot("cloud_coral_fragment", CFG.CLOUD_CORAL.DROP_RATE) local start_scale = CFG.CLOUD_CORAL.START_SCALE inst.components.scaler:SetScale(start_scale) local dt = CFG.CLOUD_CORAL.GROW_RATE inst.growtask = inst:DoPeriodicTask(dt, grow, nil, dt) inst.OnLongUpdate = grow inst.OnLoad = onload inst.OnSave = onsave return inst end return Prefab ("common/inventory/cloud_coral", fn, assets, prefabs)
gpl-2.0
xdemolish/darkstar
scripts/zones/Konschtat_Highlands/npcs/qm1.lua
34
1376
----------------------------------- -- Area: Konschtat Highlands -- NPC: qm1 (???) -- Continues Quests: Past Perfect -- @pos -201 16 80 108 ----------------------------------- package.loaded["scripts/zones/Konschtat_Highlands/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Konschtat_Highlands/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local PastPerfect = player:getQuestStatus(BASTOK,PAST_PERFECT); if (PastPerfect == QUEST_ACCEPTED) then player:addKeyItem(0x6d); player:messageSpecial(KEYITEM_OBTAINED,0x6d); -- Tattered Mission Orders else player:messageSpecial(FIND_NOTHING); 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); end;
gpl-3.0
xdemolish/darkstar
scripts/zones/Upper_Jeuno/npcs/Migliorozz.lua
38
1033
----------------------------------- -- Area: Upper Jeuno -- NPC: Migliorozz -- Type: Standard NPC -- @zone: 244 -- @pos -37.760 -2.499 12.924 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x272a); 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
snegovick/luasocket
etc/forward.lua
43
2066
-- load our favourite library local dispatch = require("dispatch") local handler = dispatch.newhandler() -- make sure the user knows how to invoke us if #arg < 1 then print("Usage") print(" lua forward.lua <iport:ohost:oport> ...") os.exit(1) end -- function to move data from one socket to the other local function move(foo, bar) local live while 1 do local data, error, partial = foo:receive(2048) live = data or error == "timeout" data = data or partial local result, error = bar:send(data) if not live or not result then foo:close() bar:close() break end end end -- for each tunnel, start a new server for i, v in ipairs(arg) do -- capture forwarding parameters local _, _, iport, ohost, oport = string.find(v, "([^:]+):([^:]+):([^:]+)") assert(iport, "invalid arguments") -- create our server socket local server = assert(handler.tcp()) assert(server:setoption("reuseaddr", true)) assert(server:bind("*", iport)) assert(server:listen(32)) -- handler for the server object loops accepting new connections handler:start(function() while 1 do local client = assert(server:accept()) assert(client:settimeout(0)) -- for each new connection, start a new client handler handler:start(function() -- handler tries to connect to peer local peer = assert(handler.tcp()) assert(peer:settimeout(0)) assert(peer:connect(ohost, oport)) -- if sucessful, starts a new handler to send data from -- client to peer handler:start(function() move(client, peer) end) -- afte starting new handler, enter in loop sending data from -- peer to client move(peer, client) end) end end) end -- simply loop stepping the server while 1 do handler:step() end
mit
xdemolish/darkstar
scripts/globals/spells/poisonga_iii.lua
2
1216
----------------------------------------- -- Spell: Poisonga III ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local effect = EFFECT_POISON; local duration = 180; local pINT = caster:getStat(MOD_INT); local mINT = target:getStat(MOD_INT); local dINT = (pINT - mINT); local power = caster:getSkillLevel(ENFEEBLING_MAGIC_SKILL) / 10 + 1; if power > 25 then power = 25; end --local bonus = AffinityBonus(caster, spell:getElement()); Removed: affinity bonus is added in applyResistance local resist = applyResistanceEffect(caster,spell,target,dINT,ENFEEBLING_MAGIC_SKILL,0,effect); if(resist == 1 or resist == 0.5) then -- effect taken duration = duration * resist; if(target:addStatusEffect(effect,power,3,duration)) then spell:setMsg(236); else spell:setMsg(75); end else -- resist entirely. spell:setMsg(85); end return effect; end;
gpl-3.0
xdemolish/darkstar
scripts/zones/Waughroon_Shrine/npcs/Burning_Circle.lua
1
2214
----------------------------------- -- Area: Waughroon Shrine -- NPC: Burning Circle -- Waughroon Shrine Burning Circle -- @pos -345 104 -260 144 ------------------------------------- package.loaded["scripts/zones/Waughroon_Shrine/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/Waughroon_Shrine/TextIDs"); ---- 0: Rank 2 Final Mission for Bastok "The Emissary" and Sandy "Journey Abroad" ---- 1: Worms Turn ---- 2: Grimshell Shocktroopers ---- 3: On my Way ---- 4: Thief in Norg ---- 5: 3, 2, 1 ---- 6: Shattering Stars (RDM) ---- 7: Shattering Stars (THF) ---- 8: Shattering Stars (BST) ---- 9: Birds of the feather ---- 10: Crustacean Conundrum ---- 11: Grove Gardians ---- 12: The Hills are alive ---- 13: Royal Jelly ---- 14: The Final Bout ---- 15: Up in arms ---- 16: Copy Cat ---- 17: Operation Desert Swarm ---- 18: Prehistoric Pigeons ---- 19: The Palborough Project ---- 20: Shell Shocked ---- 21: Beyond infinity ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(TradeBCNM(player,player:getZone():getID(),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
chris5560/openwrt-luci
modules/luci-base/luasrc/model/firewall.lua
17
10704
-- Copyright 2009 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local type, pairs, ipairs, table, luci, math = type, pairs, ipairs, table, luci, math local tpl = require "luci.template.parser" local utl = require "luci.util" local uci = require "luci.model.uci" module "luci.model.firewall" local uci_r, uci_s function _valid_id(x) return (x and #x > 0 and x:match("^[a-zA-Z0-9_]+$")) end function _get(c, s, o) return uci_r:get(c, s, o) end function _set(c, s, o, v) if v ~= nil then if type(v) == "boolean" then v = v and "1" or "0" end return uci_r:set(c, s, o, v) else return uci_r:delete(c, s, o) end end function init(cursor) uci_r = cursor or uci_r or uci.cursor() uci_s = uci_r:substate() return _M end function save(self, ...) uci_r:save(...) uci_r:load(...) end function commit(self, ...) uci_r:commit(...) uci_r:load(...) end function get_defaults() return defaults() end function new_zone(self) local name = "newzone" local count = 1 while self:get_zone(name) do count = count + 1 name = "newzone%d" % count end return self:add_zone(name) end function add_zone(self, n) if _valid_id(n) and not self:get_zone(n) then local d = defaults() local z = uci_r:section("firewall", "zone", nil, { name = n, network = " ", input = d:input() or "DROP", forward = d:forward() or "DROP", output = d:output() or "DROP" }) return z and zone(z) end end function get_zone(self, n) if uci_r:get("firewall", n) == "zone" then return zone(n) else local z uci_r:foreach("firewall", "zone", function(s) if n and s.name == n then z = s['.name'] return false end end) return z and zone(z) end end function get_zones(self) local zones = { } local znl = { } uci_r:foreach("firewall", "zone", function(s) if s.name then znl[s.name] = zone(s['.name']) end end) local z for z in utl.kspairs(znl) do zones[#zones+1] = znl[z] end return zones end function get_zone_by_network(self, net) local z uci_r:foreach("firewall", "zone", function(s) if s.name and net then local n for n in utl.imatch(s.network or s.name) do if n == net then z = s['.name'] return false end end end end) return z and zone(z) end function del_zone(self, n) local r = false if uci_r:get("firewall", n) == "zone" then local z = uci_r:get("firewall", n, "name") r = uci_r:delete("firewall", n) n = z else uci_r:foreach("firewall", "zone", function(s) if n and s.name == n then r = uci_r:delete("firewall", s['.name']) return false end end) end if r then uci_r:foreach("firewall", "rule", function(s) if s.src == n or s.dest == n then uci_r:delete("firewall", s['.name']) end end) uci_r:foreach("firewall", "redirect", function(s) if s.src == n or s.dest == n then uci_r:delete("firewall", s['.name']) end end) uci_r:foreach("firewall", "forwarding", function(s) if s.src == n or s.dest == n then uci_r:delete("firewall", s['.name']) end end) end return r end function rename_zone(self, old, new) local r = false if _valid_id(new) and not self:get_zone(new) then uci_r:foreach("firewall", "zone", function(s) if old and s.name == old then if not s.network then uci_r:set("firewall", s['.name'], "network", old) end uci_r:set("firewall", s['.name'], "name", new) r = true return false end end) if r then uci_r:foreach("firewall", "rule", function(s) if s.src == old then uci_r:set("firewall", s['.name'], "src", new) end if s.dest == old then uci_r:set("firewall", s['.name'], "dest", new) end end) uci_r:foreach("firewall", "redirect", function(s) if s.src == old then uci_r:set("firewall", s['.name'], "src", new) end if s.dest == old then uci_r:set("firewall", s['.name'], "dest", new) end end) uci_r:foreach("firewall", "forwarding", function(s) if s.src == old then uci_r:set("firewall", s['.name'], "src", new) end if s.dest == old then uci_r:set("firewall", s['.name'], "dest", new) end end) end end return r end function del_network(self, net) local z if net then for _, z in ipairs(self:get_zones()) do z:del_network(net) end end end defaults = utl.class() function defaults.__init__(self) uci_r:foreach("firewall", "defaults", function(s) self.sid = s['.name'] return false end) self.sid = self.sid or uci_r:section("firewall", "defaults", nil, { }) end function defaults.get(self, opt) return _get("firewall", self.sid, opt) end function defaults.set(self, opt, val) return _set("firewall", self.sid, opt, val) end function defaults.syn_flood(self) return (self:get("syn_flood") == "1") end function defaults.drop_invalid(self) return (self:get("drop_invalid") == "1") end function defaults.input(self) return self:get("input") or "DROP" end function defaults.forward(self) return self:get("forward") or "DROP" end function defaults.output(self) return self:get("output") or "DROP" end zone = utl.class() function zone.__init__(self, z) if uci_r:get("firewall", z) == "zone" then self.sid = z self.data = uci_r:get_all("firewall", z) else uci_r:foreach("firewall", "zone", function(s) if s.name == z then self.sid = s['.name'] self.data = s return false end end) end end function zone.get(self, opt) return _get("firewall", self.sid, opt) end function zone.set(self, opt, val) return _set("firewall", self.sid, opt, val) end function zone.masq(self) return (self:get("masq") == "1") end function zone.name(self) return self:get("name") end function zone.network(self) return self:get("network") end function zone.input(self) return self:get("input") or defaults():input() or "DROP" end function zone.forward(self) return self:get("forward") or defaults():forward() or "DROP" end function zone.output(self) return self:get("output") or defaults():output() or "DROP" end function zone.add_network(self, net) if uci_r:get("network", net) == "interface" then local nets = { } local n for n in utl.imatch(self:get("network") or self:get("name")) do if n ~= net then nets[#nets+1] = n end end nets[#nets+1] = net _M:del_network(net) self:set("network", table.concat(nets, " ")) end end function zone.del_network(self, net) local nets = { } local n for n in utl.imatch(self:get("network") or self:get("name")) do if n ~= net then nets[#nets+1] = n end end if #nets > 0 then self:set("network", table.concat(nets, " ")) else self:set("network", " ") end end function zone.get_networks(self) local nets = { } local n for n in utl.imatch(self:get("network") or self:get("name")) do nets[#nets+1] = n end return nets end function zone.clear_networks(self) self:set("network", " ") end function zone.get_forwardings_by(self, what) local name = self:name() local forwards = { } uci_r:foreach("firewall", "forwarding", function(s) if s.src and s.dest and s[what] == name then forwards[#forwards+1] = forwarding(s['.name']) end end) return forwards end function zone.add_forwarding_to(self, dest) local exist, forward for _, forward in ipairs(self:get_forwardings_by('src')) do if forward:dest() == dest then exist = true break end end if not exist and dest ~= self:name() and _valid_id(dest) then local s = uci_r:section("firewall", "forwarding", nil, { src = self:name(), dest = dest }) return s and forwarding(s) end end function zone.add_forwarding_from(self, src) local exist, forward for _, forward in ipairs(self:get_forwardings_by('dest')) do if forward:src() == src then exist = true break end end if not exist and src ~= self:name() and _valid_id(src) then local s = uci_r:section("firewall", "forwarding", nil, { src = src, dest = self:name() }) return s and forwarding(s) end end function zone.del_forwardings_by(self, what) local name = self:name() uci_r:delete_all("firewall", "forwarding", function(s) return (s.src and s.dest and s[what] == name) end) end function zone.add_redirect(self, options) options = options or { } options.src = self:name() local s = uci_r:section("firewall", "redirect", nil, options) return s and redirect(s) end function zone.add_rule(self, options) options = options or { } options.src = self:name() local s = uci_r:section("firewall", "rule", nil, options) return s and rule(s) end function zone.get_color(self) if self and self:name() == "lan" then return "#90f090" elseif self and self:name() == "wan" then return "#f09090" elseif self then math.randomseed(tpl.hash(self:name())) local r = math.random(128) local g = math.random(128) local min = 0 local max = 128 if ( r + g ) < 128 then min = 128 - r - g else max = 255 - r - g end local b = min + math.floor( math.random() * ( max - min ) ) return "#%02x%02x%02x" % { 0xFF - r, 0xFF - g, 0xFF - b } else return "#eeeeee" end end forwarding = utl.class() function forwarding.__init__(self, f) self.sid = f end function forwarding.src(self) return uci_r:get("firewall", self.sid, "src") end function forwarding.dest(self) return uci_r:get("firewall", self.sid, "dest") end function forwarding.src_zone(self) local z = zone(self:src()) return z.sid and z end function forwarding.dest_zone(self) local z = zone(self:dest()) return z.sid and z end rule = utl.class() function rule.__init__(self, f) self.sid = f end function rule.get(self, opt) return _get("firewall", self.sid, opt) end function rule.set(self, opt, val) return _set("firewall", self.sid, opt, val) end function rule.src(self) return uci_r:get("firewall", self.sid, "src") end function rule.dest(self) return uci_r:get("firewall", self.sid, "dest") end function rule.src_zone(self) return zone(self:src()) end function rule.dest_zone(self) return zone(self:dest()) end redirect = utl.class() function redirect.__init__(self, f) self.sid = f end function redirect.get(self, opt) return _get("firewall", self.sid, opt) end function redirect.set(self, opt, val) return _set("firewall", self.sid, opt, val) end function redirect.src(self) return uci_r:get("firewall", self.sid, "src") end function redirect.dest(self) return uci_r:get("firewall", self.sid, "dest") end function redirect.src_zone(self) return zone(self:src()) end function redirect.dest_zone(self) return zone(self:dest()) end
apache-2.0
czfshine/UpAndAway
code/prefabs/vine.lua
2
3266
BindGlobal() local CFG = TheMod:GetConfig() local brain = require "brains/vinebrain" local assets= { Asset("ANIM", "anim/vine.zip"), Asset("SOUND", "sound/tentacle.fsb"), } local prefabs = CFG.VINE.PREFABS SetSharedLootTable( "vine", CFG.VINE.LOOT) local function OnHit(inst, attacker, damage) if attacker and attacker.prefab == bean_giant then damage = 0 end return damage end local function Retarget(inst) local newtarget = FindEntity(inst, 20, function(guy) return (guy:HasTag("character") or guy:HasTag("monster")) and not (inst.components.follower and inst.components.follower.leader == guy) and not guy:HasTag("vine") and not guy:HasTag("beanmonster") and not guy:HasTag("beanprotector") and not guy:HasTag("cloudneutral") and inst.components.combat:CanTarget(guy) end) return newtarget end local function KeepTarget(inst, target) if target and target:IsValid() and target.components.health and not target.components.health:IsDead() then return distsq(Vector3(target.Transform:GetWorldPosition() ), Vector3(inst.Transform:GetWorldPosition() ) ) < 30*30 end end local function fn(Sim) local inst = CreateEntity() local trans = inst.entity:AddTransform() local anim = inst.entity:AddAnimState() inst.entity:AddPhysics() inst.Physics:SetCylinder(0.50,2) trans:SetScale(.6, .7, 0.5) MakeGhostPhysics(inst, 1, .5) anim:SetBank("tentacle") anim:SetBuild("vine") anim:PlayAnimation("idle") inst.entity:AddSoundEmitter() inst:AddTag("monster") inst:AddTag("hostile") inst:AddTag("vine") inst:AddTag("cloudmonster") inst:AddTag("beanprotector") inst:AddTag("beanmonster") ------------------------------------------------------------------------ SetupNetwork(inst) ------------------------------------------------------------------------ inst:AddComponent("health") inst.components.health:SetMaxHealth(CFG.VINE.HEALTH) inst:AddComponent("combat") inst.components.combat:SetRange(CFG.VINE.RANGE) inst.components.combat:SetDefaultDamage(CFG.VINE.DAMAGE) inst.components.combat:SetAttackPeriod(CFG.VINE.ATTACK_PERIOD) inst.components.combat:SetRetargetFunction(1, Retarget) inst.components.combat:SetKeepTargetFunction(KeepTarget) inst.components.combat:SetOnHit(OnHit) MakeLargeFreezableCharacter(inst) inst:AddComponent("sanityaura") inst.components.sanityaura.aura = -(CFG.VINE.SANITY_AURA) inst:AddComponent("inspectable") inst:AddComponent("lootdropper") inst.components.lootdropper:SetChanceLootTable("vine") inst:ListenForEvent("attacked", OnAttacked) inst:AddComponent("locomotor") inst.components.locomotor.walkspeed = CFG.VINE.WALKSPEED inst.components.locomotor.runspeed = CFG.VINE.RUNSPEED inst.components.locomotor.directdrive = true inst:SetStateGraph("SGvine") inst:SetBrain(brain) inst:ListenForEvent("death", function(inst) inst:StopBrain() end) return inst end return Prefab("cloudrealm/monsters/vine", fn, assets, prefabs)
gpl-2.0
xdemolish/darkstar
scripts/globals/items/earth_wand.lua
16
1034
----------------------------------------- -- ID: 17076 -- Item: Earth Wand -- Additional Effect: Earth 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,20); local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(player, ELE_EARTH, target, dmg, params); dmg = dmg * applyResistanceAddEffect(player,target,ELE_EARTH,0); dmg = adjustForTarget(target,dmg,ELE_EARTH); dmg = finalMagicNonSpellAdjustments(player,target,ELE_EARTH,dmg); local message = 163; if (dmg < 0) then message = 167; end return SUBEFFECT_EARTH_DAMAGE,message,dmg; end end;
gpl-3.0
CNSRE/ABTestingGateway
lib/lua-resty-core/lib/resty/core/uri.lua
7
1524
-- Copyright (C) Yichun Zhang (agentzh) local ffi = require 'ffi' local ffi_string = ffi.string local C = ffi.C local ngx = ngx local type = type local tostring = tostring local base = require "resty.core.base" local get_string_buf = base.get_string_buf ffi.cdef[[ size_t ngx_http_lua_ffi_uri_escaped_length(const unsigned char *src, size_t len); void ngx_http_lua_ffi_escape_uri(const unsigned char *src, size_t len, unsigned char *dst); size_t ngx_http_lua_ffi_unescape_uri(const unsigned char *src, size_t len, unsigned char *dst); ]] ngx.escape_uri = function (s) if type(s) ~= 'string' then if not s then s = '' else s = tostring(s) end end local slen = #s local dlen = C.ngx_http_lua_ffi_uri_escaped_length(s, slen) -- print("dlen: ", tonumber(dlen)) if dlen == slen then return s end local dst = get_string_buf(dlen) C.ngx_http_lua_ffi_escape_uri(s, slen, dst) return ffi_string(dst, dlen) end ngx.unescape_uri = function (s) if type(s) ~= 'string' then if not s then s = '' else s = tostring(s) end end local slen = #s local dlen = slen local dst = get_string_buf(dlen) dlen = C.ngx_http_lua_ffi_unescape_uri(s, slen, dst) return ffi_string(dst, dlen) end return { version = base.version, }
mit
henrythasler/nodemcu
rc-car/scripts/status.lua
1
2459
return function(sck, request) local majorVer, minorVer, devVer, chipid, flashid, flashsize, flashmode, flashspeed = node.info() local remaining, used, total = file.fsinfo() local _, reset_reason = node.bootreason() local total_allocated, estimated_used = node.egc.meminfo() local addr, netmask, gateway = (cfg.wifi.mode == wifi.STATION) and wifi.sta.getip() or wifi.ap.getip() local data = { timestamp = rtctime.get(), node = { majorVer = majorVer, minorVer = minorVer, devVer = devVer, chipid = chipid, flashid = flashid, flashsize = flashsize, flashmode = flashmode, flashspeed = flashspeed, reset_reason = reset_reason, cpufreq = node.getcpufreq(), }, mem = { total_allocated = total_allocated, estimated_used = estimated_used, }, net = { hostname = (cfg.wifi.mode == wifi.STATION) and wifi.sta.gethostname() or nil, channel = wifi.getchannel(), address = addr, netmask = netmask, gateway = gateway, mac = (cfg.wifi.mode == wifi.STATION) and wifi.sta.getmac() or wifi.ap.getmac(), rssi = (cfg.wifi.mode == wifi.STATION) and wifi.sta.getrssi() or nil, ssid = (cfg.wifi.mode == wifi.STATION) and wifi.sta.getconfig() or wifi.ap.getconfig(), clients = (cfg.wifi.mode == wifi.SOFTAP) and wifi.ap.getclient() or nil, }, fs = { remaining = remaining, used = used, total = total, }, files = file.list(), } -- use as stream-json-encoder to chunk large content local encoder = sjson.encoder(data) -- callback upon completion of current response local function on_sent(local_conn) local chunk = encoder:read(256) -- send 256-Byte chunks if chunk then -- send chunk to client and wait for next callback local_conn:send(chunk) else -- all done; close socket and release semaphore when done local_conn:close() maxThreads = maxThreads + 1 end end -- register callback sck:on("sent", on_sent) -- send http-header ("200 OK") with matching MIME-Type; on_sent is called upon completion dofile("webserver-header.lc")(sck, 200, "json", false) end
mit
czfshine/UpAndAway
wicker/plugins/addworldgenparameterspostconstruct.lua
6
1101
local Lambda = wickerrequire "paradigms.functional" local FunctionQueue = wickerrequire "gadgets.functionqueue" local postconstructs = FunctionQueue() local function AddParamsPostConstruct(fn) table.insert(postconstructs, fn) end local function PatchJsonEncode(encode) local type = type local depth = 0 local function process_encoded_data(...) depth = depth - 1 return ... end return function(data, ...) if depth == 0 and type(data) == "table" and data.level_type ~= nil then postconstructs(data, ...) end depth = depth + 1 return process_encoded_data(encode(data, ...)) end end local function PatchWGenScreenCtor(ctor) return function(self, ...) require "json" local old_encode = _G.json.encode _G.json.encode = PatchJsonEncode(old_encode) ctor(self, ...) _G.json.encode = old_encode end end if not IsWorldgen() then local WGenScreen = require "screens/worldgenscreen" WGenScreen._ctor = PatchWGenScreenCtor(WGenScreen._ctor) else AddParamsPostConstruct = Lambda.Nil end TheMod:EmbedHook("AddWorldgenParametersPostConstruct", AddParamsPostConstruct)
gpl-2.0
lailongwei/llbc
tools/premake/premake5.lua
1
21190
-- @file premake5.lua -- @author Longwei Lai<lailongwei@126.com> -- @brief The llbc library(included all wrap libraries) premake script define. -- ######################################################################### -- Global compile settings -- flags. IS_WINDOWS = string.match(_ACTION, 'vs') ~= nil -- solution/projects path SLN_PATH = "../../" CORELIB_PATH = SLN_PATH .. "/llbc" TESTSUITE_PATH = SLN_PATH .. "/testsuite" WRAPS_PATH = SLN_PATH .. "/wrap" PY_WRAP_PATH = WRAPS_PATH .. "/pyllbc" LU_WRAP_PATH = WRAPS_PATH .. "/lullbc" CS_WRAP_PATH = WRAPS_PATH .. "/csllbc" -- Capture shell cmd's output local 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 -- PY target local PY if IS_WINDOWS then PY = "$(ProjectDir)../../tools/py.exe" else local output = os_capture("python --version") if output:find("command not found") then error("python command not found") elseif output:find("Python 3") then if os_capture("which python2"):len() == 0 then error("Python3 is not yet supported, please install python2 and make sure python2 can be use") end PY = "python2" else PY = "python" end end -- All libraries output directory LLBC_OUTPUT_BASE_DIR = SLN_PATH .. "/output/" .. _ACTION if IS_WINDOWS then LLBC_OUTPUT_DIR = LLBC_OUTPUT_BASE_DIR .. "/$(Configuration)" else LLBC_OUTPUT_DIR = LLBC_OUTPUT_BASE_DIR .. "/$(config)" end -- ######################################################################### workspace ("llbc_" .. _ACTION) -- location define location (SLN_PATH .. "/build/" .. _ACTION) -- target directory define targetdir (LLBC_OUTPUT_DIR) -- start project startproject("testsuite") -- configurations configurations { "release32", "debug32", "release64", "debug64" } -- architecture filter { "configurations:*32" } architecture "x86" filter {} filter { "configurations:*64" } architecture "x86_64" filter {} -- defines filter { "configurations:debug*" } defines { "DEBUG" } filter {} -- enable symbols symbols "On" -- set optimize options filter { "configurations:debug*" } runtime "Debug" optimize "Debug" filter {} filter { "configurations:release*" } optimize "On" filter {} -- warnings setting filter { "system:windows", "language:c++" } disablewarnings { "4091", "4068", "4251", } filter {} filter { "system:not windows", "language:c++" } buildoptions { "-Wall -Werror", "-Wno-strict-aliasing", } filter {} -- set debug target suffix filter { "configurations:debug*" } targetsuffix "_debug" filter {} -- enable multithread compile(only avabilable on windows) filter { "system:windows" } flags { "MultiProcessorCompile", "NoMinimalRebuild" } filter {} -- characterset architecture filter { "language:c++" } characterset "MBCS" filter {} -- enable obtaining backtraces from within a program filter { "system:not windows", "language:c++" } linkoptions { "-rdynamic" } filter {} -- **************************************************************************** -- llbc core library compile setting project "llbc" -- language, kind language "c++" kind "SharedLib" -- files files { SLN_PATH .. "/CHANGELOG", SLN_PATH .. "/README.md", CORELIB_PATH .. "/**.h", CORELIB_PATH .. "/**.c", CORELIB_PATH .. "/**.cpp", SLN_PATH .. "/tools/premake/*.lua", } filter { "system:macosx" } files { CORELIB_PATH .. "/**.mm", } filter {} -- includedirs includedirs { SLN_PATH, CORELIB_PATH .. "/include", } -- target prefix targetprefix "lib" -- links filter { "system:linux" } links { "uuid", "pthread", } filter { "system:windows" } links { "ws2_32", "Mswsock", "DbgHelp", } filter { "system:macosx" } links { "iconv", } filter {} -- Enable c++11 support. filter { "system:not windows" } buildoptions { "-std=c++11", } filter {} -- Default hidden symbols. filter { "system:not windows" } buildoptions { "-fvisibility=hidden", } filter {} -- **************************************************************************** -- core library testsuite compile setting project "testsuite" -- language, kind language "c++" kind "ConsoleApp" -- dependents dependson { "llbc", } -- files files { TESTSUITE_PATH .. "/**.h", TESTSUITE_PATH .. "/**.cpp", } -- includedirswrap\csllbc\csharp\script_tools includedirs { CORELIB_PATH .. "/include", TESTSUITE_PATH, } -- links libdirs { LLBC_OUTPUT_DIR } filter { "system:linux" } links { "dl", "pthread", } filter {} filter { "system:not windows", "configurations:debug*" } links { "llbc_debug", } filter {} filter { "system:not windows", "configurations:release*" } links { "llbc", } filter {} filter { "system:windows" } links { "ws2_32", } filter {} filter { "system:windows", "configurations:debug*" } links { "libllbc_debug", } filter {} filter { "system:windows", "configurations:release*" } links { "libllbc", } filter {} -- warnings -- filter { "system:not windows" } -- disablewarnings { -- "invalid-source-encoding", -- } -- filter {} -- Enable c++11 support. filter { "system:not windows" } buildoptions { "-std=c++11", } filter {} group "wrap" -- **************************************************************************** -- python wrap library(pyllbc) compile setting -- import pylib_setting package.path = package.path .. ";" .. "../../wrap/pyllbc/?.lua" local PYLIB_SETTING = require "pylib_setting" local PYLIB_PY_VER = PYLIB_SETTING.py_ver or 2 if PYLIB_PY_VER == 2 then elseif PYLIB_PY_VER == 3 then else error('Please set the python version number correctly(in wrap/pyllbc/pylib_setting.lua)!') end local PYLIB_INCL_PATH = (PYLIB_SETTING.py_path[1] ~= nil and PYLIB_SETTING.py_path[1] ~= "") and PYLIB_SETTING.py_path[1] or "" local PYLIB_LIB_DIR = (PYLIB_SETTING.py_path[2] ~= nil and PYLIB_SETTING.py_path[2] ~= "") and PYLIB_SETTING.py_path[2] or "" local PYLIB_LIB_NAME = (PYLIB_SETTING.py_path[3] ~= nil and PYLIB_SETTING.py_path[3] ~= "") and PYLIB_SETTING.py_path[3] or "" project "pyllbc" -- language, kind language "c++" kind "SharedLib" -- dependents dependson { "llbc", } -- files files { PY_WRAP_PATH .. "/include/**.h", PY_WRAP_PATH .. "/src/**.h", PY_WRAP_PATH .. "/src/**.cpp", PY_WRAP_PATH .. "/script/**.py", PY_WRAP_PATH .. "/testsuite/**.py", } if PYLIB_PY_VER == 2 then files { PY_WRAP_PATH .. "/Python2.7.8/**.h" , } elseif PYLIB_PY_VER == 3 then files { PY_WRAP_PATH .. "/Python3.8.5/**.h", } end -- includedirs includedirs { CORELIB_PATH .. "/include", PY_WRAP_PATH .. "/include", PY_WRAP_PATH, } if string.len(PYLIB_INCL_PATH) > 0 then includedirs { PYLIB_INCL_PATH } else -- if not specific python include path, windows platform will use specific version python, other platforms will auto detect. filter { "system:windows" } if PYLIB_PY_VER == 2 then includedirs { PY_WRAP_PATH .. "/Python2.7.8/Include" } elseif PYLIB_PY_VER == 3 then includedirs { PY_WRAP_PATH .. "/Python3.8.5/Include" } end filter {} filter { "system:not windows" } if PYLIB_PY_VER == 2 then includedirs { "/usr/include/python2.7" } elseif PYLIB_PY_VER == 3 then includedirs { "/usr/include/python3.8" } end filter {} end -- define HAVE_ROUND(only on vs2013, vs2015, vs2017 and later version visual studio IDEs). filter { "action:vs20*" } defines { "HAVE_ROUND" } filter {} -- prebuild commands prebuildcommands { PY .. " ../../tools/building_script/py_prebuild.py pyllbc", } -- target name, target prefix, extension targetname "llbc" targetprefix "" filter { "system:windows" } targetextension ".pyd" filter {} -- links -- link llbc library libdirs { LLBC_OUTPUT_DIR } filter { "system:windows", "configurations:debug*" } links { "libllbc_debug" } filter {} filter { "system:windows", "configurations:release*" } links { "libllbc" } filter {} filter { "system:not windows", "configurations:debug*" } links { "llbc_debug" } filter {} filter { "system:not windows", "configurations:release*" } links { "llbc" } filter {} -- link python library if string.len(PYLIB_LIB_DIR) > 0 then libdirs { PYLIB_LIB_DIR } else filter { "system:windows", "architecture:x86" } if PYLIB_PY_VER == 2 then libdirs { PY_WRAP_PATH .. "/Python2.7.8/Libs/Win/32" } elseif PYLIB_PY_VER == 3 then libdirs { PY_WRAP_PATH .. "/Python3.8.5/Libs/Win/32" } end filter {} filter { "system:windows", "architecture:x64" } if PYLIB_PY_VER == 2 then libdirs { PY_WRAP_PATH .. "/Python2.7.8/Libs/Win/64" } elseif PYLIB_PY_VER == 3 then libdirs { PY_WRAP_PATH .. "/Python3.8.5/Libs/Win/64" } end filter {} end if string.len(PYLIB_LIB_NAME) > 0 then links { PYLIB_LIB_NAME } else -- in windows platform, python library use the python library file in the repo filter { "system:windows", "configurations:debug*" } if PYLIB_PY_VER == 2 then links { "python27_d" } elseif PYLIB_PY_VER == 3 then links { "python38_d" } end filter {} filter { "system:windows", "configurations:release*" } if PYLIB_PY_VER == 2 then links { "python27" } elseif PYLIB_PY_VER == 3 then links { "python38" } end filter {} -- in non-windows platform, python library default named: python2.7 filter { "system:not windows" } if PYLIB_PY_VER == 2 then links { "python2.7" } elseif PYLIB_PY_VER == 3 then links { "python3.8" } end filter {} end -- Enable c++11 support. filter { "system:not windows" } buildoptions { "-std=c++11", "-Wno-deprecated-register", } filter {} -- Default hidden symbols. filter { "system:not windows" } buildoptions { "-fvisibility=hidden", } filter {} group "wrap/csllbc" -- **************************************************************************** -- csharp wrap library(csllbc) native library compile setting project "csllbc_native" -- language, kind language "c++" kind "SharedLib" -- dependents dependson { "llbc", } -- library suffix targetprefix "lib" -- files files { CS_WRAP_PATH .. "/native/**.h", CS_WRAP_PATH .. "/native/**.cpp", } -- includedirs includedirs { CORELIB_PATH .. "/include", CS_WRAP_PATH .. "/native/include", } -- links libdirs { LLBC_OUTPUT_DIR, } filter { "system:windows", "configurations:debug*" } links { "libllbc_debug", } filter {} filter { "system:windows", "configurations:release*" } links { "libllbc", } filter {} filter { "system:not windows", "configurations:debug*" } links { "llbc_debug", } filter {} filter { "system:not windows", "configurations:release*" } links { "llbc", } filter {} -- disable warnings filter { "system:not windows" } disablewarnings { "attributes" } filter {} -- Enable c++11 support. filter { "system:not windows" } buildoptions { "-std=c++11", } filter {} -- Default hidden symbols. filter { "system:not windows" } buildoptions { "-fvisibility=hidden", } filter {} -- **************************************************************************** -- csharp wrap library(csllbc) compile setting project "csllbc" -- language, kind kind "SharedLib" language "c#" -- files files { CS_WRAP_PATH .. "/csharp/**.cs", } -- dependents dependson { "llbc", "csllbc_native", } -- set unsafe flag clr "Unsafe" -- prebuild commands filter { "system:windows" } prebuildcommands { PY .. ' -c "import os;print(os.getcwd())"', PY .. " ../../../wrap/csllbc/csharp/script_tools/gen_native_code.py", PY .. " ../../../wrap/csllbc/csharp/script_tools/gen_errno_code.py", } filter {} filter { "system:not windows" } prebuildcommands { PY .. ' -c "import os;print(os.getcwd())"', PY .. " ../../wrap/csllbc/csharp/script_tools/gen_native_code.py", PY .. " ../../wrap/csllbc/csharp/script_tools/gen_errno_code.py", } filter {} -- postbuild commands filter { "system:not windows" } postbuildcommands { PY .. " ../../wrap/csllbc/csharp/script_tools/gen_dll_cfg.py ../../output/" .. _ACTION, } filter {} -- defines filter { "system:linux" } defines { "CSLLBC_TARGET_PLATFORM_LINUX", } filter {} filter { "system:windows" } defines { "CSLLBC_TARGET_PLATFORM_WIN32", } filter {} -- links filter {} links { "System", "System.Net", "System.Core", } -- **************************************************************************** -- csharp wrap library(csllbc) testsuite compile setting project "csllbc_testsuite" -- language, kind kind "ConsoleApp" language "c#" -- dependents dependson { "llbc", "csllbc_native", "csllbc", } -- files files { CS_WRAP_PATH .. "/testsuite/**.cs", } -- links links { "System", "System.Net", "System.Core", "csllbc", } group "wrap/lullbc" -- **************************************************************************** -- luasrc library(liblua) compile setting local LUA_SRC_PATH = "../../wrap/lullbc/lua" project "lullbc_lualib" -- language, kind language "c++" kind "SharedLib" -- files files { LUA_SRC_PATH .. "/*.h", LUA_SRC_PATH .. "/*.c", } removefiles { LUA_SRC_PATH .. "/lua.c", LUA_SRC_PATH .. "/luac.c", LUA_SRC_PATH .. "/onelua.c", } -- defines defines { "LUA_COMPAT_5_1", "LUA_COMPAT_5_2", "LUA_COMPAT_5_3", } filter { "system:windows" } defines { "LUA_BUILD_AS_DLL" } filter {} filter { "system:not windows" } defines { "LUA_USE_DLOPEN" } filter {} -- links filter { "system:not windows" } links { "dl" } filter {} -- target name, target prefix targetname "lua" targetprefix "lib" -- lua executable compile setting local LUA_SRC_PATH = LU_WRAP_PATH .. "/lua" project "lullbc_luaexec" -- language, kind language "c++" kind "ConsoleApp" -- files files { LUA_SRC_PATH .. "/*.h", LUA_SRC_PATH .. "/lua.c", } -- defines defines { "LUA_COMPAT_5_1", "LUA_COMPAT_5_2", "LUA_COMPAT_5_3", } -- dependents dependson { "lullbc_lualib" } -- links libdirs { LLBC_OUTPUT_DIR, } filter { "system:not windows" } links { "dl" } filter {} filter { "configurations:debug*", "system:windows" } links { "liblua_debug" } filter {} filter { "configurations:release*", "system:windows" } links { "liblua" } filter {} filter { "configurations:debug*", "system:not windows" } links { "lua_debug" } filter {} filter { "configurations:release*", "system:not windows" } links { "lua" } filter {} -- target name, target prefix targetname "lua" -- lua wrap library(lullbc) compile setting -- import lualib_setting package.path = package.path .. ";" .. "../../wrap/lullbc/?.lua" local LUALIB_SETTING = require "lualib_setting" local LUALIB_INCL_PATH = (LUALIB_SETTING.lua_path[1] ~= nil and LUALIB_SETTING.lua_path[1] ~= "") and LUALIB_SETTING.lua_path[1] or LUA_SRC_PATH local LUALIB_LIB_DIR = (LUALIB_SETTING.lua_path[2] ~= nil and LUALIB_SETTING.lua_path[2] ~= "") and LUALIB_SETTING.lua_path[2] or LLBC_OUTPUT_DIR project "lullbc" -- language, kind language "c++" kind "SharedLib" -- dependents dependson { "llbc", "lullbc_lualib", "lullbc_luaexec", } -- files files { LU_WRAP_PATH .. "/lua/*.h", LU_WRAP_PATH .. "/include/**.h", LU_WRAP_PATH .. "/src/**.h", LU_WRAP_PATH .. "/src/**.c", LU_WRAP_PATH .. "/src/**.cpp", LU_WRAP_PATH .. "/script/**.lua", LU_WRAP_PATH .. "/testsuite/**.lua", LU_WRAP_PATH .. "/testsuite/**.cfg", } -- define targetextension filter { "system:macosx" } targetextension ".so" filter {} -- includedirs includedirs { LUALIB_INCL_PATH, CORELIB_PATH .. "/include", LU_WRAP_PATH .. "/include", LU_WRAP_PATH, } -- defines filter { "system:windows", "action:vs2013 and vs2015 and vs2017" } defines { "HAVE_ROUND", } filter {} -- prebuild commands filter { "configurations:debug*" } prebuildcommands { PY .. " ../../tools/building_script/lu_prebuild.py lullbc debug", } postbuildcommands { PY .. string.format(' ../../tools/building_script/lu_postbuild.py %s %s "%s"', "lullbc", "debug", LLBC_OUTPUT_DIR), } filter {} filter { "configurations:release*" } prebuildcommands { PY .. " ../../tools/building_script/lu_prebuild.py lullbc release", } postbuildcommands { PY .. string.format(' ../../tools/building_script/lu_postbuild.py %s %s "%s"', "lullbc", "release", LLBC_OUTPUT_DIR), } filter {} -- target name, target prefix, extension targetname "_lullbc" targetprefix "" -- links libdirs { LLBC_OUTPUT_DIR, LUALIB_LIB_DIR, } filter { "configurations:debug*", "system:windows" } links { "libllbc_debug", (LUALIB_SETTING.lua_path[3] ~= nil and LUALIB_SETTING.lua_path[3] ~= "") and LUALIB_SETTING.lua_path[3] or "liblua_debug", } filter {} filter { "configurations:debug*", "system:not windows" } links { "llbc_debug", (LUALIB_SETTING.lua_path[3] ~= nil and LUALIB_SETTING.lua_path[3] ~= "") and LUALIB_SETTING.lua_path[3] or "lua_debug", } filter {} filter { "configurations:release*", "system:windows" } links { "libllbc", (LUALIB_SETTING.lua_path[3] ~= nil and LUALIB_SETTING.lua_path[3] ~= "") and LUALIB_SETTING.lua_path[3] or "liblua", } filter {} filter { "configurations:release*", "system:not windows" } links { "llbc", (LUALIB_SETTING.lua_path[3] ~= nil and LUALIB_SETTING.lua_path[3] ~= "") and LUALIB_SETTING.lua_path[3] or "lua", } filter {} -- Enable c++11 support. filter { "system:not windows" } buildoptions { "-std=c++11", } filter {} -- Default hidden symbols. filter { "system:not windows" } buildoptions { "-fvisibility=hidden", } filter {} -- linkoptions filter { "system:macosx" } linkoptions { "-undefined dynamic_lookup", } filter {} group ""
mit
xdemolish/darkstar
scripts/globals/spells/bluemagic/magic_hammer.lua
3
1216
----------------------------------------- -- -- Magic Hammer -- ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage local multi = 1.5; if(caster:hasStatusEffect(EFFECT_AZURE_LORE)) then multi = multi + 0.50; end params.multiplier = multi; params.tMultiplier = 1.0; params.duppercap = 35; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.39; params.chr_wsc = 0.0; damage = BlueMagicalSpell(caster, target, spell, params, MND_BASED); damage = BlueFinalAdjustments(caster, target, spell, damage, params); caster:addMP(dmg); if(target:isUndead()) then spell:setMsg(75); -- No effect return damage; end return dmg; end;
gpl-3.0
simonswine/chdkptp
lua/gui_user.lua
1
2876
--[[ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ]] --[[ module for user tab in gui a place for user defined stuff ]] local m={} function m.get_container_title() return "User" end function m.init() m.dest = "" -- destination path for download, default is chdkptp dir return end function m.get_container() local usertab = iup.vbox{ margin="4x4", m.remote_capture_ui(), } return usertab end --[[ remote capture function as gui function * Destination - dialog for file destination, default is chdkptp dir * JPG Remote Shoot - shoot and save a JPG file in the destination (only available for cameras that support filewrite_task) * DNG Remote Shoot - shoot and save a DNG file in the destination ]] function m.remote_capture_ui() local gui_frame = iup.frame{ title="Remote Capture", iup.vbox{ gap="10", iup.button{ title="Destination", size="75x15", fgcolor="0 0 255", action=function(self) local dlg=iup.filedlg{ dialogtype = "DIR", title = "Destination", } dlg:popup(iup_centerparent, iup_centerparent) if dlg.status == "0" then m.dest = dlg.value gui.infomsg("download destination %s\n", m.dest) end end, }, iup.button{ title="JPG Remote Shoot", size="75x15", fgcolor="255 0 0", tip="Does not work for all cameras!", action=function(self) local cmd="rs "..m.dest add_status(cli:execute(cmd)) end, }, iup.button{ title="DNG Remote Shoot", size="75x15", fgcolor="255 0 0", action=function(self) local cmd="rs "..m.dest.." -dng" add_status(cli:execute(cmd)) end, }, }, } return gui_frame end return m
gpl-2.0
nalidixic/OpenRA
mods/cnc/maps/nod06a/nod06a.lua
19
7647
NodStartUnitsRight = { 'ltnk', 'bike', 'e1', 'e1', 'e3', 'e3' } NodStartUnitsLeft = { 'ltnk', 'ltnk', 'bggy', 'e1', 'e1', 'e1', 'e1', 'e3', 'e3', 'e3', 'e3' } Chn1Units = { 'e1', 'e1', 'e1', 'e1', 'e1' } Chn2Units = { 'e2', 'e2', 'e2', 'e2', 'e2' } Obj2Units = { 'ltnk', 'bike', 'e1', 'e1', 'e1' } Chn3CellTriggerActivator = { CPos.New(49,58), CPos.New(48,58), CPos.New(49,57), CPos.New(48,57), CPos.New(49,56), CPos.New(48,56), CPos.New(49,55), CPos.New(48,55) } DzneCellTriggerActivator = { CPos.New(61,45), CPos.New(60,45), CPos.New(59,45), CPos.New(58,45), CPos.New(57,45), CPos.New(61,44), CPos.New(60,44), CPos.New(59,44), CPos.New(58,44), CPos.New(57,44), CPos.New(61,43), CPos.New(60,43), CPos.New(58,43), CPos.New(57,43), CPos.New(61,42), CPos.New(60,42), CPos.New(59,42), CPos.New(58,42), CPos.New(57,42), CPos.New(61,41), CPos.New(60,41), CPos.New(59,41), CPos.New(58,41), CPos.New(57,41) } Win1CellTriggerActivator = { CPos.New(59,43) } Win2CellTriggerActivator = { CPos.New(54,58), CPos.New(53,58), CPos.New(52,58), CPos.New(54,57), CPos.New(53,57), CPos.New(52,57), CPos.New(54,56), CPos.New(53,56), CPos.New(52,56), CPos.New(54,55), CPos.New(53,55), CPos.New(52,55) } Grd2ActorTriggerActivator = { Guard1, Guard2, Guard3 } Atk1ActorTriggerActivator = { Atk1Activator1, Atk1Activator2 } Atk2ActorTriggerActivator = { Atk2Activator1, Atk2Activator2 } Chn1ActorTriggerActivator = { Chn1Activator1, Chn1Activator2, Chn1Activator3, Chn1Activator4, Chn1Activator5 } Chn2ActorTriggerActivator = { Chn2Activator1, Chn2Activator2, Chn2Activator3 } Obj2ActorTriggerActivator = { Chn1Activator1, Chn1Activator2, Chn1Activator3, Chn1Activator4, Chn1Activator5, Chn2Activator1, Chn2Activator2, Chn2Activator3, Atk3Activator } Chn1Waypoints = { ChnEntry.Location, waypoint5.Location } Chn2Waypoints = { ChnEntry.Location, waypoint6.Location } Gdi3Waypoints = { waypoint1, waypoint3, waypoint7, waypoint8, waypoint9 } Gdi4Waypoints = { waypoint4, waypoint10, waypoint9, waypoint11, waypoint9, waypoint10 } Gdi5Waypoints = { waypoint1, waypoint4 } Gdi6Waypoints = { waypoint2, waypoints3 } Grd1TriggerFunctionTime = DateTime.Seconds(3) Grd1TriggerFunction = function() MyActors = Utils.Take(2, GDI.GetActorsByType('mtnk')) Utils.Do(MyActors, function(actor) MovementAndHunt(actor, Gdi3Waypoints) end) end Grd2TriggerFunction = function() if not Grd2Switch then for type, count in pairs({ ['e1'] = 2, ['e2'] = 1, ['jeep'] = 1 }) do MyActors = Utils.Take(count, GDI.GetActorsByType(type)) Utils.Do(MyActors, function(actor) MovementAndHunt(actor, Gdi4Waypoints) end) end Grd2Swicth = true end end Atk1TriggerFunction = function() if not Atk1Switch then for type, count in pairs({ ['e1'] = 3, ['e2'] = 3, ['jeep'] = 1 }) do MyActors = Utils.Take(count, GDI.GetActorsByType(type)) Utils.Do(MyActors, function(actor) MovementAndHunt(actor, Gdi5Waypoints) end) end Atk1Switch = true end end Atk2TriggerFunction = function() if not Atk2Switch then for type, count in pairs({ ['mtnk'] = 1, ['jeep'] = 1 }) do MyActors = Utils.Take(count, GDI.GetActorsByType(type)) Utils.Do(MyActors, function(actor) MovementAndHunt(actor, Gdi6Waypoints) end) end Atk2Switch = true end end Atk3TriggerFunction = function() if not Atk3Switch then Atk3Switch = true if not Radar.IsDead then local targets = Nod.GetGroundAttackers() local target = targets[DateTime.GameTime % #targets + 1].CenterPosition if target then Radar.SendAirstrike(target, false, Facing.NorthEast + 4) end end end end Chn1TriggerFunction = function() local cargo = Reinforcements.ReinforceWithTransport(GDI, 'tran', Chn1Units, Chn1Waypoints, { waypoint14.Location })[2] Utils.Do(cargo, function(actor) IdleHunt(actor) end) end Chn2TriggerFunction = function() local cargo = Reinforcements.ReinforceWithTransport(GDI, 'tran', Chn2Units, Chn2Waypoints, { waypoint14.Location })[2] Utils.Do(cargo, function(actor) IdleHunt(actor) end) end Obj2TriggerFunction = function() Nod.MarkCompletedObjective(NodObjective2) Reinforcements.Reinforce(Nod, Obj2Units, { Obj2UnitsEntry.Location, waypoint13.Location }, 15) end MovementAndHunt = function(unit, waypoints) if unit ~= nil then Utils.Do(waypoints, function(waypoint) unit.AttackMove(waypoint.Location) end) IdleHunt(unit) end end InsertNodUnits = function() Camera.Position = UnitsRallyRight.CenterPosition Media.PlaySpeechNotification(Nod, "Reinforce") Reinforcements.Reinforce(Nod, NodStartUnitsLeft, { UnitsEntryLeft.Location, UnitsRallyLeft.Location }, 15) Reinforcements.Reinforce(Nod, NodStartUnitsRight, { UnitsEntryRight.Location, UnitsRallyRight.Location }, 15) end WorldLoaded = function() GDI = Player.GetPlayer("GDI") Nod = Player.GetPlayer("Nod") Trigger.OnObjectiveAdded(Nod, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) Trigger.OnObjectiveCompleted(Nod, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(Nod, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerWon(Nod, function() Media.PlaySpeechNotification(Nod, "Win") end) Trigger.OnPlayerLost(Nod, function() Media.PlaySpeechNotification(Nod, "Lose") end) NodObjective1 = Nod.AddPrimaryObjective("Steal the GDI nuclear detonator.") NodObjective2 = Nod.AddSecondaryObjective("Destroy the houses of the GDI supporters\nin the village.") GDIObjective = GDI.AddPrimaryObjective("Stop the Nod taskforce from escaping with the detonator.") InsertNodUnits() Trigger.AfterDelay(Grd1TriggerFunctionTime, Grd1TriggerFunction) Utils.Do(Grd2ActorTriggerActivator, function(actor) Trigger.OnDiscovered(actor, Grd2TriggerFunction) end) OnAnyDamaged(Atk1ActorTriggerActivator, Atk1TriggerFunction) OnAnyDamaged(Atk2ActorTriggerActivator, Atk2TriggerFunction) Trigger.OnDamaged(Atk3Activator, Atk3TriggerFunction) Trigger.OnAllKilled(Chn1ActorTriggerActivator, Chn1TriggerFunction) Trigger.OnAllKilled(Chn2ActorTriggerActivator, Chn2TriggerFunction) Trigger.OnEnteredFootprint(Chn3CellTriggerActivator, function(a, id) if a.Owner == Nod then Media.PlaySpeechNotification(Nod, "Reinforce") Reinforcements.ReinforceWithTransport(Nod, 'tran', nil, { ChnEntry.Location, waypoint17.Location }, nil, nil, nil) Trigger.RemoveFootprintTrigger(id) end end) Trigger.OnEnteredFootprint(DzneCellTriggerActivator, function(a, id) if a.Owner == Nod then Actor.Create('flare', true, { Owner = Nod, Location = waypoint17.Location }) Trigger.RemoveFootprintTrigger(id) end end) Trigger.OnAllRemovedFromWorld(Obj2ActorTriggerActivator, Obj2TriggerFunction) Trigger.OnEnteredFootprint(Win1CellTriggerActivator, function(a, id) if a.Owner == Nod then NodObjective3 = Nod.AddPrimaryObjective("Move to the evacuation point.") Nod.MarkCompletedObjective(NodObjective1) Trigger.RemoveFootprintTrigger(id) end end) Trigger.OnEnteredFootprint(Win2CellTriggerActivator, function(a, id) if a.Owner == Nod and NodObjective3 then Nod.MarkCompletedObjective(NodObjective3) Trigger.RemoveFootprintTrigger(id) end end) end Tick = function() if DateTime.GameTime > 2 and Nod.HasNoRequiredUnits() then GDI.MarkCompletedObjective(GDIObjective) end end IdleHunt = function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end OnAnyDamaged = function(actors, func) Utils.Do(actors, function(actor) Trigger.OnDamaged(actor, func) end) end
gpl-3.0
jarvissso3/jokerblue
tools.lua
6
23182
--Begin Tools.lua :) local SUDO = 157059515 -- put Your ID here! <=== local function index_function(user_id) for k,v in pairs(_config.admins) do if user_id == v[1] then print(k) return k end end -- If not found return false end local function getindex(t,id) for i,v in pairs(t) do if v == id then return i end end return nil end local function already_sudo(user_id) for k,v in pairs(_config.sudo_users) do if user_id == v then return k end end -- If not found return false end local function reload_plugins( ) plugins = {} load_plugins() end local function sudolist(msg) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local sudo_users = _config.sudo_users if not lang then text = "*List of sudo users :*\n" else text = "_لیست سودو های ربات :_\n" end for i=1,#sudo_users do text = text..i.." - "..sudo_users[i].."\n" end return text end local function adminlist(msg) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local sudo_users = _config.sudo_users if not lang then text = '*List of bot admins :*\n' else text = "_لیست ادمین های ربات :_\n" end local compare = text local i = 1 for v,user in pairs(_config.admins) do text = text..i..'- '..(user[2] or '')..' ➣ ('..user[1]..')\n' i = i +1 end if compare == text then if not lang then text = '_No_ *admins* _available_' else text = '_ادمینی برای ربات تعیین نشده_' end end return text end local function chat_list(msg) i = 1 local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of Groups:\n*Use #join (ID) to join*\n\n' for k,v in pairsByKeys(data[tostring(groups)]) do local group_id = v if data[tostring(group_id)] then settings = data[tostring(group_id)]['settings'] end for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n:gsub("", "") chat_name = name:gsub("‮", "") group_name_id = name .. '\n(ID: ' ..group_id.. ')\n\n' if name:match("[\216-\219][\128-\191]") then group_info = i..' - \n'..group_name_id else group_info = i..' - '..group_name_id end i = i + 1 end end message = message..group_info end return message end local function action_by_reply(arg, data) local cmd = arg.cmd if not tonumber(data.sender_user_id_) then return false end if data.sender_user_id_ then if cmd == "adminprom" then local function adminprom_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if is_admin1(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already an_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات بود_", 0, "md") end end table.insert(_config.admins, {tonumber(data.id_), user_name}) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been promoted as_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام ادمین ربات منتصب شد_", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, adminprom_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "admindem" then local function admindem_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local nameid = index_function(tonumber(data.id_)) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not is_admin1(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, admindem_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "visudo" then local function visudo_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if already_sudo(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات بود_", 0, "md") end end table.insert(_config.sudo_users, tonumber(data.id_)) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام سودو ربات منتصب شد_", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, visudo_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "desudo" then local function desudo_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not already_sudo(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات نبود_", 0, "md") end end table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_))) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام سودو ربات برکنار شد_", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, desudo_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end else if lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(data.chat_id_, "", 0, "*User Not Found*", 0, "md") end end end local function action_by_username(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local cmd = arg.cmd if not arg.username then return false end if data.id_ then if data.type_.user_.username_ then user_name = '@'..check_markdown(data.type_.user_.username_) else user_name = check_markdown(data.title_) end if cmd == "adminprom" then if is_admin1(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already an_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات بود_", 0, "md") end end table.insert(_config.admins, {tonumber(data.id_), user_name}) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been promoted as_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام ادمین ربات منتصب شد_", 0, "md") end end if cmd == "admindem" then local nameid = index_function(tonumber(data.id_)) if not is_admin1(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md") end end if cmd == "visudo" then if already_sudo(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات بود_", 0, "md") end end table.insert(_config.sudo_users, tonumber(data.id_)) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام سودو ربات منتصب شد_", 0, "md") end end if cmd == "desudo" then if not already_sudo(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات نبود_", 0, "md") end end table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_))) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام سودو ربات برکنار شد_", 0, "md") end end else if lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md") end end end local function action_by_id(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local cmd = arg.cmd if not tonumber(arg.user_id) then return false end if data.id_ then if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if cmd == "adminprom" then if is_admin1(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already an_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات بود_", 0, "md") end end table.insert(_config.admins, {tonumber(data.id_), user_name}) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been promoted as_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام ادمین ربات منتصب شد_", 0, "md") end end if cmd == "admindem" then local nameid = index_function(tonumber(data.id_)) if not is_admin1(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md") end end if cmd == "visudo" then if already_sudo(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات بود_", 0, "md") end end table.insert(_config.sudo_users, tonumber(data.id_)) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام سودو ربات منتصب شد_", 0, "md") end end if cmd == "desudo" then if not already_sudo(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات نبود_", 0, "md") end end table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_))) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام سودو ربات برکنار شد_", 0, "md") end end else if lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md") end end end local function run(msg, matches) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if tonumber(msg.from.id) == SUDO then if matches[1] == "visudo" then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="visudo"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="visudo"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="visudo"}) end end if matches[1] == "desudo" then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="desudo"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="desudo"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="desudo"}) end end end if matches[1] == "adminprom" and is_sudo(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="adminprom"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="adminprom"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="adminprom"}) end end if matches[1] == "admindem" and is_sudo(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_to_message_id_ }, action_by_reply, {chat_id=msg.to.id,cmd="admindem"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="admindem"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="admindem"}) end end if matches[1] == 'creategroup' and is_admin(msg) then local text = matches[2] tdcli.createNewGroupChat({[0] = msg.from.id}, text) if not lang then return '_Group Has Been Created!_' else return '_گروه ساخته شد!_' end end if matches[1] == 'createsuper' and is_admin(msg) then local text = matches[2] tdcli.createNewChannelChat({[0] = msg.sender_user_id_}, text) if not lang then return '_SuperGroup Has Been Created!_' else return '_سوپر گروه ساخته شد!_' end end if matches[1] == 'tosuper' and is_admin(msg) then local id = msg.to.id tdcli.migrateGroupChatToChannelChat(id) if not lang then return '_Group Has Been Changed To SuperGroup!_' else return '_گروه به سوپر گروه تبدیل شد!_' end end if matches[1] == 'import' and is_admin(msg) then tdcli.importChatInviteLink(matches[2]) if not lang then return '*Done!*' else return '*انجام شد!*' end end if matches[1] == 'setbotname' and is_sudo(msg) then tdcli.changeName(matches[2]) if not lang then return '_Bot Name Changed To:_ *'..matches[2]..'*' else return '_اسم ربات تغییر کرد به:_ \n*'..matches[2]..'*' end end if matches[1] == 'setbotusername' and is_sudo(msg) then tdcli.changeUsername(matches[2]) if not lang then return '_Bot Username Changed To:_ @'..matches[2] else return '_یوزرنیم ربات تغییر کرد به:_ \n@'..matches[2]..'' end end if matches[1] == 'delbotusername' and is_sudo(msg) then tdcli.changeUsername('') if not lang then return '*Done!*' else return '*انجام شد!*' end end if matches[1] == 'markread' and is_sudo(msg) then if matches[2] == 'on' then redis:set('markread','on') if not lang then return '_Markread >_ *ON*' else return '_تیک دوم >_ *روشن*' end end if matches[2] == 'off' then redis:set('markread','off') if not lang then return '_Markread >_ *OFF*' else return '_تیک دوم >_ *خاموش*' end end end if matches[1] == 'bc' and is_admin(msg) then tdcli.sendMessage(matches[2], 0, 0, matches[3], 0) end if matches[1] == 'broadcast' and is_sudo(msg) then local data = load_data(_config.moderation.data) local bc = matches[2] for k,v in pairs(data) do tdcli.sendMessage(k, 0, 0, bc, 0) end end if matches[1] == 'sudolist' and is_sudo(msg) then return sudolist(msg) end if matches[1] == 'chats' and is_admin(msg) then return chat_list(msg) end if matches[1]:lower() == 'join' and is_admin(msg) and matches[2] then tdcli.sendMessage(msg.to.id, msg.id, 1, 'I Invite you in '..matches[2]..'', 1, 'html') tdcli.sendMessage(matches[2], 0, 1, "Admin Joined!🌚", 1, 'html') tdcli.addChatMember(matches[2], msg.from.id, 0, dl_cb, nil) end if matches[1] == 'rem' and matches[2] and is_admin(msg) then local data = load_data(_config.moderation.data) -- Group configuration removal data[tostring(matches[2])] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(matches[2])] = nil save_data(_config.moderation.data, data) tdcli.sendMessage(matches[2], 0, 1, "Group has been removed by admin command", 1, 'html') return '_Group_ *'..matches[2]..'* _removed_' end if matches[1] == 'beyond' then return tdcli.sendMessage(msg.to.id, msg.id, 1, _config.info_text, 1, 'html') end if matches[1] == 'adminlist' and is_admin(msg) then return adminlist(msg) end if matches[1] == 'leave' and is_admin(msg) then tdcli.changeChatMemberStatus(msg.to.id, our_id, 'Left', dl_cb, nil) end if matches[1] == 'autoleave' and is_admin(msg) then local hash = 'auto_leave_bot' --Enable Auto Leave if matches[2] == 'enable' then redis:del(hash) return 'Auto leave has been enabled' --Disable Auto Leave elseif matches[2] == 'disable' then redis:set(hash, true) return 'Auto leave has been disabled' --Auto Leave Status elseif matches[2] == 'status' then if not redis:get(hash) then return 'Auto leave is enable' else return 'Auto leave is disable' end end end end return { patterns = { "^[!/#](visudo)$", "^[!/#](desudo)$", "^[!/#](sudolist)$", "^[!/#](visudo) (.*)$", "^[!/#](desudo) (.*)$", "^[!/#](adminprom)$", "^[!/#](admindem)$", "^[!/#](adminlist)$", "^[!/#](adminprom) (.*)$", "^[!/#](admindem) (.*)$", "^[!/#](leave)$", "^[!/#](autoleave) (.*)$", "^[!/#](beyond)$", "^[!/#](creategroup) (.*)$", "^[!/#](createsuper) (.*)$", "^[!/#](tosuper)$", "^[!/#](chats)$", "^[!/#](join) (.*)$", "^[!/#](rem) (.*)$", "^[!/#](import) (.*)$", "^[!/#](setbotname) (.*)$", "^[!/#](setbotusername) (.*)$", "^[!/#](delbotusername) (.*)$", "^[!/#](markread) (.*)$", "^[!/#](bc) (%d+) (.*)$", "^[!/#](broadcast) (.*)$", }, run = run } -- #End By @BeyondTeam
gpl-2.0
hfjgjfg/mohammad
plugins/wiki.lua
735
4364
-- http://git.io/vUA4M local socket = require "socket" local JSON = require "cjson" local wikiusage = { "!wiki [text]: Read extract from default Wikipedia (EN)", "!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola", "!wiki search [text]: Search articles on default Wikipedia (EN)", "!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola", } local Wikipedia = { -- http://meta.wikimedia.org/wiki/List_of_Wikipedias wiki_server = "https://%s.wikipedia.org", wiki_path = "/w/api.php", wiki_load_params = { action = "query", prop = "extracts", format = "json", exchars = 300, exsectionformat = "plain", explaintext = "", redirects = "" }, wiki_search_params = { action = "query", list = "search", srlimit = 20, format = "json", }, default_lang = "en", } function Wikipedia:getWikiServer(lang) return string.format(self.wiki_server, lang or self.default_lang) end --[[ -- return decoded JSON table from Wikipedia --]] function Wikipedia:loadPage(text, lang, intro, plain, is_search) local request, sink = {}, {} local query = "" local parsed if is_search then for k,v in pairs(self.wiki_search_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "srsearch=" .. URL.escape(text) else self.wiki_load_params.explaintext = plain and "" or nil for k,v in pairs(self.wiki_load_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "titles=" .. URL.escape(text) end -- HTTP request request['url'] = URL.build(parsed) print(request['url']) request['method'] = 'GET' request['sink'] = ltn12.sink.table(sink) local httpRequest = parsed.scheme == 'http' and http.request or https.request local code, headers, status = socket.skip(1, httpRequest(request)) if not headers or not sink then return nil end local content = table.concat(sink) if content ~= "" then local ok, result = pcall(JSON.decode, content) if ok and result then return result else return nil end else return nil end end -- extract intro passage in wiki page function Wikipedia:wikintro(text, lang) local result = self:loadPage(text, lang, true, true) if result and result.query then local query = result.query if query and query.normalized then text = query.normalized[1].to or text end local page = query.pages[next(query.pages)] if page and page.extract then return text..": "..page.extract else local text = "Extract not found for "..text text = text..'\n'..table.concat(wikiusage, '\n') return text end else return "Sorry an error happened" end end -- search for term in wiki function Wikipedia:wikisearch(text, lang) local result = self:loadPage(text, lang, true, true, true) if result and result.query then local titles = "" for i,item in pairs(result.query.search) do titles = titles .. "\n" .. item["title"] end titles = titles ~= "" and titles or "No results found" return titles else return "Sorry, an error occurred" end end local function run(msg, matches) -- TODO: Remember language (i18 on future version) -- TODO: Support for non Wikipedias but Mediawikis local search, term, lang if matches[1] == "search" then search = true term = matches[2] lang = nil elseif matches[2] == "search" then search = true term = matches[3] lang = matches[1] else term = matches[2] lang = matches[1] end if not term then term = lang lang = nil end if term == "" then local text = "Usage:\n" text = text..table.concat(wikiusage, '\n') return text end local result if search then result = Wikipedia:wikisearch(term, lang) else -- TODO: Show the link result = Wikipedia:wikintro(term, lang) end return result end return { description = "Searches Wikipedia and send results", usage = wikiusage, patterns = { "^![Ww]iki(%w+) (search) (.+)$", "^![Ww]iki (search) ?(.*)$", "^![Ww]iki(%w+) (.+)$", "^![Ww]iki ?(.*)$" }, run = run }
gpl-2.0
hsiaoyi/Melo
cocos2d/cocos/scripting/lua-bindings/auto/api/TurnOffTiles.lua
11
2477
-------------------------------- -- @module TurnOffTiles -- @extend TiledGrid3DAction -- @parent_module cc -------------------------------- -- brief Show the tile at specified position.<br> -- param pos The position index of the tile should be shown. -- @function [parent=#TurnOffTiles] turnOnTile -- @param self -- @param #vec2_table pos -- @return TurnOffTiles#TurnOffTiles self (return value: cc.TurnOffTiles) -------------------------------- -- brief Hide the tile at specified position.<br> -- param pos The position index of the tile should be hide. -- @function [parent=#TurnOffTiles] turnOffTile -- @param self -- @param #vec2_table pos -- @return TurnOffTiles#TurnOffTiles self (return value: cc.TurnOffTiles) -------------------------------- -- brief Initializes the action with grid size, random seed and duration.<br> -- param duration Specify the duration of the TurnOffTiles action. It's a value in seconds.<br> -- param gridSize Specify the size of the grid.<br> -- param seed Specify the random seed.<br> -- return If the Initialization success, return true; otherwise, return false. -- @function [parent=#TurnOffTiles] initWithDuration -- @param self -- @param #float duration -- @param #size_table gridSize -- @param #unsigned int seed -- @return bool#bool ret (return value: bool) -------------------------------- -- @overload self, float, size_table, unsigned int -- @overload self, float, size_table -- @function [parent=#TurnOffTiles] create -- @param self -- @param #float duration -- @param #size_table gridSize -- @param #unsigned int seed -- @return TurnOffTiles#TurnOffTiles ret (return value: cc.TurnOffTiles) -------------------------------- -- -- @function [parent=#TurnOffTiles] startWithTarget -- @param self -- @param #cc.Node target -- @return TurnOffTiles#TurnOffTiles self (return value: cc.TurnOffTiles) -------------------------------- -- -- @function [parent=#TurnOffTiles] clone -- @param self -- @return TurnOffTiles#TurnOffTiles ret (return value: cc.TurnOffTiles) -------------------------------- -- -- @function [parent=#TurnOffTiles] update -- @param self -- @param #float time -- @return TurnOffTiles#TurnOffTiles self (return value: cc.TurnOffTiles) -------------------------------- -- -- @function [parent=#TurnOffTiles] TurnOffTiles -- @param self -- @return TurnOffTiles#TurnOffTiles self (return value: cc.TurnOffTiles) return nil
apache-2.0
czfshine/UpAndAway
code/map/static_layouts/strix_shrine.lua
2
2173
return { version = "1.1", luaversion = "5.1", orientation = "orthogonal", width = 6, height = 6, tilewidth = 64, tileheight = 64, properties = {}, tilesets = { { name = "ground", firstgid = 1, filename = "../../../../../../../../../Don't Starve Mod Tools/mod_tools/Tiled/samplelayout/layout_source/dont_starve/ground.tsx", tilewidth = 64, tileheight = 64, spacing = 0, margin = 0, image = "../../../../../../../../../Don't Starve Mod Tools/mod_tools/Tiled/samplelayout/layout_source/dont_starve/tiles.png", imagewidth = 512, imageheight = 128, properties = {}, tiles = {} } }, layers = { { type = "tilelayer", name = "BG_TILES", x = 0, y = 0, width = 6, height = 6, visible = true, opacity = 1, properties = {}, encoding = "lua", data = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, { type = "objectgroup", name = "FG_OBJECTS", visible = true, opacity = 1, properties = {}, objects = { { name = "", type = "crystal_relic", shape = "rectangle", x = 192, y = 190, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "owl", shape = "rectangle", x = 291, y = 162, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "owl", shape = "rectangle", x = 154, y = 149, width = 0, height = 0, visible = true, properties = {} }, { name = "", type = "owl", shape = "rectangle", x = 109, y = 223, width = 0, height = 0, visible = true, properties = {} } } } } }
gpl-2.0
samael65535/quick-ng
cocos/scripting/lua-bindings/auto/api/FadeOut.lua
7
1047
-------------------------------- -- @module FadeOut -- @extend FadeTo -- @parent_module cc -------------------------------- -- js NA -- @function [parent=#FadeOut] setReverseAction -- @param self -- @param #cc.FadeTo ac -- @return FadeOut#FadeOut self (return value: cc.FadeOut) -------------------------------- -- Creates the action.<br> -- param d Duration time, in seconds. -- @function [parent=#FadeOut] create -- @param self -- @param #float d -- @return FadeOut#FadeOut ret (return value: cc.FadeOut) -------------------------------- -- -- @function [parent=#FadeOut] startWithTarget -- @param self -- @param #cc.Node target -- @return FadeOut#FadeOut self (return value: cc.FadeOut) -------------------------------- -- -- @function [parent=#FadeOut] clone -- @param self -- @return FadeOut#FadeOut ret (return value: cc.FadeOut) -------------------------------- -- -- @function [parent=#FadeOut] reverse -- @param self -- @return FadeTo#FadeTo ret (return value: cc.FadeTo) return nil
mit
CodedBrandon/BuildingWithFriends
ClientSide.lua
1
6512
local player = game.Players.LocalPlayer local mouse = player:GetMouse() local camera = game.Workspace.CurrentCamera local screen = player.PlayerGui:WaitForChild("Screen") do -- Visual Renders holo = Instance.new("Part", camera) do holo.Anchored = true holo.FormFactor = Enum.FormFactor.Custom do holo.BackSurface = Enum.SurfaceType.SmoothNoOutlines holo.BottomSurface = Enum.SurfaceType.SmoothNoOutlines holo.FrontSurface = Enum.SurfaceType.SmoothNoOutlines holo.LeftSurface = Enum.SurfaceType.SmoothNoOutlines holo.RightSurface = Enum.SurfaceType.SmoothNoOutlines holo.TopSurface = Enum.SurfaceType.SmoothNoOutlines end holo.Size = Vector3.new(4,4,4) holo.BrickColor = BrickColor.Blue() holo.CanCollide = false holo.Transparency = 0.5 holo.Name = "Builder" end outline = Instance.new("SelectionBox", holo) do outline.Adornee = holo outline.SurfaceTransparency = 0.5 outline.Transparency = 0 outline.LineThickness = 0.05 outline.Color3 = BrickColor.Blue().Color outline.SurfaceColor3 = BrickColor.Blue().Color outline.Name = "Outline" end local beam = Instance.new("BlockMesh", holo) do beam.Scale = Vector3.new(0.99, 300, 0.99) beam.Name = "Beam" end mouse.TargetFilter = holo end do -- Verify Collisions collider = Instance.new("Part", holo) do collider.Anchored = true collider.FormFactor = Enum.FormFactor.Custom do collider.BackSurface = Enum.SurfaceType.SmoothNoOutlines collider.BottomSurface = Enum.SurfaceType.SmoothNoOutlines collider.FrontSurface = Enum.SurfaceType.SmoothNoOutlines collider.LeftSurface = Enum.SurfaceType.SmoothNoOutlines collider.RightSurface = Enum.SurfaceType.SmoothNoOutlines collider.TopSurface = Enum.SurfaceType.SmoothNoOutlines end collider.Transparency = 1 collider.CanCollide = false collider.Name = "Collision Detector" end local sizeMinimizer = Vector3.new(-0.03, -0.03, -0.03) holo.Changed:connect(function() collider.Size = holo.Size + sizeMinimizer collider.Position = holo.CFrame.p end) collider.Size = holo.Size + sizeMinimizer collider.Position = holo.CFrame.p end local function visualRender() local hit, target = mouse.Hit, mouse.Target if hit and target then local renderPos = Vector3.new( math.floor(hit.p.X + 0.5), math.floor(hit.p.Y + 0.5), math.floor(hit.p.Z + 0.5) ) if mouse.TargetSurface == Enum.NormalId.Top then renderPos = renderPos + Vector3.new(0, holo.Size.Y/2, 0) elseif mouse.TargetSurface == Enum.NormalId.Bottom then renderPos = renderPos + Vector3.new(0, -holo.Size.Y/2, 0) elseif mouse.TargetSurface == Enum.NormalId.Front then renderPos = renderPos + Vector3.new(0, 0, -holo.Size.Y/2) elseif mouse.TargetSurface == Enum.NormalId.Back then renderPos = renderPos + Vector3.new(0, 0, holo.Size.Y/2) elseif mouse.TargetSurface == Enum.NormalId.Left then renderPos = renderPos + Vector3.new(-holo.Size.Y/2, 0, 0) elseif mouse.TargetSurface == Enum.NormalId.Right then renderPos = renderPos + Vector3.new(holo.Size.Y/2, 0, 0) end holo.CFrame = CFrame.new(renderPos) end end do -- Material GUI local materialPicker = screen.BuilderControls.Material materialSelection = Enum.Material.SmoothPlastic materialPicker.Display.MouseButton1Down:connect(function() materialPicker.Options.Visible = true end) materialPicker.Options.MouseLeave:connect(function() materialPicker.Options.Visible = false end) local options = materialPicker.Options local materials = { "Brick", "Cobblestone", "Concrete", "CorrodedMetal", "DiamondPlate", "Fabric", "Foil", "Granite", "Grass", "Marble", "Metal", "Neon", "Pebble", "Plastic", "Sand", "Slate", "SmoothPlastic", "Wood", "WoodPlanks" } for index, material in pairs(materials) do local button = options.MaterialTemplate:Clone() button.Parent = options button.Name, button.Text = material, material button.Position = UDim2.new(0, 0, 0, (index-1) * 27) options.CanvasSize = UDim2.new(0, 0, 0, (index) * 27) button.Visible = true button.MouseButton1Down:connect(function() materialPicker.Display.Text = button.Text materialSelection = Enum.Material[button.Name] options.Visible = false end) end end do -- Color GUI local colorPicker = screen.BuilderControls.Color colorSelection = BrickColor.palette(math.random(0, 63)) do colorPicker.BackgroundColor3 = colorSelection.Color colorPicker.Display.Text = colorSelection.Name end colorPicker.Display.MouseButton1Down:connect(function() colorPicker.Options.Visible = true end) colorPicker.Options.MouseLeave:connect(function() colorPicker.Options.Visible = false end) local options = colorPicker.Options local colors = 63 for x = 0, colors do local button = options.ColorTemplate:Clone() button.Parent = options button.Name = tostring(x) button.Text = BrickColor.palette(x).Name button.BackgroundColor3 = BrickColor.palette(x).Color button.Position = UDim2.new(0, 0, 0, x * 27) options.CanvasSize = UDim2.new(0, 0, 0, x * 27) button.Visible = true button.MouseButton1Down:connect(function() local color = BrickColor.palette(tonumber(button.Name)) colorPicker.Display.Text = color.Name colorPicker.BackgroundColor3 = color.Color colorSelection = color print(color.Name) options.Visible = false end) end end local buildDebounce = true local function build() if buildDebounce then buildDebounce = false collider.CanCollide = true local collisions = collider:GetTouchingParts() collider.CanCollide = false if #collisions <= 0 then local block = Instance.new("Part", game.Workspace) block.Anchored = true block.FormFactor = Enum.FormFactor.Custom do block.BackSurface = Enum.SurfaceType.SmoothNoOutlines block.BottomSurface = Enum.SurfaceType.SmoothNoOutlines block.FrontSurface = Enum.SurfaceType.SmoothNoOutlines block.LeftSurface = Enum.SurfaceType.SmoothNoOutlines block.RightSurface = Enum.SurfaceType.SmoothNoOutlines block.TopSurface = Enum.SurfaceType.SmoothNoOutlines end block.Size = holo.Size block.CFrame = CFrame.new(holo.CFrame.p) block.Transparency = 0 block.CanCollide = true block.Material = materialSelection block.BrickColor = colorSelection block.Name = "Block" wait(0.05) else outline.Color3 = BrickColor.Red().Color wait(0.2) outline.Color3 = BrickColor.Blue().Color end buildDebounce = true end visualRender() end mouse.Move:connect(visualRender) mouse.Button1Down:connect(build) visualRender()
gpl-2.0
Javaxio/BadRotations
System/UI/Toggles/ToggleFunctions.lua
5
11020
-- when we find a match, we reset tooltip function ResetTip(toggleValue,thisValue) GameTooltip:SetOwner(_G["button"..toggleValue], mainButton, 0 , 0) GameTooltip:SetText(_G[toggleValue.. "Modes"][thisValue].tip, 225/255, 225/255, 225/255, nil, true) GameTooltip:Show() end function GarbageButtons() if buttonsTable then for i = 1, #buttonsTable do local Name = buttonsTable[i].name _G["button"..Name]:Hide() _G["text"..Name]:Hide() _G["frame"..Name].texture:Hide() _G[Name.."Modes"] = nil end end end function ToggleToValue(toggleValue,index) local index = tonumber(index) local modesCount = #_G[toggleValue.."Modes"] if index > modesCount then Print("Invalid Toggle Index for |cffFFDD11"..toggleValue..": |cFFFF0000 Index ( |r"..index.."|cFFFF0000) exceeds Max ( |r".. modesCount .."|cFFFF0000)|r.") else for i = 1,modesCount do if i == index then specialToggleCodes(toggleValue,index) br.data.settings[br.selectedSpec].toggles[tostring(toggleValue)] = index changeButton(toggleValue,index) -- We reset the tip ResetTip(toggleValue,index) break end end end end function ToggleValue(toggleValue) -- prevent nil fails local toggleOldValue = br.data.settings[br.selectedSpec].toggles[tostring(toggleValue)] or 1 local modesCount = #_G[toggleValue.."Modes"] if toggleOldValue == nil then br.data.settings[br.selectedSpec].toggles[tostring(toggleValue)] = 1 toggleOldValue = br.data.settings[br.selectedSpec].toggles[tostring(toggleValue)] end -- Scan Table and find which mode = our i for i = 1,modesCount do if toggleOldValue == i then -- see if we can go higher in modes is #modes > i if modesCount > i then -- calculate newValue newValue = i + 1 specialToggleCodes(toggleValue,newValue) -- We set the value in DB br.data.settings[br.selectedSpec].toggles[tostring(toggleValue)] = newValue changeButton(toggleValue,newValue) -- We reset the tip ResetTip(toggleValue,newValue) break else specialToggleCodes(toggleValue,1) -- if cannot go higher we define mode to 1. br.data.settings[br.selectedSpec].toggles[tostring(toggleValue)] = 1 changeButton(toggleValue,1) -- We reset the tip ResetTip(toggleValue,1) break end end end end function ToggleMinus(toggleValue) -- prevent nil fails if br.data.settings[br.selectedSpec].toggles[tostring(toggleValue)] == nil then br.data.settings[br.selectedSpec].toggles[tostring(toggleValue)] = 1 end local modesCount = #_G[toggleValue.."Modes"] -- Scan Table and find which mode = our i for i = 1,modesCount do local thisValue = br.data.settings[br.selectedSpec].toggles[tostring(toggleValue)] or 1 if thisValue == i then local Icon -- see if we can go lower in modes if i > 1 then -- calculate newValue newValue = i - 1 specialToggleCodes(toggleValue,newValue) -- We set the value in DB br.data.settings[br.selectedSpec].toggles[tostring(toggleValue)] = newValue -- change the button changeButton(toggleValue,newValue) -- We reset the tip ResetTip(toggleValue,newValue) break else -- if cannot go higher we define to last mode br.data.settings[br.selectedSpec].toggles[tostring(toggleValue)] = modesCount specialToggleCodes(toggleValue,newValue) changeButton(toggleValue,newValue) -- We reset the tip ResetTip(toggleValue,newValue) break end end end end function specialToggleCodes(toggleValue,newValue) if toggleValue == "Interrupts" then local InterruptsModes = InterruptsModes if newValue == 1 and InterruptsModes[1].mode == "None" then -- no interupts mode if br.data.settings[br.selectedSpec]["Interrupts HandlerCheck"] ~= 0 then _G["optionsInterrupts HandlerCheck"]:Click() end elseif newValue == 2 and InterruptsModes[2].mode == "Raid" then -- on/off switch if br.data.settings[br.selectedSpec]["Interrupts HandlerCheck"] ~= 1 then _G["optionsInterrupts HandlerCheck"]:Click() end -- only known switch if br.data.settings[br.selectedSpec]["Only Known UnitsCheck"] ~= 1 then _G["optionsOnly Known UnitsCheck"]:Click() end -- if we want to change drop down here is code. --[[if br.data.settings[br.selectedSpec]["Interrupts HandlerDrop"] ~= 4 then -- _G[parent..value.."DropChild"] local colorGreen = "|cff00FF00" _G["Interrupts Handler"..colorGreen.."AllDropChild"]:Click() end]] elseif newValue == 3 and InterruptsModes[3].mode == "All" then -- interrupt all mode -- on/off switch if br.data.settings[br.selectedSpec]["Interrupts HandlerCheck"] ~= 1 then _G["optionsInterrupts HandlerCheck"]:Click() end -- only known switch if br.data.settings[br.selectedSpec]["Only Known UnitsCheck"] ~= 0 then _G["optionsOnly Known UnitsCheck"]:Click() end end end end function changeButtonValue(toggleValue,newValue) br.data.settings[br.selectedSpec].toggles[tostring(toggleValue)] = newValue end -- set to desired button value function changeButton(toggleValue,newValue) -- define text _G["text"..toggleValue]:SetText(_G[toggleValue.. "Modes"][newValue].mode) -- define icon if type(_G[toggleValue.. "Modes"][newValue].icon) == "number" then Icon = select(3,GetSpellInfo(_G[toggleValue.."Modes"][newValue].icon)) else Icon = _G[toggleValue.."Modes"][newValue].icon end _G["button"..toggleValue]:SetNormalTexture(Icon or emptyIcon) -- define highlight if _G[toggleValue.."Modes"][newValue].highlight == 0 then _G["frame"..toggleValue].texture:SetTexture(genericIconOff) else _G["frame"..toggleValue].texture:SetTexture(genericIconOn) end -- We tell the user we changed mode ChatOverlay("\124cFF3BB0FF".._G[toggleValue.. "Modes"][newValue].overlay) -- We reset the tip ResetTip(toggleValue,newValue) end function UpdateButton(Name) local Name = tostring(Name) ToggleValue(Name) end function buttonsResize() for i = 1, #buttonsTable do local Name = buttonsTable[i].name local x = buttonsTable[i].bx local y = buttonsTable[i].by _G["button"..Name]:SetWidth(br.data.settings["buttonSize"]) _G["button"..Name]:SetHeight(br.data.settings["buttonSize"]) _G["button"..Name]:SetPoint("LEFT",x*(br.data.settings["buttonSize"]),y*(br.data.settings["buttonSize"])) _G["text"..Name]:SetTextHeight(br.data.settings["buttonSize"]/3) _G["text"..Name]:SetPoint("CENTER",0,-(br.data.settings["buttonSize"]/4)) _G["frame"..Name]:SetWidth(br.data.settings["buttonSize"]*1.67) _G["frame"..Name]:SetHeight(br.data.settings["buttonSize"]*1.67) _G["frame"..Name].texture:SetWidth(br.data.settings["buttonSize"]*1.67) _G["frame"..Name].texture:SetHeight(br.data.settings["buttonSize"]*1.67) end end -- /run CreateButton("AoE",2,2) function CreateButton(Name,x,y) local Icon -- todo: extend to use spec + profile specific variable; ATM it shares between profile AND spec, -> global for char if br.data.settings[br.selectedSpec].toggles[Name] == nil or br.data.settings[br.selectedSpec].toggles[Name] > #_G[Name.."Modes"] then br.data.settings[br.selectedSpec].toggles[Name] = 1 end tinsert(buttonsTable, { name = Name, bx = x, by = y }) _G["button"..Name] = CreateFrame("Button", "MyButtonBR", mainButton, "SecureHandlerClickTemplate") _G["button"..Name]:SetWidth(br.data.settings["buttonSize"]) _G["button"..Name]:SetHeight(br.data.settings["buttonSize"]) _G["button"..Name]:SetPoint("LEFT",x*(br.data.settings["buttonSize"])+(x*2),y*(br.data.settings["buttonSize"])+(y*2)) _G["button"..Name]:RegisterForClicks("AnyUp") if _G[Name.."Modes"][br.data.settings[br.selectedSpec].toggles[Name]].icon ~= nil and type(_G[Name.."Modes"][br.data.settings[br.selectedSpec].toggles[Name]].icon) == "number" then Icon = select(3,GetSpellInfo(_G[Name.."Modes"][br.data.settings[br.selectedSpec].toggles[Name]].icon)) else Icon = _G[Name.."Modes"][br.data.settings[br.selectedSpec].toggles[Name]].icon end _G["button"..Name]:SetNormalTexture(Icon or emptyIcon) --CreateBorder(_G["button"..Name], 8, 0.6, 0.6, 0.6) _G["text"..Name] = _G["button"..Name]:CreateFontString(nil, "OVERLAY") _G["text"..Name]:SetFont(br.data.settings.font,br.data.settings.fontsize,"THICKOUTLINE") _G["text"..Name]:SetJustifyH("CENTER") _G["text"..Name]:SetTextHeight(br.data.settings["buttonSize"]/3) _G["text"..Name]:SetPoint("CENTER",3,-(br.data.settings["buttonSize"]/8)) _G["text"..Name]:SetTextColor(1,1,1,1) _G["frame"..Name] = CreateFrame("Frame", nil, _G["button"..Name]) _G["frame"..Name]:SetWidth(br.data.settings["buttonSize"]*1.67) _G["frame"..Name]:SetHeight(br.data.settings["buttonSize"]*1.67) _G["frame"..Name]:SetPoint("CENTER") _G["frame"..Name].texture = _G["frame"..Name]:CreateTexture(_G["button"..Name], "OVERLAY") _G["frame"..Name].texture:SetAllPoints() _G["frame"..Name].texture:SetWidth(br.data.settings["buttonSize"]*1.67) _G["frame"..Name].texture:SetHeight(br.data.settings["buttonSize"]*1.67) _G["frame"..Name].texture:SetAlpha(100) _G["frame"..Name].texture:SetTexture(genericIconOn) local modeTable if _G[Name.."Modes"] == nil then Print("No table found for ".. Name); _G[Name.."Modes"] = tostring(Name) else _G[Name.."Modes"] = _G[Name.."Modes"] end local modeValue if br.data.settings[br.selectedSpec].toggles[tostring(Name)] == nil then br.data.settings[br.selectedSpec].toggles[tostring(Name)] = 1 modeValue = 1 else modeValue = br.data.settings[br.selectedSpec].toggles[tostring(Name)] end _G["button"..Name]:SetScript("OnClick", function(self, button) if button == "RightButton" then ToggleMinus(Name) else ToggleValue(Name) end end ) local actualTip = _G[Name.."Modes"][br.data.settings[br.selectedSpec].toggles[Name]].tip _G["button"..Name]:SetScript("OnMouseWheel", function(self, delta) local Go = false if delta < 0 and br.data.settings[br.selectedSpec].toggles[tostring(Name)] > 1 then Go = true elseif delta > 0 and br.data.settings[br.selectedSpec].toggles[tostring(Name)] < #_G[Name.."Modes"] then Go = true end if Go == true then br.data.settings[br.selectedSpec].toggles[tostring(Name)] = br.data.settings[br.selectedSpec].toggles[tostring(Name)] + delta end end) _G["button"..Name]:SetScript("OnEnter", function(self) GameTooltip:SetOwner(_G["button"..Name], UIParent, 0 , 0) GameTooltip:SetText(_G[Name.."Modes"][br.data.settings[br.selectedSpec].toggles[Name]].tip, 225/255, 225/255, 225/255, nil, true) GameTooltip:Show() end) _G["button"..Name]:SetScript("OnLeave", function(self) GameTooltip:Hide() end) _G["text"..Name]:SetText(_G[Name.."Modes"][modeValue].mode) if _G[Name.."Modes"][modeValue].highlight == 0 then _G["frame"..Name].texture:SetTexture(genericIconOff) else _G["frame"..Name].texture:SetTexture(genericIconOn) end if br.data.settings[br.selectedSpec].toggles["Main"] == 1 then mainButton:Show() else mainButton:Hide() end SlashCommandHelp("br toggle "..Name.." 1-"..#_G[Name.."Modes"],"Toggles "..Name.." Modes, Optional: specify number") end
gpl-3.0
hfjgjfg/armanarman
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
xdemolish/darkstar
scripts/zones/The_Ashu_Talif/Zone.lua
34
1119
----------------------------------- -- -- Zone: The_Ashu_Talif -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/The_Ashu_Talif/TextIDs"] = nil; require("scripts/zones/The_Ashu_Talif/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) 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
xdemolish/darkstar
scripts/zones/The_Eldieme_Necropolis_[S]/npcs/Layton.lua
34
1914
----------------------------------- -- Area: The Eldieme Necropolis (S) -- NPC: Layton -- Type: Standard Merchant NPC -- Note: Available during Campaign battles -- @pos 382.679 -39.999 3.541 175 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/zones/The_Eldieme_Necropolis_[S]/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,LAYTON_SHOP_DIALOG); stock = {0x17A1,8060, -- Firestorm Schema 0x17A2,6318, -- Rainstorm Schema 0x17A3,9100, -- Thunderstorm Schema 0x17A4,8580, -- Hailstorm Schema 0x17A5,5200, -- Sandstorm Schema 0x17A6,6786, -- Windstorm Schema 0x17A7,11440, -- Aurorastorm Schema 0x17A8,10725, -- Voidstorm Schema 0x1799,7714, -- Pyrohelix Schema 0x179A,6786, -- Hydrohelix Schema 0x179B,8625, -- Ionohelix Schema 0x179C,7896, -- Cryohelix Schema 0x179D,6591, -- Geohelix Schema 0x179E,6981, -- Anemohelix Schema 0x179F,8940, -- Luminohelix Schema 0x17A0,8790} -- Noctohelix Schema showShop(player, STATIC, stock); 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
hostingrust-ru/rust-shop
plugins/shop.lua
1
18974
--[[ © 2014 HostingRust.ru Plugin for implementation the web-api requests for service: shop.hostingrust.ru --]] -- Be safe, your config :) local MARKET_ID = 0; local SECRET_KEY = 'YOUR SECRET_KEY'; -- DO NOT EDIT BELOW THIS LINE PLUGIN.Title = "Shop System"; PLUGIN.Description = "The shop system for human"; PLUGIN.Author = "Andrew Mensky"; PLUGIN.Version = "Git"; local AUTH_TIME = 0; local EXPIRES_IN = 0; local MARKET_NAME = ""; -- Exend standart stl function util.PrintTable(t, indent, done) done = done or {}; indent = indent or 0; for key, value in pairs (t) do if (type(value) == "table" and not done[value]) then done [value] = true; print(string.rep("\t", indent) .. tostring(key) .. ":"); util.PrintTable (value, indent + 2, done); else print(string.rep("\t", indent) .. tostring (key) .. " = " .. tostring(value)); end; end; end; function table.HasValue(t, val) for k,v in pairs(t) do if (v == val) then return true end; end; return false; end; function table.count(t) local i = 0; for k in pairs(t) do i = i + 1 end; return i; end; local function implode(tbl, seperator) local str = ""; local b = true; for k, v in pairs(tbl) do str = str..(b and "" or seperator)..tostring(k).."="..tostring(v); b = false; end; return str; end; -- A function to get curtime of server local curTime = util.GetStaticPropertyGetter(UnityEngine.Time, "realtimeSinceStartup"); -- A function call when plugin initialized function PLUGIN:Init() print("SHOP plugin loading..."); self.version = 0.13; self.initialized = false; self.on_auth = false; self.fatal_errors = {3, 5, 6, 7, 8, 9}; self:LoadConfig(); self:AddUserCommand("shop_sell", self.cmdSell); self:AddUserCommand("shop_buy", self.cmdBuy); self:AddUserCommand("shop_cash", self.cmdCash); self:AddAdminCommand("shop_import", self.cmdImport); self:AddAdminCommand("shop_auth", self.cmdAuth); self:AddAdminCommand("shop_key", self.cmdKey); self.re_auth_timer = timer.Once(10, function() self:Auth(true); end); end; -- A function call when plugin has been reload function PLUGIN:Unload() if (self.re_auth_timer) then self.re_auth_timer:Destroy(); end; end; -- A function to add admin chat command function PLUGIN:AddAdminCommand(name, callback) local func = function(class, netuser, cmd, args) -- Check admin permision if (not netuser:CanAdmin()) then rust.Notice(netuser, "Unknown chat command!"); return false; end; return callback(class, netuser, cmd, args); end; self:AddChatCommand(name, func); end; -- A function to add shop chat command function PLUGIN:AddUserCommand(name, callback) local func = function(class, netuser, cmd, args) -- Check initialized shop status if (not class.initialized) then class:chat(netuser, "Магазин не инициализирован."); return false; end; return callback(class, netuser, cmd, args); end; self:AddChatCommand(name, func); end; -- A function to load config of this plugin function PLUGIN:LoadConfig() local b, res = config.Read("shop"); self.Config = res or {}; self:InitConfig("shop_url", ""); self:InitConfig("api_url", "http://shop.hostingrust.ru/api"); self:InitConfig("sell_slot", 30); self:InitConfig("debug", true); self:InitConfig("black_list", {-971007166}); self:InitConfig("black_as_white", false); self:InitConfig("require_recovery", {}); config.Save("shop"); end; -- A function to get config with default value function PLUGIN:InitConfig(name, default) if (type(self.Config) ~= "table") then self.Config = {}; end; if (self.Config[name] == nil or type(self.Config[name]) ~= type(default)) then self.Config[name] = default; end; end; -- A function to send msg to the player with shop tag function PLUGIN:chat(netuser, msg) if (not netuser) then return; end; rust.SendChatToUser(netuser, "shop", tostring(msg)); end; -- A function to debug message function PLUGIN:debug(msg, global) if (self.Config.debug) then if (global) then self:log(msg); else print("SHOP: "..tostring(msg)); end; end; end; -- A function to pint msg for all admin on server function PLUGIN:log(msg) print("SHOP: "..tostring(msg)); local plys = rust.GetAllNetUsers(); for i=1, #plys do if (plys[i]:CanAdmin()) then rust.SendChatToUser(plys[i], "shop", tostring(msg)); end; end; end; -- A function to call web shop api function PLUGIN:CallApi(api_method, data, onSuccess, onFailure) -- Validate data if (not api_method or type(api_method) ~= "string") then return false, "API method not valid!"; elseif (onSuccess and type(onSuccess) ~= "function") then return false, "onSuccess not valid!"; elseif (onFailure and type(onFailure) ~= "function") then return false, "onFailure not valid!"; end; data = type(data) ~= "table" and {} or data; -- Prepare data local api_url = self.Config.api_url.."/"..api_method; local post_data = data.post and implode(data.post, "&") or ""; local get_data = {}; if (data.get) then get_data = data.get; elseif (not data.post and table.count(data) > 0) then get_data = data; end; get_data.token = api_method ~= "global.auth" and TOKEN or nil; get_data.secret_key = api_method == "global.auth" and SECRET_KEY or nil; get_data.market_id = api_method == "global.auth" and MARKET_ID or nil; api_url = api_url.."?"..implode(get_data, "&"); self:debug(api_url); -- Create web request webrequest.PostQueue(api_url, post_data, function(_, code, response) -- Check http status if (code ~= 200) then local err_msg = "Error on the server, returned code: "..tostring(code); if (onFailure) then onFailure(err_msg, 0) end; error("SHOP: "..err_msg); return false; end; -- Decode and validate json response local result = json.decode(response); if (type(result) ~= "table") then local err_msg = "Server return incorrect json response."; if (onFailure) then onFailure(err_msg, 0) end; error("SHOP: "..err_msg); return false; elseif (result.plugin_version and result.plugin_version > self.version) then self:log("New plugin version available, keep calm and make update."); end; -- Switch correct json result if (not result.error and onSuccess) then onSuccess(result.response); elseif (onFailure) then -- De initialize if (table.HasValue(self.fatal_errors, result.error_code)) then self.initialized = false; end; onFailure(result.error, result.error_code or 1); end; end); end; function PLUGIN:Auth(bRetry) -- Check auth thered exists if (self.on_auth) then return false; end; self.on_auth = true; -- Call API self:CallApi("global.auth", {}, function(response) -- Initialize shop TOKEN, AUTH_TIME, EXPIRES_IN, MARKET_NAME = response.token, response.auth_time, response.expires_in-10, response.market_name; self.initialized = true; self.on_auth = false; -- Create re-auth timer if (self.re_auth_timer) then self.re_auth_timer:Destroy(); end; self.re_auth_timer = timer.Once(EXPIRES_IN, function() self:Auth(true); end); self:log("Auth complete ["..MARKET_NAME.."]."); self:log("Re-Auth will be called after "..EXPIRES_IN..' sec.'); end, function(err, error_code) -- Clear data TOKEN, AUTH_TIME, MARKET_NAME = '', 0, ''; self.initialized = false; self.on_auth = false; self:log("Error web API auth ["..error_code.."]: "..err); -- Make retry if (bRetry) then if (table.HasValue(self.fatal_errors, result.error_code)) then self:log("Automatic retry auth cannot be execute, fatal error."); else self.on_auth = true; self:log("Execute retry auth."); self.re_auth_timer = timer.Once(10, function() self.on_auth = false; if (not self.initialize) then self:Auth(true); end; end); end; end; end); return true; end; -- Getter functions function PLUGIN:GetMarketName() return MARKET_NAME; end; function PLUGIN:IsInitialized() return self.initialize; end; function PLUGIN:GetMarketID() return MARKET_ID; end; function PLUGIN:GetConfig() return self.Config; end; -- A function to import rust items (only admin service) function PLUGIN:cmdImport(netuser, cmd, args) -- Prepare data local count = Rust.DatablockDictionary.All.Length; local list = {}; for i=0, count-1 do local item = Rust.DatablockDictionary.All[i]; local cat = tostring(item.category); local s = string.find(cat, ": "); local l = string.len(cat); cat = string.sub(cat, s+2, l); list[ tonumber(item.uniqueID) ] = { name = tostring(item.name), cat = tonumber(cat), icon = string.gsub(item.icon, "content/item/tex/", ""), desc = tostring(item:GetItemDescription()), splittable = item:IsSplittable(); }; end; local data = json.encode(list); -- Call API self:log("Starting import "..tostring(count).." items!"); self:CallApi("ritem.import", { post = { data = data } }, function(response) self:log("Import items success!"); end, function(err) self:log("Error import items ["..err.."]!"); end); end; function PLUGIN:cmdAuth(netuser, cmd, args) -- Call Auth function if (not self:Auth()) then self:chat(netuser, "Auth thered allready execute."); end; end; function PLUGIN:cmdKey(netuser, cmd, args) -- Check admin permision if (not netuser:CanAdmin()) then rust.Notice(netuser, "Unknown chat command!"); return false; end; if (not args[1]) then return false end; SECRET_KEY = args[1]; self:log("Secret key has ben changed, don't forget change him in script MANUALITY!"); end; function PLUGIN:modsList(item) local t = {}; if (type(item.itemMods) ~= "string" and item.usedModSlots > 0) then for i=0, item.usedModSlots-1 do table.insert(t, item.itemMods[i].uniqueID); end; end; return t; end; -- A function return count of free slout in player inventory function PLUGIN:FreeSlotsCount(netuser) local inv = rust.GetInventory(netuser); local count = 0; if (not inv) then return 0; end; for i=0, 35 do if (inv:IsSlotFree(i)) then count = count + 1; end; end; return count; end; -- A function to give item with some parameters function PLUGIN:GiveItem(netuser, uid, dt) -- Initialize data local datablock = Rust.DatablockDictionary.GetByUniqueID(uid); local inv = rust.GetInventory(netuser); dt = dt or {}; -- Validate data if (not datablock) then return false, "Datablock not find."; elseif (not inv) then return false, "Player inventory not found."; elseif (self:FreeSlotsCount(netuser) <= 0) then return false, "Has no empty slots."; end; -- Give player item local item = inv:AddItemSomehow(datablock, InventorySlotKind.Belt, 0, tonumber(dt.uses) or 1); if (not item) then return false, "Failed to add item."; end; -- Set item properties item:SetCondition(tonumber(dt.condition) or 1.0); item:SetMaxCondition(tonumber(dt.maxcondition) or 1.0); -- Addition mods if (type(item.itemMods) ~= "string") then item:SetTotalModSlotCount(tonumber(dt.modSlots) or 0); if (type(dt.itemMods) == "table") then for i = 1, #dt.itemMods do local mod = Rust.DatablockDictionary.GetByUniqueID(dt.itemMods[i]); if (mod and type(mod.modFlag) ~= "string") then item:AddMod(mod); else inv:RemoveItem(item); -- Take item return false, "Invalid mod item ["..dt.itemMods[i].."]."; end; end; end; end; return item, ''; end; function PLUGIN:cmdBuy(netuser, cmd, args) -- Initializing data local barcode = tonumber(args[1]); -- Validate data if (not barcode) then self:chat(netuser, "Пожалуйста, укажите код вещи."); return false; end; if (self:FreeSlotsCount(netuser) <= 0) then self:chat(netuser, "У вас нет свободных слотов для покупки."); return false; end; -- Call hook if (plugins.Call("PreCanBuyItem", netuser, barcode) == false) then return false; end; -- Call API self:chat(netuser, "Барыга пытается найти ваш товар!"); self:CallApi("item.getById", { id = barcode, filter = json.encode({ sold = false }) }, function(response) local item = response[1]; if (not item) then self:chat(netuser, "Барыга не нашел товар, скорей всего уже продан!"); return false; end; -- Call hook if (plugins.Call("CanBuyItem", netuser, item) == false) then return false; end; -- Call API local properties = { sold = true }; self:CallApi("item.edit", { id = barcode, properties = json.encode(properties) }, function(response) -- Checking changes if (not response.sold) then return self:chat(netuser, "Товар уже продан!"); end; -- Give item local success, err = self:GiveItem(netuser, tonumber(item.item_id), { uses = item.uses, condition = item.condition, maxcondition = item.maxcondition, modSlots = item.mod_slots, itemMods = item.item_mods or {}, }); if (success) then plugins.Call("OnBuyItem", netuser, item); self:chat(netuser, "Барыга продал вам товар!"); else self.Config.require_recovery[barcode] = { sold = false }; config.Save("shop"); self:chat(netuser, "Барыга передумал: "..err); end; end, function(err) self:chat(netuser, "Барыга не продаст вам товар: "..err); end); end, function(err) self:chat(netuser, "Барыга не нашел товар: "..err); end); end; function PLUGIN:cmdSell(netuser, cmd, args) -- Call hook if (plugins.Call("PreCanSellItem", netuser) == false) then return false; end; -- Initializing data local price = args[1] and tonumber(args[1]) or 0; local uid = rust.GetUserID(netuser); local name = netuser.displayName; local inv = rust.GetInventory(netuser); local item; -- Validate data if (price <= 0) then self:chat(netuser, "Не корректная цена!"); return false; end; if (not inv) then self:chat(netuser, "Инвентарь не инициализирован!"); return false; else local b, i = inv:GetItem(self.Config.sell_slot); if (not b) then self:chat(netuser, "Для продажи, поместите вещь на "..(self.Config.sell_slot-29).."-й слот быстрого доступа!"); return false; end; item = i; end; -- Generate api data local item_mods = self:modsList(item); local data = { item_id = item.datablock.uniqueID, price = price, uses = tonumber(item.uses) or 1, condition = item.condition or 1.0, maxcondition = item.maxcondition or 1.0, mod_slots = tonumber(item.totalModSlots) or 0, item_mods = json.encode(item_mods), owner_id = uid, owner_name = name, auction = false, }; -- Call hook if (plugins.Call("CanSellItem", netuser, data) == false) then return false; end; -- Take item and log hee inv:RemoveItem(self.Config.sell_slot); self:debug("Take item["..item.datablock.uniqueID.."]["..item.datablock.name.."] from '"..name.."' with: { uses: "..item.uses..", condition: "..item.condition.."/"..item.maxcondition..", mods: "..data.item_mods.." }"); self:chat(netuser, "Барыга взял вашу вещь на осмотр!"); -- Call API self:CallApi("item.add", data, function(response) plugins.Call("OnSellItem", netuser, data); self:chat(netuser, "Барыга принял вашу вещь на продажу!"); self:chat(netuser, "Код вещи: "..response.barcode); end, function(err) local item = self:GiveItem(netuser, data.item_id, { uses = data.uses, condition = data.condition, maxcondition = data.maxcondition, modSlots = data.mod_slots, itemMods = item_mods }); self:chat(netuser, "Барыга вернул ваш хлам: "..err); end); end; function PLUGIN:cmdCash(netuser, cmd, args) -- Custom checker if (plugins.Call("CanGetCash", netuser) == false) then return false; end; self:chat(netuser, "Барыга проверяет записи ваших продаж!"); local uid = rust.GetUserID(netuser); local data = { id = uid, filter = json.encode({sold = true}) }; self:CallApi("item.getByOwnerId", data, function(response) local cash = 0; local count = #response; for i=1, count do cash = cash + response[i].price; end; if (cash <= 0) then self:chat(netuser, "Ваше барахло никто не купил."); return false; end; plugins.Call("OnGetCash", netuser, count, cash, response); end, function(err) self:chat(netuser, "Барыга нашел ошибку: "..err); end); end; -- Events function PLUGIN:CanBuyItem(netuser, item) -- Backlist check local exist = table.HasValue(self.Config.black_list, item.item_id); if ((exist and not self.Config.black_as_white) or (not exist and self.Config.black_as_white)) then self:chat(netuser, "Покупка этого предмета запрещена администратором."); return false; end; -- Money check local econmod = plugins.Find("econ"); if (econmod) then if (econmod:getMoney(netuser) < item.price) then self:chat(netuser, "Барыга огорчен, недостаточно средств."); return false; end; end; end; function PLUGIN:OnBuyItem(netuser, item) local econmod = plugins.Find("econ"); if (econmod) then econmod:takeMoneyFrom(netuser, item.price); econmod:printmoney(netuser); end; end; function PLUGIN:CanSellItem(netuser, item) local exist = table.HasValue(self.Config.black_list, item.item_id); if ((exist and not self.Config.black_as_white) or (not exist and self.Config.black_as_white)) then self:chat(netuser, "Продажа этого предмета запрещена администратором."); return false; end; end; function PLUGIN:OnGetCash(netuser, count, cash, items) local econmod = plugins.Find("econ"); if (econmod) then local remove_list = {} for i=1, count do remove_list[i] = items[i].barcode; end; self:CallApi("item.remove", {list = json.encode(remove_list)}, function(response) econmod:giveMoneyTo(netuser, cash); self:chat(netuser, "Кол-во продаж: "..count); self:chat(netuser, "Общая сумма дохода: "..cash); end, function(err) self:chat(netuser, "Барыга нашел ошибку: "..err); end); end; end; -- Help function PLUGIN:SendHelpText(netuser) self:chat(netuser, "Адрес онлайн магазина: "..self.Config.shop_url); self:chat(netuser, "/shop_buy <код> - для покупки вещей."); self:chat(netuser, "/shop_sell <цена> - для продажи, предварительно поместите вещь на "..(self.Config.sell_slot-29).."-й быстрого доступа."); self:chat(netuser, "/shop_cash - для получения средств с продаж."); end; -- Registration API if (not api.Exists("shop")) then api.Bind(PLUGIN, "shop"); end;
mpl-2.0
generalistr6/Radeon_Rays
Tools/deploy/App.lua
5
1721
project "App" kind "ConsoleApp" location "../App" links {"CLW"} files { "../App/**.h", "../App/**.cpp", "../App/**.cl", "../App/**.fsh", "../App/**.vsh" } includedirs{ "../FireRays/include", "../CLW" } configuration {"x64"} links { "FireRays64" } libdirs { "../FireRays/lib/x64"} configuration {} if os.is("macosx") then includedirs {"../3rdParty/oiio16/include"} libdirs {"../3rdParty/oiio16/lib/x64"} linkoptions{ "-framework OpenGL", "-framework GLUT" } buildoptions "-std=c++11 -stdlib=libc++" links {"OpenImageIO"} end if os.is("windows") then includedirs { "../3rdParty/glew/include", "../3rdParty/freeglut/include", "../3rdParty/oiio/include" } links {"freeglut", "glew"} configuration {"x64"} libdirs { "../3rdParty/glew/lib/x64", "../3rdParty/freeglut/lib/x64", "../3rdParty/embree/lib/x64", "../3rdParty/oiio/lib/x64"} configuration {} configuration {"Debug"} links {"OpenImageIOD"} configuration {"Release"} links {"OpenImageIO"} end if os.is("linux") then buildoptions "-std=c++11" links {"OpenImageIO", "glut", "GLEW", "GL", "pthread"} os.execute("rm -rf obj"); end if _OPTIONS["embed_kernels"] then configuration {} defines {"FR_EMBED_KERNELS"} os.execute("python ../scripts/stringify.py ./CL/ > ./CL/cache/kernels.h") print ">> App: CL kernels embedded" end configuration {"x64", "Debug"} targetdir "../Bin/Debug/x64" configuration {"x64", "Release"} targetdir "../Bin/Release/x64" configuration {}
mit
xdemolish/darkstar
scripts/zones/RuLude_Gardens/npcs/Archanne.lua
38
1047
----------------------------------- -- Area: Ru'Lude Gardens -- NPC: Archanne -- Type: Event Scene Replayer -- @zone: 243 -- @pos -54.104 10.999 -34.144 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x2717); 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
xdemolish/darkstar
scripts/zones/Cloister_of_Tides/Zone.lua
32
1658
----------------------------------- -- -- Zone: Cloister_of_Tides (211) -- ----------------------------------- package.loaded["scripts/zones/Cloister_of_Tides/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Cloister_of_Tides/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(564.776,34.297,500.819,250); 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); end;
gpl-3.0
xdemolish/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Dhea_Prandoleh.lua
16
1048
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Dhea Prandoleh -- Type: Standard NPC -- @zone: 94 -- @pos 3.167 -2 15.545 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00a0); 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
hsiaoyi/Melo
cocos2d/cocos/scripting/lua-bindings/auto/api/Slider.lua
4
9240
-------------------------------- -- @module Slider -- @extend Widget -- @parent_module ccui -------------------------------- -- Changes the progress direction of slider.<br> -- param percent Percent value from 1 to 100. -- @function [parent=#Slider] setPercent -- @param self -- @param #int percent -- @return Slider#Slider self (return value: ccui.Slider) -------------------------------- -- Query the maximum percent of Slider. The default value is 100.<br> -- since v3.7<br> -- return The maximum percent of the Slider. -- @function [parent=#Slider] getMaxPercent -- @param self -- @return int#int ret (return value: int) -------------------------------- -- Load normal state texture for slider ball.<br> -- param normal Normal state texture.<br> -- param resType @see TextureResType . -- @function [parent=#Slider] loadSlidBallTextureNormal -- @param self -- @param #string normal -- @param #int resType -- @return Slider#Slider self (return value: ccui.Slider) -------------------------------- -- Load dark state texture for slider progress bar.<br> -- param fileName File path of texture.<br> -- param resType @see TextureResType . -- @function [parent=#Slider] loadProgressBarTexture -- @param self -- @param #string fileName -- @param #int resType -- @return Slider#Slider self (return value: ccui.Slider) -------------------------------- -- -- @function [parent=#Slider] getBallNormalFile -- @param self -- @return ResourceData#ResourceData ret (return value: cc.ResourceData) -------------------------------- -- Sets if slider is using scale9 renderer.<br> -- param able True that using scale9 renderer, false otherwise. -- @function [parent=#Slider] setScale9Enabled -- @param self -- @param #bool able -- @return Slider#Slider self (return value: ccui.Slider) -------------------------------- -- -- @function [parent=#Slider] getBallPressedFile -- @param self -- @return ResourceData#ResourceData ret (return value: cc.ResourceData) -------------------------------- -- brief Return a zoom scale<br> -- since v3.3 -- @function [parent=#Slider] getZoomScale -- @param self -- @return float#float ret (return value: float) -------------------------------- -- Sets capinsets for progress bar slider, if slider is using scale9 renderer.<br> -- param capInsets Capinsets for progress bar slider.<br> -- js NA -- @function [parent=#Slider] setCapInsetProgressBarRenderer -- @param self -- @param #rect_table capInsets -- @return Slider#Slider self (return value: ccui.Slider) -------------------------------- -- Load textures for slider ball.<br> -- param normal Normal state texture.<br> -- param pressed Pressed state texture.<br> -- param disabled Disabled state texture.<br> -- param texType @see TextureResType . -- @function [parent=#Slider] loadSlidBallTextures -- @param self -- @param #string normal -- @param #string pressed -- @param #string disabled -- @param #int texType -- @return Slider#Slider self (return value: ccui.Slider) -------------------------------- -- Add call back function called when slider's percent has changed to slider.<br> -- param callback An given call back function called when slider's percent has changed to slider. -- @function [parent=#Slider] addEventListener -- @param self -- @param #function callback -- @return Slider#Slider self (return value: ccui.Slider) -------------------------------- -- Set a large value could give more control to the precision.<br> -- since v3.7<br> -- param percent The max percent of Slider. -- @function [parent=#Slider] setMaxPercent -- @param self -- @param #int percent -- @return Slider#Slider self (return value: ccui.Slider) -------------------------------- -- Load texture for slider bar.<br> -- param fileName File name of texture.<br> -- param resType @see TextureResType . -- @function [parent=#Slider] loadBarTexture -- @param self -- @param #string fileName -- @param #int resType -- @return Slider#Slider self (return value: ccui.Slider) -------------------------------- -- -- @function [parent=#Slider] getProgressBarFile -- @param self -- @return ResourceData#ResourceData ret (return value: cc.ResourceData) -------------------------------- -- Gets capinsets for bar slider, if slider is using scale9 renderer.<br> -- return capInsets Capinsets for bar slider. -- @function [parent=#Slider] getCapInsetsBarRenderer -- @param self -- @return rect_table#rect_table ret (return value: rect_table) -------------------------------- -- Gets capinsets for progress bar slider, if slider is using scale9 renderer.<br> -- return Capinsets for progress bar slider.<br> -- js NA -- @function [parent=#Slider] getCapInsetsProgressBarRenderer -- @param self -- @return rect_table#rect_table ret (return value: rect_table) -------------------------------- -- Load pressed state texture for slider ball.<br> -- param pressed Pressed state texture.<br> -- param resType @see TextureResType . -- @function [parent=#Slider] loadSlidBallTexturePressed -- @param self -- @param #string pressed -- @param #int resType -- @return Slider#Slider self (return value: ccui.Slider) -------------------------------- -- -- @function [parent=#Slider] getBackFile -- @param self -- @return ResourceData#ResourceData ret (return value: cc.ResourceData) -------------------------------- -- Gets If slider is using scale9 renderer.<br> -- return True that using scale9 renderer, false otherwise. -- @function [parent=#Slider] isScale9Enabled -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#Slider] getBallDisabledFile -- @param self -- @return ResourceData#ResourceData ret (return value: cc.ResourceData) -------------------------------- -- Sets capinsets for bar slider, if slider is using scale9 renderer.<br> -- param capInsets Capinsets for bar slider. -- @function [parent=#Slider] setCapInsetsBarRenderer -- @param self -- @param #rect_table capInsets -- @return Slider#Slider self (return value: ccui.Slider) -------------------------------- -- Gets the progress direction of slider.<br> -- return percent Percent value from 1 to 100. -- @function [parent=#Slider] getPercent -- @param self -- @return int#int ret (return value: int) -------------------------------- -- Sets capinsets for slider, if slider is using scale9 renderer.<br> -- param capInsets Capinsets for slider. -- @function [parent=#Slider] setCapInsets -- @param self -- @param #rect_table capInsets -- @return Slider#Slider self (return value: ccui.Slider) -------------------------------- -- Load disabled state texture for slider ball.<br> -- param disabled Disabled state texture.<br> -- param resType @see TextureResType . -- @function [parent=#Slider] loadSlidBallTextureDisabled -- @param self -- @param #string disabled -- @param #int resType -- @return Slider#Slider self (return value: ccui.Slider) -------------------------------- -- When user pressed the button, the button will zoom to a scale.<br> -- The final scale of the button equals (button original scale + _zoomScale)<br> -- since v3.3 -- @function [parent=#Slider] setZoomScale -- @param self -- @param #float scale -- @return Slider#Slider self (return value: ccui.Slider) -------------------------------- -- @overload self, string, string, int -- @overload self -- @function [parent=#Slider] create -- @param self -- @param #string barTextureName -- @param #string normalBallTextureName -- @param #int resType -- @return Slider#Slider ret (return value: ccui.Slider) -------------------------------- -- -- @function [parent=#Slider] createInstance -- @param self -- @return Ref#Ref ret (return value: cc.Ref) -------------------------------- -- -- @function [parent=#Slider] getVirtualRenderer -- @param self -- @return Node#Node ret (return value: cc.Node) -------------------------------- -- -- @function [parent=#Slider] ignoreContentAdaptWithSize -- @param self -- @param #bool ignore -- @return Slider#Slider self (return value: ccui.Slider) -------------------------------- -- Returns the "class name" of widget. -- @function [parent=#Slider] getDescription -- @param self -- @return string#string ret (return value: string) -------------------------------- -- -- @function [parent=#Slider] hitTest -- @param self -- @param #vec2_table pt -- @param #cc.Camera camera -- @param #vec3_table p -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#Slider] init -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#Slider] getVirtualRendererSize -- @param self -- @return size_table#size_table ret (return value: size_table) -------------------------------- -- Default constructor.<br> -- js ctor<br> -- lua new -- @function [parent=#Slider] Slider -- @param self -- @return Slider#Slider self (return value: ccui.Slider) return nil
apache-2.0
mrbangi/mrbangi
plugins/google.lua
336
1323
do local function googlethat(query) local url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&safe=active&&rsz=5&' local parameters = 'q='..(URL.escape(query) or '') -- Do the request local res, code = https.request(url..parameters) if code ~=200 then return nil end local data = json:decode(res) local results = {} for key,result in ipairs(data.responseData.results) do table.insert(results, { result.titleNoFormatting, result.unescapedUrl or result.url }) end return results end local function stringlinks(results) local stringresults='' i = 0 for key,val in ipairs(results) do i = i+1 stringresults=stringresults..i..'. '..val[1]..'\n'..val[2]..'\n' end return stringresults end local function run(msg, matches) -- comment this line if you want this plugin works in private message. if not is_chat_msg(msg) then return nil end local results = googlethat(matches[1]) return stringlinks(results) end return { description = 'Returns five results from Google. Safe search is enabled by default.', usage = ' !google [terms]: Searches Google and send results', patterns = { '^!google (.*)$', '^%.[g|G]oogle (.*)$' }, run = run } end
gpl-2.0
xdemolish/darkstar
scripts/zones/Dynamis-Xarcabard/mobs/King_Zagan.lua
19
1251
----------------------------------- -- Area: Dynamis Xarcabard -- NPC: King Zagan ----------------------------------- require("scripts/globals/dynamis"); require("scripts/zones/Dynamis-Xarcabard/TextIDs"); ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local Animate_Trigger = GetServerVariable("[DynaXarcabard]Boss_Trigger"); if(mob:isInBattlefieldList() == false) then mob:addInBattlefieldList(); Animate_Trigger = Animate_Trigger + 2048; SetServerVariable("[DynaXarcabard]Boss_Trigger",Animate_Trigger); if(Animate_Trigger == 32767) then SpawnMob(17330911); -- 142 SpawnMob(17330912); -- 143 SpawnMob(17330183); -- 177 SpawnMob(17330184); -- 178 activateAnimatedWeapon(); -- Change subanim of all animated weapon end end if(Animate_Trigger == 32767) then killer:messageSpecial(PRISON_OF_SOULS_HAS_SET_FREE); end end;
gpl-3.0
xdemolish/darkstar
scripts/zones/Oldton_Movalpolos/TextIDs.lua
5
1146
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6382; -- Obtained: <item>. GIL_OBTAINED = 6383; -- Obtained <number> gil. KEYITEM_OBTAINED = 6385; -- Obtained key item: <keyitem>. FISHING_MESSAGE_OFFSET = 7549; -- You can't fish here. -- Mining MINING_IS_POSSIBLE_HERE = 7675; -- Mining is possible here if you have -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7722; -- You unlock the chest! CHEST_FAIL = 7723; -- Fails to open the chest. CHEST_TRAP = 7724; -- The chest was trapped! CHEST_WEAK = 7725; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7726; -- The chest was a mimic! CHEST_MOOGLE = 7727; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7728; -- The chest was but an illusion... CHEST_LOCKED = 7729; -- The chest appears to be locked. -- NPCs RAKOROK_DIALOGUE = 7699; -- Nsy pipul. Gattohre! I bisynw! -- conquest Base CONQUEST_BASE = 7030; -- Tallying conquest results...
gpl-3.0
xdemolish/darkstar
scripts/globals/items/galkan_sausage_-1.lua
35
1586
----------------------------------------- -- ID: 5862 -- Item: galkan_sausage_-1 -- Food Effect: 30Min, All Races ----------------------------------------- -- Strength -3 -- Dexterity -3 -- Vitality -3 -- Agility -3 -- Mind -3 -- Intelligence -3 -- Charisma -3 ----------------------------------------- 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,5862); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, -3); target:addMod(MOD_DEX, -3); target:addMod(MOD_VIT, -3); target:addMod(MOD_AGI, -3); target:addMod(MOD_MND, -3); target:addMod(MOD_INT, -3); target:addMod(MOD_CHR, -3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, -3); target:delMod(MOD_DEX, -3); target:delMod(MOD_VIT, -3); target:delMod(MOD_AGI, -3); target:delMod(MOD_MND, -3); target:delMod(MOD_INT, -3); target:delMod(MOD_CHR, -3); end;
gpl-3.0
hsiaoyi/Melo
cocos2d/tests/lua-empty-test/src/mobdebug.lua
23
57276
-- -- MobDebug 0.542 -- Copyright 2011-13 Paul Kulchenko -- Based on RemDebug 1.0 Copyright Kepler Project 2005 -- local mobdebug = { _NAME = "mobdebug", _VERSION = 0.542, _COPYRIGHT = "Paul Kulchenko", _DESCRIPTION = "Mobile Remote Debugger for the Lua programming language", port = os and os.getenv and os.getenv("MOBDEBUG_PORT") or 8172, checkcount = 200, yieldtimeout = 0.02, } local coroutine = coroutine local error = error local getfenv = getfenv local setfenv = setfenv local loadstring = loadstring or load -- "load" replaced "loadstring" in Lua 5.2 local io = io local os = os local pairs = pairs local require = require local setmetatable = setmetatable local string = string local tonumber = tonumber local unpack = table.unpack or unpack local rawget = rawget -- if strict.lua is used, then need to avoid referencing some global -- variables, as they can be undefined; -- use rawget to to avoid complaints from strict.lua at run-time. -- it's safe to do the initialization here as all these variables -- should get defined values (of any) before the debugging starts. -- there is also global 'wx' variable, which is checked as part of -- the debug loop as 'wx' can be loaded at any time during debugging. local genv = _G or _ENV local jit = rawget(genv, "jit") local MOAICoroutine = rawget(genv, "MOAICoroutine") if not setfenv then -- Lua 5.2 -- based on http://lua-users.org/lists/lua-l/2010-06/msg00314.html -- this assumes f is a function local function findenv(f) local level = 1 repeat local name, value = debug.getupvalue(f, level) if name == '_ENV' then return level, value end level = level + 1 until name == nil return nil end getfenv = function (f) return(select(2, findenv(f)) or _G) end setfenv = function (f, t) local level = findenv(f) if level then debug.setupvalue(f, level, t) end return f end end -- check for OS and convert file names to lower case on windows -- (its file system is case insensitive, but case preserving), as setting a -- breakpoint on x:\Foo.lua will not work if the file was loaded as X:\foo.lua. -- OSX and Windows behave the same way (case insensitive, but case preserving) local iscasepreserving = os and os.getenv and (os.getenv('WINDIR') or (os.getenv('OS') or ''):match('[Ww]indows') or os.getenv('DYLD_LIBRARY_PATH')) or not io.open("/proc") -- turn jit off based on Mike Pall's comment in this discussion: -- http://www.freelists.org/post/luajit/Debug-hooks-and-JIT,2 -- "You need to turn it off at the start if you plan to receive -- reliable hook calls at any later point in time." if jit and jit.off then jit.off() end local socket = require "socket" local debug = require "debug" local coro_debugger local coro_debugee local coroutines = {}; setmetatable(coroutines, {__mode = "k"}) -- "weak" keys local events = { BREAK = 1, WATCH = 2, RESTART = 3, STACK = 4 } local breakpoints = {} local watches = {} local lastsource local lastfile local watchescnt = 0 local abort -- default value is nil; this is used in start/loop distinction local seen_hook = false local checkcount = 0 local step_into = false local step_over = false local step_level = 0 local stack_level = 0 local server local buf local outputs = {} local iobase = {print = print} local basedir = "" local deferror = "execution aborted at default debugee" local debugee = function () local a = 1 for _ = 1, 10 do a = a + 1 end error(deferror) end local function q(s) return s:gsub('([%(%)%.%%%+%-%*%?%[%^%$%]])','%%%1') end local serpent = (function() ---- include Serpent module for serialization local n, v = "serpent", 0.25 -- (C) 2012-13 Paul Kulchenko; MIT License local c, d = "Paul Kulchenko", "Lua serializer and pretty printer" local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'} local badtype = {thread = true, userdata = true, cdata = true} local keyword, globals, G = {}, {}, (_G or _ENV) for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end for k,v in pairs(G) do globals[v] = k end -- build func to name mapping for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do for k,v in pairs(G[g]) do globals[v] = g..'.'..k end end local function s(t, opts) local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge) local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge) local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0 local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)", -- tostring(val) is needed because __tostring may return a non-string value function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return syms[s] end)) end local function safestr(s) return type(s) == "number" and (huge and snum[tostring(s)] or s) or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026 or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r'] local n = name == nil and '' or name local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n] local safe = plain and n or '['..safestr(n)..']' return (path or '')..(plain and path and '.' or '')..safe, safe end local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'} local function padnum(d) return ("%0"..maxn.."d"):format(d) end table.sort(k, function(a,b) -- sort numeric keys first: k[key] is non-nil for numeric keys return (k[a] and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum)) < (k[b] and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end local function val2str(t, name, indent, insref, path, plainindex, level) local ttype, level, mt = type(t), (level or 0), getmetatable(t) local spath, sname = safename(path, name) local tag = plainindex and ((type(name) == "number") and '' or name..space..'='..space) or (name ~= nil and sname..space..'='..space or '') if seen[t] then -- already seen this element sref[#sref+1] = spath..space..'='..space..seen[t] return tag..'nil'..comment('ref', level) end if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself seen[t] = insref or spath if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end ttype = type(t) end -- new value falls through to be serialized if ttype == "table" then if level >= maxl then return tag..'{}'..comment('max', level) end seen[t] = insref or spath if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty local maxn, o, out = math.min(#t, maxnum or #t), {}, {} for key = 1, maxn do o[key] = key end if not maxnum or #o < maxnum then local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end if maxnum and #o > maxnum then o[maxnum+1] = nil end if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output) for n, key in ipairs(o) do local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing or opts.keyallow and not opts.keyallow[key] or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types or sparse and value == nil then -- skipping nils; do nothing elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then if not seen[key] and not globals[key] then sref[#sref+1] = 'placeholder' local sname = safename(iname, gensym(key)) -- iname is table for local variables sref[#sref] = val2str(key,sname,indent,sname,iname,true) end sref[#sref+1] = 'placeholder' local path = seen[t]..'['..(seen[key] or globals[key] or gensym(key))..']' sref[#sref] = path..space..'='..space..(seen[value] or val2str(value,nil,indent,path)) else out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1) end end local prefix = string.rep(indent or '', level) local head = indent and '{\n'..prefix..indent or '{' local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space)) local tail = indent and "\n"..prefix..'}' or '}' return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level) elseif badtype[ttype] then seen[t] = insref or spath return tag..globerr(t, level) elseif ttype == 'function' then seen[t] = insref or spath local ok, res = pcall(string.dump, t) local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or "loadstring("..safestr(res)..",'@serialized')")..comment(t, level)) return tag..(func or globerr(t, level)) else return tag..safestr(t) end -- handle all other types end local sepr = indent and "\n" or ";"..space local body = val2str(t, name, indent) -- this call also populates sref local tail = #sref>1 and table.concat(sref, sepr)..sepr or '' local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or '' return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end" end local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s, dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end, line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end, block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end } end)() ---- end of Serpent module local function removebasedir(path, basedir) if iscasepreserving then -- check if the lowercased path matches the basedir -- if so, return substring of the original path (to not lowercase it) return path:lower():find('^'..q(basedir:lower())) and path:sub(#basedir+1) or path else return string.gsub(path, '^'..q(basedir), '') end end local function stack(start) local function vars(f) local func = debug.getinfo(f, "f").func local i = 1 local locals = {} while true do local name, value = debug.getlocal(f, i) if not name then break end if string.sub(name, 1, 1) ~= '(' then locals[name] = {value, tostring(value)} end i = i + 1 end i = 1 local ups = {} while func and true do -- check for func as it may be nil for tail calls local name, value = debug.getupvalue(func, i) if not name then break end ups[name] = {value, tostring(value)} i = i + 1 end return locals, ups end local stack = {} for i = (start or 0), 100 do local source = debug.getinfo(i, "Snl") if not source then break end local src = source.source if src:find("@") == 1 then src = src:sub(2):gsub("\\", "/") if src:find("%./") == 1 then src = src:sub(3) end end table.insert(stack, { -- remove basedir from source {source.name, removebasedir(src, basedir), source.linedefined, source.currentline, source.what, source.namewhat, source.short_src}, vars(i+1)}) if source.what == 'main' then break end end return stack end local function set_breakpoint(file, line) if file == '-' and lastfile then file = lastfile elseif iscasepreserving then file = string.lower(file) end if not breakpoints[line] then breakpoints[line] = {} end breakpoints[line][file] = true end local function remove_breakpoint(file, line) if file == '-' and lastfile then file = lastfile elseif iscasepreserving then file = string.lower(file) end if breakpoints[line] then breakpoints[line][file] = nil end end local function has_breakpoint(file, line) return breakpoints[line] and breakpoints[line][iscasepreserving and string.lower(file) or file] end local function restore_vars(vars) if type(vars) ~= 'table' then return end -- locals need to be processed in the reverse order, starting from -- the inner block out, to make sure that the localized variables -- are correctly updated with only the closest variable with -- the same name being changed -- first loop find how many local variables there is, while -- the second loop processes them from i to 1 local i = 1 while true do local name = debug.getlocal(3, i) if not name then break end i = i + 1 end i = i - 1 local written_vars = {} while i > 0 do local name = debug.getlocal(3, i) if not written_vars[name] then if string.sub(name, 1, 1) ~= '(' then debug.setlocal(3, i, rawget(vars, name)) end written_vars[name] = true end i = i - 1 end i = 1 local func = debug.getinfo(3, "f").func while true do local name = debug.getupvalue(func, i) if not name then break end if not written_vars[name] then if string.sub(name, 1, 1) ~= '(' then debug.setupvalue(func, i, rawget(vars, name)) end written_vars[name] = true end i = i + 1 end end local function capture_vars(level) local vars = {} local func = debug.getinfo(level or 3, "f").func local i = 1 while true do local name, value = debug.getupvalue(func, i) if not name then break end if string.sub(name, 1, 1) ~= '(' then vars[name] = value end i = i + 1 end i = 1 while true do local name, value = debug.getlocal(level or 3, i) if not name then break end if string.sub(name, 1, 1) ~= '(' then vars[name] = value end i = i + 1 end -- returned 'vars' table plays a dual role: (1) it captures local values -- and upvalues to be restored later (in case they are modified in "eval"), -- and (2) it provides an environment for evaluated chunks. -- getfenv(func) is needed to provide proper environment for functions, -- including access to globals, but this causes vars[name] to fail in -- restore_vars on local variables or upvalues with `nil` values when -- 'strict' is in effect. To avoid this `rawget` is used in restore_vars. setmetatable(vars, { __index = getfenv(func), __newindex = getfenv(func) }) return vars end local function stack_depth(start_depth) for i = start_depth, 0, -1 do if debug.getinfo(i, "l") then return i+1 end end return start_depth end local function is_safe(stack_level) -- the stack grows up: 0 is getinfo, 1 is is_safe, 2 is debug_hook, 3 is user function if stack_level == 3 then return true end for i = 3, stack_level do -- return if it is not safe to abort local info = debug.getinfo(i, "S") if not info then return true end if info.what == "C" then return false end end return true end local function in_debugger() local this = debug.getinfo(1, "S").source -- only need to check few frames as mobdebug frames should be close for i = 3, 7 do local info = debug.getinfo(i, "S") if not info then return false end if info.source == this then return true end end return false end local function is_pending(peer) -- if there is something already in the buffer, skip check if not buf and checkcount >= mobdebug.checkcount then peer:settimeout(0) -- non-blocking buf = peer:receive(1) peer:settimeout() -- back to blocking checkcount = 0 end return buf end local function debug_hook(event, line) -- (1) LuaJIT needs special treatment. Because debug_hook is set for -- *all* coroutines, and not just the one being debugged as in regular Lua -- (http://lua-users.org/lists/lua-l/2011-06/msg00513.html), -- need to avoid debugging mobdebug's own code as LuaJIT doesn't -- always correctly generate call/return hook events (there are more -- calls than returns, which breaks stack depth calculation and -- 'step' and 'step over' commands stop working; possibly because -- 'tail return' events are not generated by LuaJIT). -- the next line checks if the debugger is run under LuaJIT and if -- one of debugger methods is present in the stack, it simply returns. if jit then -- when luajit is compiled with LUAJIT_ENABLE_LUA52COMPAT, -- coroutine.running() returns non-nil for the main thread. local coro, main = coroutine.running() if not coro or main then coro = 'main' end local disabled = coroutines[coro] == false or coroutines[coro] == nil and coro ~= (coro_debugee or 'main') if coro_debugee and disabled or not coro_debugee and (disabled or in_debugger()) then return end end -- (2) check if abort has been requested and it's safe to abort if abort and is_safe(stack_level) then error(abort) end -- (3) also check if this debug hook has not been visited for any reason. -- this check is needed to avoid stepping in too early -- (for example, when coroutine.resume() is executed inside start()). if not seen_hook and in_debugger() then return end if event == "call" then stack_level = stack_level + 1 elseif event == "return" or event == "tail return" then stack_level = stack_level - 1 elseif event == "line" then -- may need to fall through because of the following: -- (1) step_into -- (2) step_over and stack_level <= step_level (need stack_level) -- (3) breakpoint; check for line first as it's known; then for file -- (4) socket call (only do every Xth check) -- (5) at least one watch is registered if not ( step_into or step_over or breakpoints[line] or watchescnt > 0 or is_pending(server) ) then checkcount = checkcount + 1; return end checkcount = mobdebug.checkcount -- force check on the next command -- this is needed to check if the stack got shorter or longer. -- unfortunately counting call/return calls is not reliable. -- the discrepancy may happen when "pcall(load, '')" call is made -- or when "error()" is called in a function. -- in either case there are more "call" than "return" events reported. -- this validation is done for every "line" event, but should be "cheap" -- as it checks for the stack to get shorter (or longer by one call). -- start from one level higher just in case we need to grow the stack. -- this may happen after coroutine.resume call to a function that doesn't -- have any other instructions to execute. it triggers three returns: -- "return, tail return, return", which needs to be accounted for. stack_level = stack_depth(stack_level+1) local caller = debug.getinfo(2, "S") -- grab the filename and fix it if needed local file = lastfile if (lastsource ~= caller.source) then file, lastsource = caller.source, caller.source -- technically, users can supply names that may not use '@', -- for example when they call loadstring('...', 'filename.lua'). -- Unfortunately, there is no reliable/quick way to figure out -- what is the filename and what is the source code. -- The following will work if the supplied filename uses Unix path. if file:find("^@") then file = file:gsub("^@", ""):gsub("\\", "/") -- need this conversion to be applied to relative and absolute -- file names as you may write "require 'Foo'" to -- load "foo.lua" (on a case insensitive file system) and breakpoints -- set on foo.lua will not work if not converted to the same case. if iscasepreserving then file = string.lower(file) end if file:find("%./") == 1 then file = file:sub(3) else file = file:gsub('^'..q(basedir), '') end -- some file systems allow newlines in file names; remove these. file = file:gsub("\n", ' ') else -- this is either a file name coming from loadstring("chunk", "file"), -- or the actual source code that needs to be serialized (as it may -- include newlines); assume it's a file name if it's all on one line. file = file:find("[\r\n]") and serpent.line(file) or file end -- set to true if we got here; this only needs to be done once per -- session, so do it here to at least avoid setting it for every line. seen_hook = true lastfile = file end local vars, status, res if (watchescnt > 0) then vars = capture_vars() for index, value in pairs(watches) do setfenv(value, vars) local ok, fired = pcall(value) if ok and fired then status, res = coroutine.resume(coro_debugger, events.WATCH, vars, file, line, index) break -- any one watch is enough; don't check multiple times end end end -- need to get into the "regular" debug handler, but only if there was -- no watch that was fired. If there was a watch, handle its result. local getin = (status == nil) and (step_into or (step_over and stack_level <= step_level) or has_breakpoint(file, line) or is_pending(server)) if getin then vars = vars or capture_vars() step_into = false step_over = false status, res = coroutine.resume(coro_debugger, events.BREAK, vars, file, line) end -- handle 'stack' command that provides stack() information to the debugger if status and res == 'stack' then while status and res == 'stack' do -- resume with the stack trace and variables if vars then restore_vars(vars) end -- restore vars so they are reflected in stack values -- this may fail if __tostring method fails at run-time local ok, snapshot = pcall(stack, 4) status, res = coroutine.resume(coro_debugger, ok and events.STACK or events.BREAK, snapshot, file, line) end end -- need to recheck once more as resume after 'stack' command may -- return something else (for example, 'exit'), which needs to be handled if status and res and res ~= 'stack' then if abort == nil and res == "exit" then os.exit(1); return end abort = res -- only abort if safe; if not, there is another (earlier) check inside -- debug_hook, which will abort execution at the first safe opportunity if is_safe(stack_level) then error(abort) end elseif not status and res then error(res, 2) -- report any other (internal) errors back to the application end if vars then restore_vars(vars) end end end local function stringify_results(status, ...) if not status then return status, ... end -- on error report as it local t = {...} for i,v in pairs(t) do -- stringify each of the returned values local ok, res = pcall(serpent.line, v, {nocode = true, comment = 1}) t[i] = ok and res or ("%q"):format(res):gsub("\010","n"):gsub("\026","\\026") end -- stringify table with all returned values -- this is done to allow each returned value to be used (serialized or not) -- intependently and to preserve "original" comments return pcall(serpent.dump, t, {sparse = false}) end local function debugger_loop(sev, svars, sfile, sline) local command local app, osname local eval_env = svars or {} local function emptyWatch () return false end local loaded = {} for k in pairs(package.loaded) do loaded[k] = true end while true do local line, err local wx = rawget(genv, "wx") -- use rawread to make strict.lua happy if (wx or mobdebug.yield) and server.settimeout then server:settimeout(mobdebug.yieldtimeout) end while true do line, err = server:receive() if not line and err == "timeout" then -- yield for wx GUI applications if possible to avoid "busyness" app = app or (wx and wx.wxGetApp and wx.wxGetApp()) if app then local win = app:GetTopWindow() local inloop = app:IsMainLoopRunning() osname = osname or wx.wxPlatformInfo.Get():GetOperatingSystemFamilyName() if win and not inloop then -- process messages in a regular way -- and exit as soon as the event loop is idle if osname == 'Unix' then wx.wxTimer(app):Start(10, true) end local exitLoop = function() win:Disconnect(wx.wxID_ANY, wx.wxID_ANY, wx.wxEVT_IDLE) win:Disconnect(wx.wxID_ANY, wx.wxID_ANY, wx.wxEVT_TIMER) app:ExitMainLoop() end win:Connect(wx.wxEVT_IDLE, exitLoop) win:Connect(wx.wxEVT_TIMER, exitLoop) app:MainLoop() end elseif mobdebug.yield then mobdebug.yield() end elseif not line and err == "closed" then error("Debugger connection unexpectedly closed", 0) else -- if there is something in the pending buffer, prepend it to the line if buf then line = buf .. line; buf = nil end break end end if server.settimeout then server:settimeout() end -- back to blocking command = string.sub(line, string.find(line, "^[A-Z]+")) if command == "SETB" then local _, _, _, file, line = string.find(line, "^([A-Z]+)%s+(.-)%s+(%d+)%s*$") if file and line then set_breakpoint(file, tonumber(line)) server:send("200 OK\n") else server:send("400 Bad Request\n") end elseif command == "DELB" then local _, _, _, file, line = string.find(line, "^([A-Z]+)%s+(.-)%s+(%d+)%s*$") if file and line then remove_breakpoint(file, tonumber(line)) server:send("200 OK\n") else server:send("400 Bad Request\n") end elseif command == "EXEC" then local _, _, chunk = string.find(line, "^[A-Z]+%s+(.+)$") if chunk then local func, res = loadstring(chunk) local status if func then setfenv(func, eval_env) status, res = stringify_results(pcall(func)) end if status then server:send("200 OK " .. #res .. "\n") server:send(res) else server:send("401 Error in Expression " .. #res .. "\n") server:send(res) end else server:send("400 Bad Request\n") end elseif command == "LOAD" then local _, _, size, name = string.find(line, "^[A-Z]+%s+(%d+)%s+(%S.-)%s*$") size = tonumber(size) if abort == nil then -- no LOAD/RELOAD allowed inside start() if size > 0 then server:receive(size) end if sfile and sline then server:send("201 Started " .. sfile .. " " .. sline .. "\n") else server:send("200 OK 0\n") end else -- reset environment to allow required modules to load again -- remove those packages that weren't loaded when debugger started for k in pairs(package.loaded) do if not loaded[k] then package.loaded[k] = nil end end if size == 0 and name == '-' then -- RELOAD the current script being debugged server:send("200 OK 0\n") coroutine.yield("load") else -- receiving 0 bytes blocks (at least in luasocket 2.0.2), so skip reading local chunk = size == 0 and "" or server:receive(size) if chunk then -- LOAD a new script for debugging local func, res = loadstring(chunk, "@"..name) if func then server:send("200 OK 0\n") debugee = func coroutine.yield("load") else server:send("401 Error in Expression " .. #res .. "\n") server:send(res) end else server:send("400 Bad Request\n") end end end elseif command == "SETW" then local _, _, exp = string.find(line, "^[A-Z]+%s+(.+)%s*$") if exp then local func, res = loadstring("return(" .. exp .. ")") if func then watchescnt = watchescnt + 1 local newidx = #watches + 1 watches[newidx] = func server:send("200 OK " .. newidx .. "\n") else server:send("401 Error in Expression " .. #res .. "\n") server:send(res) end else server:send("400 Bad Request\n") end elseif command == "DELW" then local _, _, index = string.find(line, "^[A-Z]+%s+(%d+)%s*$") index = tonumber(index) if index > 0 and index <= #watches then watchescnt = watchescnt - (watches[index] ~= emptyWatch and 1 or 0) watches[index] = emptyWatch server:send("200 OK\n") else server:send("400 Bad Request\n") end elseif command == "RUN" then server:send("200 OK\n") local ev, vars, file, line, idx_watch = coroutine.yield() eval_env = vars if ev == events.BREAK then server:send("202 Paused " .. file .. " " .. line .. "\n") elseif ev == events.WATCH then server:send("203 Paused " .. file .. " " .. line .. " " .. idx_watch .. "\n") elseif ev == events.RESTART then -- nothing to do else server:send("401 Error in Execution " .. #file .. "\n") server:send(file) end elseif command == "STEP" then server:send("200 OK\n") step_into = true local ev, vars, file, line, idx_watch = coroutine.yield() eval_env = vars if ev == events.BREAK then server:send("202 Paused " .. file .. " " .. line .. "\n") elseif ev == events.WATCH then server:send("203 Paused " .. file .. " " .. line .. " " .. idx_watch .. "\n") elseif ev == events.RESTART then -- nothing to do else server:send("401 Error in Execution " .. #file .. "\n") server:send(file) end elseif command == "OVER" or command == "OUT" then server:send("200 OK\n") step_over = true -- OVER and OUT are very similar except for -- the stack level value at which to stop if command == "OUT" then step_level = stack_level - 1 else step_level = stack_level end local ev, vars, file, line, idx_watch = coroutine.yield() eval_env = vars if ev == events.BREAK then server:send("202 Paused " .. file .. " " .. line .. "\n") elseif ev == events.WATCH then server:send("203 Paused " .. file .. " " .. line .. " " .. idx_watch .. "\n") elseif ev == events.RESTART then -- nothing to do else server:send("401 Error in Execution " .. #file .. "\n") server:send(file) end elseif command == "BASEDIR" then local _, _, dir = string.find(line, "^[A-Z]+%s+(.+)%s*$") if dir then basedir = iscasepreserving and string.lower(dir) or dir -- reset cached source as it may change with basedir lastsource = nil server:send("200 OK\n") else server:send("400 Bad Request\n") end elseif command == "SUSPEND" then -- do nothing; it already fulfilled its role elseif command == "STACK" then -- first check if we can execute the stack command -- as it requires yielding back to debug_hook it cannot be executed -- if we have not seen the hook yet as happens after start(). -- in this case we simply return an empty result local vars, ev = {} if seen_hook then ev, vars = coroutine.yield("stack") end if ev and ev ~= events.STACK then server:send("401 Error in Execution " .. #vars .. "\n") server:send(vars) else local ok, res = pcall(serpent.dump, vars, {nocode = true, sparse = false}) if ok then server:send("200 OK " .. res .. "\n") else server:send("401 Error in Execution " .. #res .. "\n") server:send(res) end end elseif command == "OUTPUT" then local _, _, stream, mode = string.find(line, "^[A-Z]+%s+(%w+)%s+([dcr])%s*$") if stream and mode and stream == "stdout" then -- assign "print" in the global environment genv.print = mode == 'd' and iobase.print or coroutine.wrap(function(...) -- wrapping into coroutine.wrap protects this function from -- being stepped through in the debugger local tbl = {...} while true do if mode == 'c' then iobase.print(unpack(tbl)) end for n = 1, #tbl do tbl[n] = select(2, pcall(serpent.line, tbl[n], {nocode = true, comment = false})) end local file = table.concat(tbl, "\t").."\n" server:send("204 Output " .. stream .. " " .. #file .. "\n" .. file) tbl = {coroutine.yield()} end end) server:send("200 OK\n") else server:send("400 Bad Request\n") end elseif command == "EXIT" then server:send("200 OK\n") coroutine.yield("exit") else server:send("400 Bad Request\n") end end end local function connect(controller_host, controller_port) return (socket.connect4 or socket.connect)(controller_host, controller_port) end local function isrunning() return coro_debugger and coroutine.status(coro_debugger) == 'suspended' end local lasthost, lastport -- Starts a debug session by connecting to a controller local function start(controller_host, controller_port) -- only one debugging session can be run (as there is only one debug hook) if isrunning() then return end lasthost = controller_host or lasthost lastport = controller_port or lastport controller_host = lasthost or "localhost" controller_port = lastport or mobdebug.port local err server, err = (socket.connect4 or socket.connect)(controller_host, controller_port) if server then -- correct stack depth which already has some calls on it -- so it doesn't go into negative when those calls return -- as this breaks subsequence checks in stack_depth(). -- start from 16th frame, which is sufficiently large for this check. stack_level = stack_depth(16) -- provide our own traceback function to report the error remotely do local dtraceback = debug.traceback debug.traceback = function (...) if select('#', ...) >= 1 then local err, lvl = ... if err and type(err) ~= 'thread' then local trace = dtraceback(err, (lvl or 2)+1) if genv.print == iobase.print then -- no remote redirect return trace else genv.print(trace) -- report the error remotely return -- don't report locally to avoid double reporting end end end -- direct call to debug.traceback: return the original. -- debug.traceback(nil, level) doesn't work in Lua 5.1 -- (http://lua-users.org/lists/lua-l/2011-06/msg00574.html), so -- simply remove first frame from the stack trace return (dtraceback(...):gsub("(stack traceback:\n)[^\n]*\n", "%1")) end end coro_debugger = coroutine.create(debugger_loop) debug.sethook(debug_hook, "lcr") seen_hook = nil -- reset in case the last start() call was refused step_into = true -- start with step command return true else print(("Could not connect to %s:%s: %s") :format(controller_host, controller_port, err or "unknown error")) end end local function controller(controller_host, controller_port, scratchpad) -- only one debugging session can be run (as there is only one debug hook) if isrunning() then return end lasthost = controller_host or lasthost lastport = controller_port or lastport controller_host = lasthost or "localhost" controller_port = lastport or mobdebug.port local exitonerror = not scratchpad local err server, err = (socket.connect4 or socket.connect)(controller_host, controller_port) if server then local function report(trace, err) local msg = err .. "\n" .. trace server:send("401 Error in Execution " .. #msg .. "\n") server:send(msg) return err end seen_hook = true -- allow to accept all commands coro_debugger = coroutine.create(debugger_loop) while true do step_into = true -- start with step command abort = false -- reset abort flag from the previous loop if scratchpad then checkcount = mobdebug.checkcount end -- force suspend right away coro_debugee = coroutine.create(debugee) debug.sethook(coro_debugee, debug_hook, "lcr") local status, err = coroutine.resume(coro_debugee) -- was there an error or is the script done? -- 'abort' state is allowed here; ignore it if abort then if tostring(abort) == 'exit' then break end else if status then -- normal execution is done break elseif err and not tostring(err):find(deferror) then -- report the error back -- err is not necessarily a string, so convert to string to report report(debug.traceback(coro_debugee), tostring(err)) if exitonerror then break end -- resume once more to clear the response the debugger wants to send -- need to use capture_vars(2) as three would be the level of -- the caller for controller(), but because of the tail call, -- the caller may not exist; -- This is not entirely safe as the user may see the local -- variable from console, but they will be reset anyway. -- This functionality is used when scratchpad is paused to -- gain access to remote console to modify global variables. local status, err = coroutine.resume(coro_debugger, events.RESTART, capture_vars(2)) if not status or status and err == "exit" then break end end end end else print(("Could not connect to %s:%s: %s") :format(controller_host, controller_port, err or "unknown error")) return false end return true end local function scratchpad(controller_host, controller_port) return controller(controller_host, controller_port, true) end local function loop(controller_host, controller_port) return controller(controller_host, controller_port, false) end local function on() if not (isrunning() and server) then return end -- main is set to true under Lua5.2 for the "main" chunk. -- Lua5.1 returns co as `nil` in that case. local co, main = coroutine.running() if main then co = nil end if co then coroutines[co] = true debug.sethook(co, debug_hook, "lcr") else if jit then coroutines.main = true end debug.sethook(debug_hook, "lcr") end end local function off() if not (isrunning() and server) then return end -- main is set to true under Lua5.2 for the "main" chunk. -- Lua5.1 returns co as `nil` in that case. local co, main = coroutine.running() if main then co = nil end -- don't remove coroutine hook under LuaJIT as there is only one (global) hook if co then coroutines[co] = false if not jit then debug.sethook(co) end else if jit then coroutines.main = false end if not jit then debug.sethook() end end -- check if there is any thread that is still being debugged under LuaJIT; -- if not, turn the debugging off if jit then local remove = true for co, debugged in pairs(coroutines) do if debugged then remove = false; break end end if remove then debug.sethook() end end end -- Handles server debugging commands local function handle(params, client, options) local _, _, command = string.find(params, "^([a-z]+)") local file, line, watch_idx if command == "run" or command == "step" or command == "out" or command == "over" or command == "exit" then client:send(string.upper(command) .. "\n") client:receive() -- this should consume the first '200 OK' response while true do local done = true local breakpoint = client:receive() if not breakpoint then print("Program finished") os.exit() return -- use return here for those cases where os.exit() is not wanted end local _, _, status = string.find(breakpoint, "^(%d+)") if status == "200" then -- don't need to do anything elseif status == "202" then _, _, file, line = string.find(breakpoint, "^202 Paused%s+(.-)%s+(%d+)%s*$") if file and line then print("Paused at file " .. file .. " line " .. line) end elseif status == "203" then _, _, file, line, watch_idx = string.find(breakpoint, "^203 Paused%s+(.-)%s+(%d+)%s+(%d+)%s*$") if file and line and watch_idx then print("Paused at file " .. file .. " line " .. line .. " (watch expression " .. watch_idx .. ": [" .. watches[watch_idx] .. "])") end elseif status == "204" then local _, _, stream, size = string.find(breakpoint, "^204 Output (%w+) (%d+)$") if stream and size then local msg = client:receive(tonumber(size)) print(msg) if outputs[stream] then outputs[stream](msg) end -- this was just the output, so go back reading the response done = false end elseif status == "401" then local _, _, size = string.find(breakpoint, "^401 Error in Execution (%d+)$") if size then local msg = client:receive(tonumber(size)) print("Error in remote application: " .. msg) os.exit(1) return nil, nil, msg -- use return here for those cases where os.exit() is not wanted end else print("Unknown error") os.exit(1) -- use return here for those cases where os.exit() is not wanted return nil, nil, "Debugger error: unexpected response '" .. breakpoint .. "'" end if done then break end end elseif command == "setb" then _, _, _, file, line = string.find(params, "^([a-z]+)%s+(.-)%s+(%d+)%s*$") if file and line then -- if this is a file name, and not a file source if not file:find('^".*"$') then file = string.gsub(file, "\\", "/") -- convert slash file = removebasedir(file, basedir) end client:send("SETB " .. file .. " " .. line .. "\n") if client:receive() == "200 OK" then set_breakpoint(file, line) else print("Error: breakpoint not inserted") end else print("Invalid command") end elseif command == "setw" then local _, _, exp = string.find(params, "^[a-z]+%s+(.+)$") if exp then client:send("SETW " .. exp .. "\n") local answer = client:receive() local _, _, watch_idx = string.find(answer, "^200 OK (%d+)%s*$") if watch_idx then watches[watch_idx] = exp print("Inserted watch exp no. " .. watch_idx) else local _, _, size = string.find(answer, "^401 Error in Expression (%d+)$") if size then local err = client:receive(tonumber(size)):gsub(".-:%d+:%s*","") print("Error: watch expression not set: " .. err) else print("Error: watch expression not set") end end else print("Invalid command") end elseif command == "delb" then _, _, _, file, line = string.find(params, "^([a-z]+)%s+(.-)%s+(%d+)%s*$") if file and line then -- if this is a file name, and not a file source if not file:find('^".*"$') then file = string.gsub(file, "\\", "/") -- convert slash file = removebasedir(file, basedir) end client:send("DELB " .. file .. " " .. line .. "\n") if client:receive() == "200 OK" then remove_breakpoint(file, line) else print("Error: breakpoint not removed") end else print("Invalid command") end elseif command == "delallb" then for line, breaks in pairs(breakpoints) do for file, _ in pairs(breaks) do client:send("DELB " .. file .. " " .. line .. "\n") if client:receive() == "200 OK" then remove_breakpoint(file, line) else print("Error: breakpoint at file " .. file .. " line " .. line .. " not removed") end end end elseif command == "delw" then local _, _, index = string.find(params, "^[a-z]+%s+(%d+)%s*$") if index then client:send("DELW " .. index .. "\n") if client:receive() == "200 OK" then watches[index] = nil else print("Error: watch expression not removed") end else print("Invalid command") end elseif command == "delallw" then for index, exp in pairs(watches) do client:send("DELW " .. index .. "\n") if client:receive() == "200 OK" then watches[index] = nil else print("Error: watch expression at index " .. index .. " [" .. exp .. "] not removed") end end elseif command == "eval" or command == "exec" or command == "load" or command == "loadstring" or command == "reload" then local _, _, exp = string.find(params, "^[a-z]+%s+(.+)$") if exp or (command == "reload") then if command == "eval" or command == "exec" then exp = (exp:gsub("%-%-%[(=*)%[.-%]%1%]", "") -- remove comments :gsub("%-%-.-\n", " ") -- remove line comments :gsub("\n", " ")) -- convert new lines if command == "eval" then exp = "return " .. exp end client:send("EXEC " .. exp .. "\n") elseif command == "reload" then client:send("LOAD 0 -\n") elseif command == "loadstring" then local _, _, _, file, lines = string.find(exp, "^([\"'])(.-)%1%s+(.+)") if not file then _, _, file, lines = string.find(exp, "^(%S+)%s+(.+)") end client:send("LOAD " .. #lines .. " " .. file .. "\n") client:send(lines) else local file = io.open(exp, "r") if not file and pcall(require, "winapi") then -- if file is not open and winapi is there, try with a short path; -- this may be needed for unicode paths on windows winapi.set_encoding(winapi.CP_UTF8) file = io.open(winapi.short_path(exp), "r") end if not file then error("Cannot open file " .. exp) end -- read the file and remove the shebang line as it causes a compilation error local lines = file:read("*all"):gsub("^#!.-\n", "\n") file:close() local file = string.gsub(exp, "\\", "/") -- convert slash file = removebasedir(file, basedir) client:send("LOAD " .. #lines .. " " .. file .. "\n") if #lines > 0 then client:send(lines) end end while true do local params, err = client:receive() if not params then return nil, nil, "Debugger connection " .. (err or "error") end local done = true local _, _, status, len = string.find(params, "^(%d+).-%s+(%d+)%s*$") if status == "200" then len = tonumber(len) if len > 0 then local status, res local str = client:receive(len) -- handle serialized table with results local func, err = loadstring(str) if func then status, res = pcall(func) if not status then err = res elseif type(res) ~= "table" then err = "received "..type(res).." instead of expected 'table'" end end if err then print("Error in processing results: " .. err) return nil, nil, "Error in processing results: " .. err end print(unpack(res)) return res[1], res end elseif status == "201" then _, _, file, line = string.find(params, "^201 Started%s+(.-)%s+(%d+)%s*$") elseif status == "202" or params == "200 OK" then -- do nothing; this only happens when RE/LOAD command gets the response -- that was for the original command that was aborted elseif status == "204" then local _, _, stream, size = string.find(params, "^204 Output (%w+) (%d+)$") if stream and size then local msg = client:receive(tonumber(size)) print(msg) if outputs[stream] then outputs[stream](msg) end -- this was just the output, so go back reading the response done = false end elseif status == "401" then len = tonumber(len) local res = client:receive(len) print("Error in expression: " .. res) return nil, nil, res else print("Unknown error") return nil, nil, "Debugger error: unexpected response after EXEC/LOAD '" .. params .. "'" end if done then break end end else print("Invalid command") end elseif command == "listb" then for l, v in pairs(breakpoints) do for f in pairs(v) do print(f .. ": " .. l) end end elseif command == "listw" then for i, v in pairs(watches) do print("Watch exp. " .. i .. ": " .. v) end elseif command == "suspend" then client:send("SUSPEND\n") elseif command == "stack" then client:send("STACK\n") local resp = client:receive() local _, _, status, res = string.find(resp, "^(%d+)%s+%w+%s+(.+)%s*$") if status == "200" then local func, err = loadstring(res) if func == nil then print("Error in stack information: " .. err) return nil, nil, err end local ok, stack = pcall(func) if not ok then print("Error in stack information: " .. stack) return nil, nil, stack end for _,frame in ipairs(stack) do print(serpent.line(frame[1], {comment = false})) end return stack elseif status == "401" then local _, _, len = string.find(resp, "%s+(%d+)%s*$") len = tonumber(len) local res = len > 0 and client:receive(len) or "Invalid stack information." print("Error in expression: " .. res) return nil, nil, res else print("Unknown error") return nil, nil, "Debugger error: unexpected response after STACK" end elseif command == "output" then local _, _, stream, mode = string.find(params, "^[a-z]+%s+(%w+)%s+([dcr])%s*$") if stream and mode then client:send("OUTPUT "..stream.." "..mode.."\n") local resp = client:receive() local _, _, status = string.find(resp, "^(%d+)%s+%w+%s*$") if status == "200" then print("Stream "..stream.." redirected") outputs[stream] = type(options) == 'table' and options.handler or nil else print("Unknown error") return nil, nil, "Debugger error: can't redirect "..stream end else print("Invalid command") end elseif command == "basedir" then local _, _, dir = string.find(params, "^[a-z]+%s+(.+)$") if dir then dir = string.gsub(dir, "\\", "/") -- convert slash if not string.find(dir, "/$") then dir = dir .. "/" end local remdir = dir:match("\t(.+)") if remdir then dir = dir:gsub("/?\t.+", "/") end basedir = dir client:send("BASEDIR "..(remdir or dir).."\n") local resp = client:receive() local _, _, status = string.find(resp, "^(%d+)%s+%w+%s*$") if status == "200" then print("New base directory is " .. basedir) else print("Unknown error") return nil, nil, "Debugger error: unexpected response after BASEDIR" end else print(basedir) end elseif command == "help" then print("setb <file> <line> -- sets a breakpoint") print("delb <file> <line> -- removes a breakpoint") print("delallb -- removes all breakpoints") print("setw <exp> -- adds a new watch expression") print("delw <index> -- removes the watch expression at index") print("delallw -- removes all watch expressions") print("run -- runs until next breakpoint") print("step -- runs until next line, stepping into function calls") print("over -- runs until next line, stepping over function calls") print("out -- runs until line after returning from current function") print("listb -- lists breakpoints") print("listw -- lists watch expressions") print("eval <exp> -- evaluates expression on the current context and returns its value") print("exec <stmt> -- executes statement on the current context") print("load <file> -- loads a local file for debugging") print("reload -- restarts the current debugging session") print("stack -- reports stack trace") print("output stdout <d|c|r> -- capture and redirect io stream (default|copy|redirect)") print("basedir [<path>] -- sets the base path of the remote application, or shows the current one") print("exit -- exits debugger") else local _, _, spaces = string.find(params, "^(%s*)$") if not spaces then print("Invalid command") return nil, nil, "Invalid command" end end return file, line end -- Starts debugging server local function listen(host, port) host = host or "*" port = port or mobdebug.port local socket = require "socket" print("Lua Remote Debugger") print("Run the program you wish to debug") local server = socket.bind(host, port) local client = server:accept() client:send("STEP\n") client:receive() local breakpoint = client:receive() local _, _, file, line = string.find(breakpoint, "^202 Paused%s+(.-)%s+(%d+)%s*$") if file and line then print("Paused at file " .. file ) print("Type 'help' for commands") else local _, _, size = string.find(breakpoint, "^401 Error in Execution (%d+)%s*$") if size then print("Error in remote application: ") print(client:receive(size)) end end while true do io.write("> ") local line = io.read("*line") handle(line, client) end end local cocreate local function coro() if cocreate then return end -- only set once cocreate = cocreate or coroutine.create coroutine.create = function(f, ...) return cocreate(function(...) require("mobdebug").on() return f(...) end, ...) end end local moconew local function moai() if moconew then return end -- only set once moconew = moconew or (MOAICoroutine and MOAICoroutine.new) if not moconew then return end MOAICoroutine.new = function(...) local thread = moconew(...) -- need to support both thread.run and getmetatable(thread).run, which -- was used in earlier MOAI versions local mt = thread.run and thread or getmetatable(thread) local patched = mt.run mt.run = function(self, f, ...) return patched(self, function(...) require("mobdebug").on() return f(...) end, ...) end return thread end end -- this is a function that removes all hooks and closes the socket to -- report back to the controller that the debugging is done. -- the script that called `done` can still continue. local function done() if not (isrunning() and server) then return end if not jit then for co, debugged in pairs(coroutines) do if debugged then debug.sethook(co) end end end debug.sethook() server:close() coro_debugger = nil -- to make sure isrunning() returns `false` seen_hook = nil -- to make sure that the next start() call works abort = nil -- to make sure that callback calls use proper "abort" value end -- make public functions available mobdebug.listen = listen mobdebug.loop = loop mobdebug.scratchpad = scratchpad mobdebug.handle = handle mobdebug.connect = connect mobdebug.start = start mobdebug.on = on mobdebug.off = off mobdebug.moai = moai mobdebug.coro = coro mobdebug.done = done mobdebug.line = serpent.line mobdebug.dump = serpent.dump mobdebug.yield = nil -- callback -- this is needed to make "require 'modebug'" to work when mobdebug -- module is loaded manually package.loaded.mobdebug = mobdebug return mobdebug
apache-2.0
lighter-cd/premake4-mobile
src/tools/ow.lua
25
2158
-- -- ow.lua -- Provides Open Watcom-specific configuration strings. -- Copyright (c) 2008 Jason Perkins and the Premake project -- premake.ow = { } premake.ow.namestyle = "windows" -- -- Set default tools -- premake.ow.cc = "WCL386" premake.ow.cxx = "WCL386" premake.ow.ar = "ar" -- -- Translation of Premake flags into OpenWatcom flags -- local cflags = { ExtraWarnings = "-wx", FatalWarning = "-we", FloatFast = "-omn", FloatStrict = "-op", Optimize = "-ox", OptimizeSize = "-os", OptimizeSpeed = "-ot", Symbols = "-d2", } local cxxflags = { NoExceptions = "-xd", NoRTTI = "-xr", } -- -- No specific platform support yet -- premake.ow.platforms = { Native = { flags = "" }, } -- -- Returns a list of compiler flags, based on the supplied configuration. -- function premake.ow.getcppflags(cfg) return {} end function premake.ow.getcflags(cfg) local result = table.translate(cfg.flags, cflags) if (cfg.flags.Symbols) then table.insert(result, "-hw") -- Watcom debug format for Watcom debugger end return result end function premake.ow.getcxxflags(cfg) local result = table.translate(cfg.flags, cxxflags) return result end -- -- Returns a list of linker flags, based on the supplied configuration. -- function premake.ow.getldflags(cfg) local result = { } if (cfg.flags.Symbols) then table.insert(result, "op symf") end return result end -- -- Returns a list of linker flags for library search directories and -- library names. -- function premake.ow.getlinkflags(cfg) local result = { } return result end -- -- Decorate defines for the command line. -- function premake.ow.getdefines(defines) local result = { } for _,def in ipairs(defines) do table.insert(result, '-D' .. def) end return result end -- -- Decorate include file search paths for the command line. -- function premake.ow.getincludedirs(includedirs) local result = { } for _,dir in ipairs(includedirs) do table.insert(result, '-I "' .. dir .. '"') end return result end
mit
HybridDog/minetest-skyblock
skyblock/register_misc.lua
1
2191
--[[ Skyblock for Minetest Copyright (c) 2015 cornernote, Brett O'Donnell <cornernote@gmail.com> Source Code: https://github.com/cornernote/minetest-skyblock License: GPLv3 ]]-- -- set mapgen to singlenode minetest.register_on_mapgen_init(function(mgparams) minetest.set_mapgen_params({mgname='singlenode', water_level=-32000}) end) -- new player minetest.register_on_newplayer(function(player) -- spawn player skyblock.spawn_player(player) end) -- respawn player minetest.register_on_respawnplayer(function(player) -- unset old spawn position if skyblock.dig_new_spawn then local player_name = player:get_player_name() local spawn = skyblock.get_spawn(player_name) skyblock.set_spawn(player_name, nil) skyblock.set_spawn(player_name..'_DEAD', spawn) end -- spawn player skyblock.spawn_player(player) return true end) -- localization local y_bottom, c_acid -- register map generation minetest.register_on_generated(function(minp, maxp, seed) if not y_bottom then y_bottom = skyblock.world_bottom c_acid = minetest.get_content_id("skyblock:acid") end -- do not handle mapchunks which are too heigh or too low if minp.y > y_bottom then return end local vm, emin, emax = minetest.get_mapgen_object("voxelmanip") local data = vm:get_data() local area = VoxelArea:new{MinEdge=emin, MaxEdge=emax} -- avoid that liquids flown down spread if maxp.y >= y_bottom then for z = minp.z,maxp.z do for x = minp.x,maxp.x do if (z+x)%2 == 0 then data[area:index(x,y_bottom,z)] = c_acid end end end maxp.y = y_bottom-1 end -- the atmosphere is bad for Sam for p_pos in area:iterp(minp, maxp) do data[p_pos] = c_acid end -- add starting blocks --[[ local start_pos_list = skyblock.get_start_positions_in_mapchunk(minp, maxp) for _,pos in ipairs(start_pos_list) do skyblock.make_spawn_blocks_on_generated(pos, data, area) end ]]-- -- store the voxelmanip data vm:set_data(data) vm:calc_lighting(emin,emax) vm:write_to_map(data) vm:update_liquids() end) -- no placing low nodes minetest.register_on_placenode(function(pos) if pos.y < y_bottom then minetest.remove_node(pos) return true -- give back item end end)
gpl-3.0
Javaxio/BadRotations
System/UI/Windows/Config.lua
1
9250
-- This creates the normal BadBay Configuration Window br.ui.window.config = {} function br.ui:createConfigWindow() br.ui.window.config = br.ui:createWindow("config", 275, 400,"Configuration") local section local function callGeneral() -- General section = br.ui:createSection(br.ui.window.config, "General") br.ui:createCheckbox(section, "Auto Delay", "Check to dynamically change update rate based on current FPS.") br.ui:createSpinnerWithout(section, "Bot Update Rate", 0.1, 0.0, 1.0, 0.01, "Adjust the update rate of Bot operations. Increase to improve FPS but may cause reaction delays. Default: 0.1") -- br.ui:createSpinnerWithout(section, "Dynamic Target Rate", 0.5, 0.5, 2.0, 0.01, "Adjusts the rate at which enemies are cycled for new dynamic targets. Default: 0.5") -- As you should use the toggle to stop, i (defmaster) just activated this toggle default and made it non interactive local startStop = br.ui:createCheckbox(section, "Start/Stop BadRotations", "Toggle this option from the Toggle Bar (Shift Left Click on the Minimap Icon."); startStop:SetChecked(true); br.data.settings[br.selectedSpec][br.selectedProfile]["Start/Stop BadRotationsCheck"] = true; startStop.frame:Disable() -- br.ui:createCheckbox(section, "Start/Stop BadRotations", "Uncheck to prevent BadRotations pulsing."); rotationLog = br.ui:createCheckbox(section, "Rotation Log", "Display Rotation Log."); -- br.ui:createCheckbox(section, "Rotation Log", "Display Rotation Log.") br.ui:createCheckbox(section, "Display Failcasts", "Dispaly Failcasts in Debug.") br.ui:createCheckbox(section, "Queue Casting", "Allow Queue Casting on some profiles.") br.ui:createSpinner(section, "Auto Loot" ,0.5, 0.1, 3, 0.1, "Sets Autloot on/off.", "Sets a delay for Auto Loot.") br.ui:createCheckbox(section, "Auto-Sell/Repair", "Automatically sells grays and repairs when you open a repair vendor.") br.ui:createCheckbox(section, "Accept Queues", "Automatically accept LFD, LFR, .. queue.") br.ui:createCheckbox(section, "Overlay Messages", "Check to enable chat overlay messages.") br.ui:createCheckbox(section, "Talent Anywhere", "Check to enable swapping of talents outside of rest areas.") br.ui:createSpinner(section, "Notify Not Unlocked", 10, 5, 60, 5, "Will alert you at the set interval when FireHack or EWT is not attached.") br.ui:createCheckbox(section, "Reset Options", "|cffFF0000 WARNING!|cffFFFFFF Checking this will reset setting on reload!") br.ui:createCheckbox(section, "Reset Saved Profiles", "|cffFF0000 WARNING!|cffFFFFFF Checking this will reset saved profiles on reload!") br.ui:checkSectionState(section) end local function callEnemiesEngine() -- Enemies Engine section = br.ui:createSection(br.ui.window.config, "Enemies Engine") br.ui:createDropdown(section, "Dynamic Targetting", {"Only In Combat", "Default"}, 2, "Check this to allow dynamic targetting. If unchecked, profile will only attack current target.") br.ui:createCheckbox(section, "Target Dynamic Target", "Check this will target the current dynamic target.") br.ui:createCheckbox(section, "Hostiles Only", "Checking this will target only units hostile to you.") br.ui:createDropdown(section, "Wise Target", {"Highest", "Lowest", "abs Highest", "Nearest", "Furthest"}, 1, "|cffFFDD11Check if you want to use Wise Targetting, if unchecked there will be no priorisation from hp/range.") br.ui:createCheckbox(section, "Forced Burn", "Check to allow forced Burn on specific whitelisted units.") br.ui:createCheckbox(section, "Avoid Shields", "Check to avoid attacking shielded units.") br.ui:createCheckbox(section, "Tank Threat", "Check add more priority to taregts you lost aggro on(tank only).") br.ui:createCheckbox(section, "Safe Damage Check", "Check to prevent damage to targets you dont want to attack.") br.ui:createCheckbox(section, "Don't break CCs", "Check to prevent damage to targets that are CC.") br.ui:createCheckbox(section, "Skull First", "Check to enable focus skull dynamically.") br.ui:createCheckbox(section, "Interrupt Only Whitelist", "Check to only interrupt casts listed on the whitelist.") br.ui:createDropdown(section, "Interrupts Handler", {"Target", "T/M", "T/M/F", "All"}, 1, "Check this to allow Interrupts Handler. DO NOT USE YET!") br.ui:createCheckbox(section, "Only Known Units", "Check this to interrupt only on known units using whitelist.") br.ui:createCheckbox(section, "Crowd Control", "Check to use crowd controls on select units/buffs.") br.ui:createCheckbox(section, "Enrages Handler", "Check this to allow Enrages Handler.") br.ui:checkSectionState(section) end local function callHealingEngine() -- Healing Engine section = br.ui:createSection(br.ui.window.config, "Healing Engine") br.ui:createCheckbox(section, "HE Active", "Uncheck to disable Healing Engine.\nCan improves FPS if you dont rely on Healing Engine.") br.ui:createCheckbox(section, "Heal Pets", "Check this to Heal Pets.") br.ui:createDropdown(section, "Special Heal", {"Target", "T/M", "T/M/F", "T/F"}, 1, "Check this to Heal Special Whitelisted Units.", "Choose who you want to Heal.") br.ui:createCheckbox(section, "Sorting with Role", "Sorting with Role") br.ui:createDropdown(section, "Prioritize Special Targets", {"Special", "All"}, 1, "Prioritize Special targets(mouseover/target/focus).", "Choose Which Special Units to consider.") br.ui:createSpinner(section, "Blacklist", 95, nil, nil, nil, "|cffFFBB00How much |cffFF0000%HP|cffFFBB00 do we want to add to |cffFFDD00Blacklisted |cffFFBB00units. Use /Blacklist while mouse-overing someone to add it to the black list.") br.ui:createSpinner(section, "Prioritize Tank", 5, 0, 100, 1, "Check this to give tanks more priority") br.ui:createSpinner(section, "Prioritize Debuff", 3, 0, 100, 1, "Check this to give debuffed targets more priority") br.ui:createCheckbox(section, "Ignore Absorbs", "Check this if you want to ignore absorb shields. If checked, it will add shieldBuffValue/4 to hp. May end up as overheals, disable to save mana.") br.ui:createCheckbox(section, "Incoming Heals", "If checked, it will add incoming health from other healers to hp. Check this if you want to prevent overhealing units.") br.ui:createSpinner(section, "Overhealing Cancel", 95, nil, nil, nil, "Set Desired Threshold at which you want to prevent your own casts. CURRENTLY NOT IMPLEMENTED!") --healingDebug = br.ui:createCheckbox(section, "Healing Debug", "Check to display Healing Engine Debug.") --br.ui:createSpinner(section, "Debug Refresh", 500, 0, 1000, 25, "Set desired Healing Engine Debug Table refresh for rate in ms.") br.ui:createSpinner(section, "Dispel delay", 15, 5, 90, 5, "Set desired dispel delay in % of debuff duration.\n|cffFF0000Will randomise around the value you set.") br.ui:createCheckbox(section, "Healer Line of Sight Indicator", "Draws a line to healers. Green In Line of Sight / Red Not In Line of Sight") br.ui:checkSectionState(section) end local function callOtherFeaturesEngine() -- Other Features section = br.ui:createSection(br.ui.window.config, "Other Features") br.ui:createSpinner(section, "Profession Helper", 0.5, 0, 1, 0.1, "Check to enable Professions Helper.", "Set Desired Recast Delay.") br.ui:createDropdown(section, "Prospect Ores", {"Legion","WoD", "MoP", "Cata", "All"}, 1, "Prospect Desired Ores.") br.ui:createDropdown(section, "Mill Herbs", {"Legion","WoD", "MoP", "Cata", "All"}, 1, "Mill Desired Herbs.") br.ui:createCheckbox(section, "Disenchant", "Disenchant Cata blues/greens.") br.ui:createCheckbox(section, "Leather Scraps", "Combine leather scraps.") br.ui:createCheckbox(section, "Lockboxes", "Unlock Lockboxes.") br.ui:checkSectionState(section) end local function callSettingsEngine() section = br.ui:createSection(br.ui.window.config, "Save/Load Settings") br.ui:createDropdownWithout(section, "Settings to Load", {"Dungeons", "Mythic Dungeons", "Raids", "Mythic Raids"}, 1, "Select Profile to Load.") br.ui:createSaveButton(section, "Save", 40, -40) br.ui:createLoadButton(section, "Load", 140, -40) br.ui:checkSectionState(section) end -- Add Page Dropdown br.ui:createPagesDropdown(br.ui.window.config, { { [1] = "General", [2] = callGeneral, }, { [1] = "Enemies Engine", [2] = callEnemiesEngine, }, { [1] = "Healing Engine", [2] = callHealingEngine, }, { [1] = "Other Features", [2] = callOtherFeaturesEngine, }, { [1] = "Save/Load Settings", [2] = callSettingsEngine, }, }) br.ui:checkWindowStatus("config") end
gpl-3.0
xdemolish/darkstar
scripts/globals/mobskills/Thundris_Shriek.lua
6
1047
--------------------------------------------- -- Thundris Shriek -- -- Description: Deals heavy lightning damage to targets in area of effect. Additional effect: Terror -- Type: Magical -- Utsusemi/Blink absorb: Wipes shadows -- Range: Unknown -- Notes: Players will begin to be intimidated by the dvergr after this attack. --------------------------------------------- require("/scripts/globals/settings"); require("/scripts/globals/status"); require("/scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local typeEffect = EFFECT_TERROR; MobStatusEffectMove(mob, target, typeEffect, 1, 0, 60); local dmgmod = 1; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,ELE_THUNDER,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_THUNDER,MOBPARAM_WIPE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
kozinalexey/ardupilot_f4by_12out
Tools/CHDK-Scripts/kap_uav.lua
183
28512
--[[ KAP UAV Exposure Control Script v3.1 -- Released under GPL by waterwingz and wayback/peabody http://chdk.wikia.com/wiki/KAP_%26_UAV_Exposure_Control_Script @title KAP UAV 3.1 @param i Shot Interval (sec) @default i 15 @range i 2 120 @param s Total Shots (0=infinite) @default s 0 @range s 0 10000 @param j Power off when done? @default j 0 @range j 0 1 @param e Exposure Comp (stops) @default e 6 @values e -2.0 -1.66 -1.33 -1.0 -0.66 -0.33 0.0 0.33 0.66 1.00 1.33 1.66 2.00 @param d Start Delay Time (sec) @default d 0 @range d 0 10000 @param y Tv Min (sec) @default y 0 @values y None 1/60 1/100 1/200 1/400 1/640 @param t Target Tv (sec) @default t 5 @values t 1/100 1/200 1/400 1/640 1/800 1/1000 1/1250 1/1600 1/2000 @param x Tv Max (sec) @default x 3 @values x 1/1000 1/1250 1/1600 1/2000 1/5000 1/10000 @param f Av Low(f-stop) @default f 4 @values f 1.8 2.0 2.2 2.6 2.8 3.2 3.5 4.0 4.5 5.0 5.6 6.3 7.1 8.0 @param a Av Target (f-stop) @default a 7 @values a 1.8 2.0 2.2 2.6 2.8 3.2 3.5 4.0 4.5 5.0 5.6 6.3 7.1 8.0 @param m Av Max (f-stop) @default m 13 @values m 1.8 2.0 2.2 2.6 2.8 3.2 3.5 4.0 4.5 5.0 5.6 6.3 7.1 8.0 @param p ISO Min @default p 1 @values p 80 100 200 400 800 1250 1600 @param q ISO Max1 @default q 2 @values q 100 200 400 800 1250 1600 @param r ISO Max2 @default r 3 @values r 100 200 400 800 1250 1600 @param n Allow use of ND filter? @default n 1 @values n No Yes @param z Zoom position @default z 0 @values z Off 0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100% @param c Focus @ Infinity Mode @default c 0 @values c None @Shot AFL MF @param v Video Interleave (shots) @default v 0 @values v Off 1 5 10 25 50 100 @param w Video Duration (sec) @default w 10 @range w 5 300 @param u USB Shot Control? @default u 0 @values u None On/Off OneShot PWM @param b Backlight Off? @default b 0 @range b 0 1 @param l Logging @default l 3 @values l Off Screen SDCard Both --]] props=require("propcase") capmode=require("capmode") -- convert user parameter to usable variable names and values tv_table = { -320, 576, 640, 736, 832, 896, 928, 960, 992, 1024, 1056, 1180, 1276} tv96target = tv_table[t+3] tv96max = tv_table[x+8] tv96min = tv_table[y+1] sv_table = { 381, 411, 507, 603, 699, 761, 795 } sv96min = sv_table[p+1] sv96max1 = sv_table[q+2] sv96max2 = sv_table[r+2] av_table = { 171, 192, 218, 265, 285, 322, 347, 384, 417, 446, 477, 510, 543, 576 } av96target = av_table[a+1] av96minimum = av_table[f+1] av96max = av_table[m+1] ec96adjust = (e - 6)*32 video_table = { 0, 1, 5, 10, 25, 50, 100 } video_mode = video_table[v+1] video_duration = w interval = i*1000 max_shots = s poff_if_done = j start_delay = d backlight = b log_mode= l focus_mode = c usb_mode = u if ( z==0 ) then zoom_setpoint = nil else zoom_setpoint = (z-1)*10 end -- initial configuration values nd96offset=3*96 -- ND filter's number of equivalent f-stops (f * 96) infx = 50000 -- focus lock distance in mm (approximately 55 yards) shot_count = 0 -- shot counter blite_timer = 300 -- backlight off delay in 100mSec increments old_console_timeout = get_config_value( 297 ) shot_request = false -- pwm mode flag to request a shot be taken -- check camera Av configuration ( variable aperture and/or ND filter ) if n==0 then -- use of nd filter allowed? if get_nd_present()==1 then -- check for ND filter only Av_mode = 0 -- 0 = ND disabled and no iris available else Av_mode = 1 -- 1 = ND disabled and iris available end else Av_mode = get_nd_present()+1 -- 1 = iris only , 2=ND filter only, 3= both ND & iris end function printf(...) if ( log_mode == 0) then return end local str=string.format(...) if (( log_mode == 1) or (log_mode == 3)) then print(str) end if ( log_mode > 1 ) then local logname="A/KAP.log" log=io.open(logname,"a") log:write(os.date("%Y%b%d %X ")..string.format(...),"\n") log:close() end end tv_ref = { -- note : tv_ref values set 1/2 way between shutter speed values -608, -560, -528, -496, -464, -432, -400, -368, -336, -304, -272, -240, -208, -176, -144, -112, -80, -48, -16, 16, 48, 80, 112, 144, 176, 208, 240, 272, 304, 336, 368, 400, 432, 464, 496, 528, 560, 592, 624, 656, 688, 720, 752, 784, 816, 848, 880, 912, 944, 976, 1008, 1040, 1072, 1096, 1129, 1169, 1192, 1225, 1265, 1376 } tv_str = { ">64", "64", "50", "40", "32", "25", "20", "16", "12", "10", "8.0", "6.0", "5.0", "4.0", "3.2", "2.5", "2.0", "1.6", "1.3", "1.0", "0.8", "0.6", "0.5", "0.4", "0.3", "1/4", "1/5", "1/6", "1/8", "1/10", "1/13", "1/15", "1/20", "1/25", "1/30", "1/40", "1/50", "1/60", "1/80", "1/100", "1/125", "1/160", "1/200", "1/250", "1/320", "1/400", "1/500", "1/640", "1/800", "1/1000","1/1250", "1/1600","1/2000","1/2500","1/3200","1/4000","1/5000","1/6400","1/8000","1/10000","hi" } function print_tv(val) if ( val == nil ) then return("-") end local i = 1 while (i <= #tv_ref) and (val > tv_ref[i]) do i=i+1 end return tv_str[i] end av_ref = { 160, 176, 208, 243, 275, 304, 336, 368, 400, 432, 464, 480, 496, 512, 544, 592, 624, 656, 688, 720, 752, 784 } av_str = {"n/a","1.8", "2.0","2.2","2.6","2.8","3.2","3.5","4.0","4.5","5.0","5.6","5.9","6.3","7.1","8.0","9.0","10.0","11.0","13.0","14.0","16.0","hi"} function print_av(val) if ( val == nil ) then return("-") end local i = 1 while (i <= #av_ref) and (val > av_ref[i]) do i=i+1 end return av_str[i] end sv_ref = { 370, 397, 424, 456, 492, 523, 555, 588, 619, 651, 684, 731, 779, 843, 907 } sv_str = {"n/a","80","100","120","160","200","250","320","400","500","640","800","1250","1600","3200","hi"} function print_sv(val) if ( val == nil ) then return("-") end local i = 1 while (i <= #sv_ref) and (val > sv_ref[i]) do i=i+1 end return sv_str[i] end function pline(message, line) -- print line function fg = 258 bg=259 end -- switch between shooting and playback modes function switch_mode( m ) if ( m == 1 ) then if ( get_mode() == false ) then set_record(1) -- switch to shooting mode while ( get_mode() == false ) do sleep(100) end sleep(1000) end else if ( get_mode() == true ) then set_record(0) -- switch to playback mode while ( get_mode() == true ) do sleep(100) end sleep(1000) end end end -- focus lock and unlock function lock_focus() if (focus_mode > 1) then -- focus mode requested ? if ( focus_mode == 2 ) then -- method 1 : set_aflock() command enables MF if (chdk_version==120) then set_aflock(1) set_prop(props.AF_LOCK,1) else set_aflock(1) end if (get_prop(props.AF_LOCK) == 1) then printf(" AFL enabled") else printf(" AFL failed ***") end else -- mf mode requested if (chdk_version==120) then -- CHDK 1.2.0 : call event proc or levents to try and enable MF mode if call_event_proc("SS.Create") ~= -1 then if call_event_proc("SS.MFOn") == -1 then call_event_proc("PT_MFOn") end elseif call_event_proc("RegisterShootSeqEvent") ~= -1 then if call_event_proc("PT_MFOn") == -1 then call_event_proc("MFOn") end end if (get_prop(props.FOCUS_MODE) == 0 ) then -- MF not set - try levent PressSw1AndMF post_levent_for_npt("PressSw1AndMF") sleep(500) end elseif (chdk_version >= 130) then -- CHDK 1.3.0 : set_mf() if ( set_mf(1) == 0 ) then set_aflock(1) end -- as a fall back, try setting AFL is set_mf fails end if (get_prop(props.FOCUS_MODE) == 1) then printf(" MF enabled") else printf(" MF enable failed ***") end end sleep(1000) set_focus(infx) sleep(1000) end end function unlock_focus() if (focus_mode > 1) then -- focus mode requested ? if (focus_mode == 2 ) then -- method 1 : AFL if (chdk_version==120) then set_aflock(0) set_prop(props.AF_LOCK,0) else set_aflock(0) end if (get_prop(props.AF_LOCK) == 0) then printf(" AFL unlocked") else printf(" AFL unlock failed") end else -- mf mode requested if (chdk_version==120) then -- CHDK 1.2.0 : call event proc or levents to try and enable MF mode if call_event_proc("SS.Create") ~= -1 then if call_event_proc("SS.MFOff") == -1 then call_event_proc("PT_MFOff") end elseif call_event_proc("RegisterShootSeqEvent") ~= -1 then if call_event_proc("PT_MFOff") == -1 then call_event_proc("MFOff") end end if (get_prop(props.FOCUS_MODE) == 1 ) then -- MF not reset - try levent PressSw1AndMF post_levent_for_npt("PressSw1AndMF") sleep(500) end elseif (chdk_version >= 130) then -- CHDK 1.3.0 : set_mf() if ( set_mf(0) == 0 ) then set_aflock(0) end -- fall back so reset AFL is set_mf fails end if (get_prop(props.FOCUS_MODE) == 0) then printf(" MF disabled") else printf(" MF disable failed") end end sleep(100) end end -- zoom position function update_zoom(zpos) local count = 0 if(zpos ~= nil) then zstep=((get_zoom_steps()-1)*zpos)/100 printf("setting zoom to "..zpos.." percent step="..zstep) sleep(200) set_zoom(zstep) sleep(2000) press("shoot_half") repeat sleep(100) count = count + 1 until (get_shooting() == true ) or (count > 40 ) release("shoot_half") end end -- restore camera settings on shutdown function restore() set_config_value(121,0) -- USB remote disable set_config_value(297,old_console_timeout) -- restore console timeout value if (backlight==1) then set_lcd_display(1) end -- display on unlock_focus() if( zoom_setpoint ~= nil ) then update_zoom(0) end if( shot_count >= max_shots) and ( max_shots > 1) then if ( poff_if_done == 1 ) then -- did script ending because # of shots done ? printf("power off - shot count at limit") -- complete power down sleep(2000) post_levent_to_ui('PressPowerButton') else set_record(0) end -- just retract lens end end -- Video mode function check_video(shot) local capture_mode if ((video_mode>0) and(shot>0) and (shot%video_mode == 0)) then unlock_focus() printf("Video mode started. Button:"..tostring(video_button)) if( video_button ) then click "video" else capture_mode=capmode.get() capmode.set('VIDEO_STD') press("shoot_full") sleep(300) release("shoot_full") end local end_second = get_day_seconds() + video_duration repeat wait_click(500) until (is_key("menu")) or (get_day_seconds() > end_second) if( video_button ) then click "video" else press("shoot_full") sleep(300) release("shoot_full") capmode.set(capture_mode) end printf("Video mode finished.") sleep(1000) lock_focus() return(true) else return(false) end end -- PWM USB pulse functions function ch1up() printf(" * usb pulse = ch1up") shot_request = true end function ch1mid() printf(" * usb pulse = ch1mid") if ( get_mode() == false ) then switch_mode(1) lock_focus() end end function ch1down() printf(" * usb pulse = ch1down") switch_mode(0) end function ch2up() printf(" * usb pulse = ch2up") update_zoom(100) end function ch2mid() printf(" * usb pulse = ch2mid") if ( zoom_setpoint ~= nil ) then update_zoom(zoom_setpoint) else update_zoom(50) end end function ch2down() printf(" * usb pulse = ch2down") update_zoom(0) end function pwm_mode(pulse_width) if pulse_width > 0 then if pulse_width < 5 then ch1up() elseif pulse_width < 8 then ch1mid() elseif pulse_width < 11 then ch1down() elseif pulse_width < 14 then ch2up() elseif pulse_width < 17 then ch2mid() elseif pulse_width < 20 then ch2down() else printf(" * usb pulse width error") end end end -- Basic exposure calculation using shutter speed and ISO only -- called for Tv-only and ND-only cameras (cameras without an iris) function basic_tv_calc() tv96setpoint = tv96target av96setpoint = nil local min_av = get_prop(props.MIN_AV) -- calculate required ISO setting sv96setpoint = tv96setpoint + min_av - bv96meter -- low ambient light ? if (sv96setpoint > sv96max2 ) then -- check if required ISO setting is too high sv96setpoint = sv96max2 -- clamp at max2 ISO if so tv96setpoint = math.max(bv96meter+sv96setpoint-min_av,tv96min) -- recalculate required shutter speed down to Tv min -- high ambient light ? elseif (sv96setpoint < sv96min ) then -- check if required ISO setting is too low sv96setpoint = sv96min -- clamp at minimum ISO setting if so tv96setpoint = bv96meter + sv96setpoint - min_av -- recalculate required shutter speed and hope for the best end end -- Basic exposure calculation using shutter speed, iris and ISO -- called for iris-only and "both" cameras (cameras with an iris & ND filter) function basic_iris_calc() tv96setpoint = tv96target av96setpoint = av96target -- calculate required ISO setting sv96setpoint = tv96setpoint + av96setpoint - bv96meter -- low ambient light ? if (sv96setpoint > sv96max1 ) then -- check if required ISO setting is too high sv96setpoint = sv96max1 -- clamp at first ISO limit av96setpoint = bv96meter + sv96setpoint - tv96setpoint -- calculate new aperture setting if ( av96setpoint < av96min ) then -- check if new setting is goes below lowest f-stop av96setpoint = av96min -- clamp at lowest f-stop sv96setpoint = tv96setpoint + av96setpoint - bv96meter -- recalculate ISO setting if (sv96setpoint > sv96max2 ) then -- check if the result is above max2 ISO sv96setpoint = sv96max2 -- clamp at highest ISO setting if so tv96setpoint = math.max(bv96meter+sv96setpoint-av96setpoint,tv96min) -- recalculate required shutter speed down to tv minimum end end -- high ambient light ? elseif (sv96setpoint < sv96min ) then -- check if required ISO setting is too low sv96setpoint = sv96min -- clamp at minimum ISO setting if so tv96setpoint = bv96meter + sv96setpoint - av96setpoint -- recalculate required shutter speed if (tv96setpoint > tv96max ) then -- check if shutter speed now too fast tv96setpoint = tv96max -- clamp at maximum shutter speed if so av96setpoint = bv96meter + sv96setpoint - tv96setpoint -- calculate new aperture setting if ( av96setpoint > av96max ) then -- check if new setting is goes above highest f-stop av96setpoint = av96max -- clamp at highest f-stop tv96setpoint = bv96meter + sv96setpoint - av96setpoint -- recalculate shutter speed needed and hope for the best end end end end -- calculate exposure for cams without adjustable iris or ND filter function exposure_Tv_only() insert_ND_filter = nil basic_tv_calc() end -- calculate exposure for cams with ND filter only function exposure_NDfilter() insert_ND_filter = false basic_tv_calc() if (tv96setpoint > tv96max ) then -- check if shutter speed now too fast insert_ND_filter = true -- flag the ND filter to be inserted bv96meter = bv96meter - nd96offset -- adjust meter for ND offset basic_tv_calc() -- start over, but with new meter value bv96meter = bv96meter + nd96offset -- restore meter for later logging end end -- calculate exposure for cams with adjustable iris only function exposure_iris() insert_ND_filter = nil basic_iris_calc() end -- calculate exposure for cams with both adjustable iris and ND filter function exposure_both() insert_ND_filter = false -- NOTE : assume ND filter never used automatically by Canon firmware basic_iris_calc() if (tv96setpoint > tv96max ) then -- check if shutter speed now too fast insert_ND_filter = true -- flag the ND filter to be inserted bv96meter = bv96meter - nd96offset -- adjust meter for ND offset basic_iris_calc() -- start over, but with new meter value bv96meter = bv96meter + nd96offset -- restore meter for later logging end end -- ========================== Main Program ================================= set_console_layout(1 ,1, 45, 14 ) printf("KAP 3.1 started - press MENU to exit") bi=get_buildinfo() printf("%s %s-%s %s %s %s", bi.version, bi.build_number, bi.build_revision, bi.platform, bi.platsub, bi.build_date) chdk_version= tonumber(string.sub(bi.build_number,1,1))*100 + tonumber(string.sub(bi.build_number,3,3))*10 + tonumber(string.sub(bi.build_number,5,5)) if ( tonumber(bi.build_revision) > 0 ) then build = tonumber(bi.build_revision) else build = tonumber(string.match(bi.build_number,'-(%d+)$')) end if ((chdk_version<120) or ((chdk_version==120)and(build<3276)) or ((chdk_version==130)and(build<3383))) then printf("CHDK 1.2.0 build 3276 or higher required") else if( props.CONTINUOUS_AF == nil ) then caf=-999 else caf = get_prop(props.CONTINUOUS_AF) end if( props.SERVO_AF == nil ) then saf=-999 else saf = get_prop(props.SERVO_AF) end cmode = capmode.get_name() printf("Mode:%s,Continuous_AF:%d,Servo_AF:%d", cmode,caf,saf) printf(" Tv:"..print_tv(tv96target).." max:"..print_tv(tv96max).." min:"..print_tv(tv96min).." ecomp:"..(ec96adjust/96).."."..(math.abs(ec96adjust*10/96)%10) ) printf(" Av:"..print_av(av96target).." minAv:"..print_av(av96minimum).." maxAv:"..print_av(av96max) ) printf(" ISOmin:"..print_sv(sv96min).." ISO1:"..print_sv(sv96max1).." ISO2:"..print_sv(sv96max2) ) printf(" MF mode:"..focus_mode.." Video:"..video_mode.." USB:"..usb_mode) printf(" AvM:"..Av_mode.." int:"..(interval/1000).." Shts:"..max_shots.." Dly:"..start_delay.." B/L:"..backlight) sleep(500) if (start_delay > 0 ) then printf("entering start delay of ".. start_delay.." seconds") sleep( start_delay*1000 ) end -- enable USB remote in USB remote moded if (usb_mode > 0 ) then set_config_value(121,1) -- make sure USB remote is enabled if (get_usb_power(1) == 0) then -- can we start ? printf("waiting on USB signal") repeat wait_click(20) until ((get_usb_power(1) == 1) or ( is_key("menu"))) else sleep(1000) end printf("USB signal received") end -- switch to shooting mode switch_mode(1) -- set zoom position update_zoom(zoom_setpoint) -- lock focus at infinity lock_focus() -- disable flash and AF assist lamp set_prop(props.FLASH_MODE, 2) -- flash off set_prop(props.AF_ASSIST_BEAM,0) -- AF assist off if supported for this camera set_config_value( 297, 60) -- set console timeout to 60 seconds if (usb_mode > 2 ) then repeat until (get_usb_power(2) == 0 ) end -- flush pulse buffer next_shot_time = get_tick_count() script_exit = false if( get_video_button() == 1) then video_button = true else video_button = false end set_console_layout(2 ,0, 45, 4 ) repeat if( ( (usb_mode < 2 ) and ( next_shot_time <= get_tick_count() ) ) or ( (usb_mode == 2 ) and (get_usb_power(2) > 0 ) ) or ( (usb_mode == 3 ) and (shot_request == true ) ) ) then -- time to insert a video sequence ? if( check_video(shot_count) == true) then next_shot_time = get_tick_count() end -- intervalometer timing next_shot_time = next_shot_time + interval -- set focus at infinity ? (maybe redundant for AFL & MF mode but makes sure its set right) if (focus_mode > 0) then set_focus(infx) sleep(100) end -- check exposure local count = 0 local timeout = false press("shoot_half") repeat sleep(50) count = count + 1 if (count > 40 ) then timeout = true end until (get_shooting() == true ) or (timeout == true) -- shoot in auto mode if meter reading invalid, else calculate new desired exposure if ( timeout == true ) then release("shoot_half") repeat sleep(50) until get_shooting() == false shoot() -- shoot in Canon auto mode if we don't have a valid meter reading shot_count = shot_count + 1 printf(string.format('IMG_%04d.JPG',get_exp_count()).." : shot in auto mode, meter reading invalid") else -- get meter reading values (and add in exposure compensation) bv96raw=get_bv96() bv96meter=bv96raw-ec96adjust tv96meter=get_tv96() av96meter=get_av96() sv96meter=get_sv96() -- set minimum Av to larger of user input or current min for zoom setting av96min= math.max(av96minimum,get_prop(props.MIN_AV)) if (av96target < av96min) then av96target = av96min end -- calculate required setting for current ambient light conditions if (Av_mode == 1) then exposure_iris() elseif (Av_mode == 2) then exposure_NDfilter() elseif (Av_mode == 3) then exposure_both() else exposure_Tv_only() end -- set up all exposure overrides set_tv96_direct(tv96setpoint) set_sv96(sv96setpoint) if( av96setpoint ~= nil) then set_av96_direct(av96setpoint) end if(Av_mode > 1) and (insert_ND_filter == true) then -- ND filter available and needed? set_nd_filter(1) -- activate the ND filter nd_string="NDin" else set_nd_filter(2) -- make sure the ND filter does not activate nd_string="NDout" end -- and finally shoot the image press("shoot_full_only") sleep(100) release("shoot_full") repeat sleep(50) until get_shooting() == false shot_count = shot_count + 1 -- update shooting statistic and log as required shot_focus=get_focus() if(shot_focus ~= -1) and (shot_focus < 20000) then focus_string=" foc:"..(shot_focus/1000).."."..(((shot_focus%1000)+50)/100).."m" if(focus_mode>0) then error_string=" **WARNING : focus not at infinity**" end else focus_string=" foc:infinity" error_string=nil end printf(string.format('%d) IMG_%04d.JPG',shot_count,get_exp_count())) printf(" meter : Tv:".. print_tv(tv96meter) .." Av:".. print_av(av96meter) .." Sv:"..print_sv(sv96meter).." "..bv96raw ..":"..bv96meter) printf(" actual: Tv:".. print_tv(tv96setpoint).." Av:".. print_av(av96setpoint).." Sv:"..print_sv(sv96setpoint)) printf(" AvMin:".. print_av(av96min).." NDF:"..nd_string..focus_string ) if ((max_shots>0) and (shot_count >= max_shots)) then script_exit = true end shot_request = false -- reset shot request flag end collectgarbage() end -- check if USB remote enabled in intervalometer mode and USB power is off -> pause if so if ((usb_mode == 1 ) and (get_usb_power(1) == 0)) then printf("waiting on USB signal") unlock_focus() switch_mode(0) repeat wait_click(20) until ((get_usb_power(1) == 1) or ( is_key("menu"))) switch_mode(1) lock_focus() if ( is_key("menu")) then script_exit = true end printf("USB wait finished") sleep(100) end if (usb_mode == 3 ) then pwm_mode(get_usb_power(2)) end if (blite_timer > 0) then blite_timer = blite_timer-1 if ((blite_timer==0) and (backlight==1)) then set_lcd_display(0) end end if( error_string ~= nil) then draw_string( 16, 144, string.sub(error_string.." ",0,42), 258, 259) end wait_click(100) if( not( is_key("no_key"))) then if ((blite_timer==0) and (backlight==1)) then set_lcd_display(1) end blite_timer=300 if ( is_key("menu") ) then script_exit = true end end until (script_exit==true) printf("script halt requested") restore() end --[[ end of file ]]--
gpl-3.0
xdemolish/darkstar
scripts/globals/items/eggplant.lua
35
1203
----------------------------------------- -- ID: 4388 -- Item: eggplant -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility 3 -- Vitality -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,300,4388); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 3); target:addMod(MOD_VIT, -5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 3); target:delMod(MOD_VIT, -5); end;
gpl-3.0
garious/flake
luau/qtest_q.lua
2
3089
local qt = require "qtest" local testCount = 0 function qt.tests.describe() testCount = testCount + 1 local function exd(a,...) local s = qt.describe(...) if a ~= s then print(a, "~=", s) error("assertion failed", 2) end end -- primitive types exd( '"abc"', 'abc' ) exd( '"a\\"b"', 'a"b' ) exd( '12', 12 ) exd( 'true', true ) exd( 'false', false ) exd( 'nil', nil ) if not string.match( qt.describe(tostring), "<function.*>") then error("did not match function") end -- tables exd( '{1,2}', {1,2} ) exd( '{1,2,[4]=true,a=3}', {a=3,1,2,[4]=true} ) -- table recursion local t = {} ; t[1] = t ; t[2] = {t} exd( '{@0,{@1}}', t) -- prefix assert( qt.describe({{1,2},3}, nil, " ") == "{\n {\n 1,\n 2\n },\n 3\n}") end local function expectFail(f, ...) local errmsg = nil local qa = qt.fail function qt.fail(msg) errmsg = msg end f(...) qt.fail = qa -- qt.fail was called? assert(type(errmsg) == "string") -- check error message format if not errmsg:match("traceback:\n\tqtest_q.lua:") then print( ("Error message:\n" .. errmsg):gsub("\n", "\n | ")) error("Cluttered traceback", 2) end end function qt.tests.eq() testCount = testCount + 1 qt.eq(true, true) qt.eq(1, 1) qt.eq({}, {}) qt.eq('a', 'a') expectFail(qt.eq, 1, 2) expectFail(qt.eq, 1, "1") expectFail(qt.eq, true, "true") expectFail(qt.eq, {a=1}, {b=1}) expectFail(qt.eq, function () end, function () return 1 end) expectFail(qt.eq, 1, 2, 3) -- too many args expectFail(qt.eq, nil) -- too few args end function qt.tests.same() testCount = testCount + 1 local t = {} qt.same(1, 1) qt.same(nil, nil) qt.same(t, t) expectFail(qt.same, 1, 2) expectFail(qt.same, {}, {}) expectFail(qt.same, nil) -- not enough args expectFail(qt.same, 1, 1, 1) -- too many args end function qt.tests.match() testCount = testCount + 1 qt.match("abc", "b") qt.match("abc", ".") expectFail(qt.match, "b", "abc") end -- qt.load local loadTestSrc = [[ local a = 1 local function f() return a end local b = 2 return { f = f, x = 2 } ]] local function writeFile(name, data) local f = assert(io.open(name, "w")) f:write(data) f:close() end function qt.tests.load() testCount = testCount + 1 local workdir = assert(os.getenv("OUTDIR")) local fname = workdir .. "/qtest_q_ml.lua" writeFile(fname, loadTestSrc) -- load module (success case) local lm, ll = qt.load(fname, {"f", "a", "b"}) qt.eq("function", type(lm.f)) qt.eq(lm.f, ll.f) qt.eq(1, ll.a) qt.eq(2, ll.b) qt.eq(ll.a, ll.f()) -- error handling local m, err = pcall(function () return qt.load("DOESNOTEXIST", {"a", "b"}) end) qt.eq(false, m) qt.match(err, "could not find file DOESNOTEXIST") end assert(qt.runTests() == 0) -- make sure qtest ran all the tests qt.eq(testCount, 5)
mit
lukego/snabb
src/apps/ipv6/ns_responder.lua
7
3495
-- This app acts as a responder for neighbor solicitaions for a -- specific target address and as a relay for all other packets. It -- has two ports, north and south. The south port attaches to a port -- on which NS messages are expected. Non-NS packets are sent on -- north. All packets received on the north port are passed south. module(..., package.seeall) local ffi = require("ffi") local app = require("core.app") local link = require("core.link") local packet = require("core.packet") local datagram = require("lib.protocol.datagram") local ethernet = require("lib.protocol.ethernet") local ipv6 = require("lib.protocol.ipv6") local icmp = require("lib.protocol.icmp.header") local ns = require("lib.protocol.icmp.nd.ns") local filter = require("lib.pcap.filter") ns_responder = subClass(nil) ns_responder._name = "ipv6 neighbor solicitation responder" function ns_responder:new(config) local o = ns_responder:superClass().new(self) o._config = config o._match_ns = function(ns) return(ns:target_eq(config.local_ip)) end local filter, errmsg = filter:new("icmp6 and ip6[40] = 135") assert(filter, errmsg and ffi.string(errmsg)) o._filter = filter o._dgram = datagram:new() packet.free(o._dgram:packet()) return o end local function process (self, p) if not self._filter:match(packet.data(p), packet.length(p)) then return false end local dgram = self._dgram:new(p, ethernet) -- Parse the ethernet, ipv6 amd icmp headers dgram:parse_n(3) local eth, ipv6, icmp = unpack(dgram:stack()) local payload, length = dgram:payload() if not icmp:checksum_check(payload, length, ipv6) then print(self:name()..": bad icmp checksum") return nil end -- Parse the neighbor solicitation and check if it contains our own -- address as target local ns = dgram:parse_match(nil, self._match_ns) if not ns then return nil end local option = ns:options(dgram:payload()) if not (#option == 1 and option[1]:type() == 1) then -- Invalid NS, ignore return nil end -- Turn this message into a solicited neighbor -- advertisement with target ll addr option -- Ethernet eth:swap() eth:src(self._config.local_mac) -- IPv6 ipv6:dst(ipv6:src()) ipv6:src(self._config.local_ip) -- ICMP option[1]:type(2) option[1]:option():addr(self._config.local_mac) icmp:type(136) -- Undo/redo icmp and ns headers to get -- payload and set solicited flag dgram:unparse(2) dgram:parse() -- icmp local payload, length = dgram:payload() dgram:parse():solicited(1) icmp:checksum(payload, length, ipv6) return true end function ns_responder:push() local l_in = self.input.north local l_out = self.output.south if l_in and l_out then while not link.empty(l_in) and not link.full(l_out) do -- Pass everything on north -> south link.transmit(l_out, link.receive(l_in)) end end l_in = self.input.south l_out = self.output.north local l_reply = self.output.south while not link.empty(l_in) and not link.full(l_out) do local p = link.receive(l_in) local status = process(self, p) if status == nil then -- Discard packet.free(p) elseif status == true then -- Send NA back south link.transmit(l_reply, p) else -- Send transit traffic up north link.transmit(l_out, p) end end end
apache-2.0
garious/flake
luau/thread.lua
2
7021
-- thread.lua -- -- Thread.lua exports a number of functions that deal with "threads". A -- "thread" consists of a *task* and a *coroutine*. -- -- Task Objects -- ------------- -- -- Task objects represent a pending operation, and store the following: -- -- * the dispatch context [needed to schedule a coroutine] -- * what the coroutine is waiting on [needed to dequeue it] -- * cleanup functions to be called when the coroutine exits -- * values returned from the coroutine's start function -- -- Dispatch Objects -- ---------------- -- -- Dispatch objects represent a context for dispatching -- i.e. the state -- associated with an invocation of `thread.dispatch()`. When a task is -- waiting on a blocking function -- e.g. read() -- it is stored in a queue -- owned by its dispatch context. When a task is being executed, it is being -- called (or resumed) from the instance of `dispatch()` associated with its -- dispatch context. local xpio = require "xpio" local Heap = require "heap" local Queue = require "queue" -- reverse of table.pack -- local function undoPack(t) return table.unpack(t, 1, t.n) end local thread = {} -- currentTask holds the task currently executing local currentTask local function taskAtExit(me, fn, ...) local id = table.pack(fn, ...) table.insert(me.atExits, id) return id end local function taskCancelAtExit(me, id) for n = #me.atExits, 1, -1 do if id == me.atExits[n] then table.remove(me.atExits, n) return true end end return nil end local function taskRunAtExits(me) while true do local oe = table.remove(me.atExits) if not oe then return end oe[1](table.unpack(oe, 2, oe.n)) end end local function taskDelete(me) if me._dequeue then me:_dequeue() end taskRunAtExits(me) me.dispatch.all[me] = nil end -- Task class thread.Task = {} -- Create a new task -- -- Other task members not assigned herein: -- me._dequeue -- me._dequeuedata -- local function taskNew(dispatch, fn, ...) local fargs = table.pack(...) local me = setmetatable({}, thread.Task) local function preamble() me.results = table.pack(xpcall(fn, debug.traceback, undoPack(fargs))) me.failed = not table.remove(me.results, 1) me.results.n = me.results.n - 1 if me.failed then dispatch.all[me] = nil end taskDelete(me) end me.coroutine = coroutine.create(preamble) me.dispatch = dispatch me.atExits = {} me._queue = dispatch._queue me.makeReady = dispatch.makeReady me:makeReady() dispatch.all[me] = true return me end function thread.new(fn, ...) return taskNew(currentTask.dispatch, fn, ...) end function thread.yield() currentTask:makeReady() coroutine.yield() end local function joinWake(task) task._dequeue = nil task._dequeueTask = nil task._dequeueID = nil task:makeReady() end local function joinDequeue(task) taskCancelAtExit(task._dequeueTask, task._dequeueID) task._dequeue = nil task._dequeueTask = nil task._dequeueID = nil end function thread.join(task) if not task.results then local id = taskAtExit(task, joinWake, currentTask) currentTask._dequeue = joinDequeue currentTask._dequeueTask = task currentTask._dequeueID = id coroutine.yield() end if task.failed then error(task.results[1], 0) else return undoPack(task.results) end end function thread.atExit(fn, ...) return taskAtExit(currentTask, fn, ...) end function thread.cancelAtExit(id) return taskCancelAtExit(currentTask, id) end function thread.kill(task) if not task.results then task.results = table.pack(nil, "killed") taskDelete(task) end end -- Create a new "dispatch" (dispatching context) -- local function newDispatch() local me = {} local ready = Queue:new() local sleepers = Heap:new() local tq = xpio.tqueue() me.all = {} -- all unfinished tasks me._queue = tq local function dqQueue(task) task._dequeuedata:remove(task) task._dequeuedata = nil task._dequeue = nil end function me.makeReady(task) assert(not task._dequeue) task._dequeue = dqQueue task._dequeuedata = ready ready:put(task) end local function dqSleeper(task) sleepers:remove(task) task._dequeue = nil end function me.wakeAt(task, timeDue) assert(not task._dequeue) task._dequeue = dqSleeper task.timeDue = timeDue sleepers:put(task, timeDue) end function me:dtor() while true do local t = ready:first() if not t then break end taskDelete(t) end end function me:dispatch() local thisTask = currentTask local run = Queue:new() while true do --printf("%d readers, %d writers, %d sleepers\n", -- count(readers), count(writers), #sleepers, ready:length()) -- Move ready tasks to the run queue, and then run them. During -- this time, any tasks placed on the ready queue will be run in -- the next iteration. run, ready = ready, run while true do currentTask = run:first() xpio.setCurrentTask(currentTask) if not currentTask then break end currentTask:_dequeue() local succ, err = coroutine.resume(currentTask.coroutine) if not succ then me:dtor() local msg = ("*** Uncaught error in thread:\n\t" .. tostring(err)):gsub("\n(.)", "\n | %1") error(msg, 0) end end local s = sleepers:first() local timeout = ready:first() and 0 or s and s.timeDue - xpio.gettime() local tasks = tq:wait(timeout) --printf("wait(%s) ->%s\n", tostring(timeout), tasks and #tasks or "nil") if tasks then for _, task in ipairs(tasks) do task:makeReady() end elseif not ready:first() then -- nothing to wait on break end -- wake sleepers local tNow = xpio.gettime() while true do local task = sleepers:first() if not task or task.timeDue > tNow then break end task:_dequeue() task:makeReady() end end currentTask = thisTask xpio.setCurrentTask(currentTask) end return me end function thread.dispatch(func, ...) local me = newDispatch() local t = taskNew(me, func, ...) me:dispatch() me:dtor() if t.failed then error(t.results[1], 0) end for task in pairs(me.all) do print("*** Dangling thread:") print(debug.traceback(task.coroutine)) end end function thread.sleepUntil(t) currentTask.dispatch.wakeAt(currentTask, t) coroutine.yield() end function thread.sleep(delay) thread.sleepUntil(delay + xpio.gettime()) end return thread
mit
cmotc/awesome
themes/sky/theme.lua
1
5144
------------------------------- -- "Sky" awesome theme -- -- By Andrei "Garoth" Thorp -- ------------------------------- -- If you want SVGs and extras, get them from garoth.com/awesome/sky-theme local theme_assets = require("beautiful.theme_assets") local xresources = require("beautiful.xresources") local dpi = xresources.apply_dpi -- BASICS local theme = {} theme.font = "sans 8" theme.bg_focus = "#e2eeea" theme.bg_normal = "#729fcf" theme.bg_urgent = "#fce94f" theme.bg_minimize = "#0067ce" theme.bg_systray = theme.bg_normal theme.fg_normal = "#2e3436" theme.fg_focus = "#2e3436" theme.fg_urgent = "#2e3436" theme.fg_minimize = "#2e3436" theme.useless_gap = 0 theme.border_width = dpi(2) theme.border_normal = "#dae3e0" theme.border_focus = "#729fcf" theme.border_marked = "#eeeeec" -- IMAGES theme.layout_fairh = "@AWESOME_THEMES_PATH@/sky/layouts/fairh.png" theme.layout_fairv = "@AWESOME_THEMES_PATH@/sky/layouts/fairv.png" theme.layout_floating = "@AWESOME_THEMES_PATH@/sky/layouts/floating.png" theme.layout_magnifier = "@AWESOME_THEMES_PATH@/sky/layouts/magnifier.png" theme.layout_max = "@AWESOME_THEMES_PATH@/sky/layouts/max.png" theme.layout_fullscreen = "@AWESOME_THEMES_PATH@/sky/layouts/fullscreen.png" theme.layout_tilebottom = "@AWESOME_THEMES_PATH@/sky/layouts/tilebottom.png" theme.layout_tileleft = "@AWESOME_THEMES_PATH@/sky/layouts/tileleft.png" theme.layout_tile = "@AWESOME_THEMES_PATH@/sky/layouts/tile.png" theme.layout_tiletop = "@AWESOME_THEMES_PATH@/sky/layouts/tiletop.png" theme.layout_spiral = "@AWESOME_THEMES_PATH@/sky/layouts/spiral.png" theme.layout_dwindle = "@AWESOME_THEMES_PATH@/sky/layouts/dwindle.png" theme.layout_cornernw = "@AWESOME_THEMES_PATH@/sky/layouts/cornernw.png" theme.layout_cornerne = "@AWESOME_THEMES_PATH@/sky/layouts/cornerne.png" theme.layout_cornersw = "@AWESOME_THEMES_PATH@/sky/layouts/cornersw.png" theme.layout_cornerse = "@AWESOME_THEMES_PATH@/sky/layouts/cornerse.png" theme.awesome_icon = "@AWESOME_THEMES_PATH@/sky/awesome-icon.png" -- from default for now... theme.menu_submenu_icon = "@AWESOME_THEMES_PATH@/default/submenu.png" -- Generate taglist squares: local taglist_square_size = dpi(4) theme.taglist_squares_sel = theme_assets.taglist_squares_sel( taglist_square_size, theme.fg_normal ) theme.taglist_squares_unsel = theme_assets.taglist_squares_unsel( taglist_square_size, theme.fg_normal ) -- MISC theme.wallpaper = "@AWESOME_THEMES_PATH@/sky/sky-background.png" theme.taglist_squares = "true" theme.titlebar_close_button = "true" theme.menu_height = dpi(15) theme.menu_width = dpi(100) -- Define the image to load theme.titlebar_close_button_normal = "@AWESOME_THEMES_PATH@/default/titlebar/close_normal.png" theme.titlebar_close_button_focus = "@AWESOME_THEMES_PATH@/default/titlebar/close_focus.png" theme.titlebar_minimize_button_normal = "@AWESOME_THEMES_PATH@/default/titlebar/minimize_normal.png" theme.titlebar_minimize_button_focus = "@AWESOME_THEMES_PATH@/default/titlebar/minimize_focus.png" theme.titlebar_ontop_button_normal_inactive = "@AWESOME_THEMES_PATH@/default/titlebar/ontop_normal_inactive.png" theme.titlebar_ontop_button_focus_inactive = "@AWESOME_THEMES_PATH@/default/titlebar/ontop_focus_inactive.png" theme.titlebar_ontop_button_normal_active = "@AWESOME_THEMES_PATH@/default/titlebar/ontop_normal_active.png" theme.titlebar_ontop_button_focus_active = "@AWESOME_THEMES_PATH@/default/titlebar/ontop_focus_active.png" theme.titlebar_sticky_button_normal_inactive = "@AWESOME_THEMES_PATH@/default/titlebar/sticky_normal_inactive.png" theme.titlebar_sticky_button_focus_inactive = "@AWESOME_THEMES_PATH@/default/titlebar/sticky_focus_inactive.png" theme.titlebar_sticky_button_normal_active = "@AWESOME_THEMES_PATH@/default/titlebar/sticky_normal_active.png" theme.titlebar_sticky_button_focus_active = "@AWESOME_THEMES_PATH@/default/titlebar/sticky_focus_active.png" theme.titlebar_floating_button_normal_inactive = "@AWESOME_THEMES_PATH@/default/titlebar/floating_normal_inactive.png" theme.titlebar_floating_button_focus_inactive = "@AWESOME_THEMES_PATH@/default/titlebar/floating_focus_inactive.png" theme.titlebar_floating_button_normal_active = "@AWESOME_THEMES_PATH@/default/titlebar/floating_normal_active.png" theme.titlebar_floating_button_focus_active = "@AWESOME_THEMES_PATH@/default/titlebar/floating_focus_active.png" theme.titlebar_maximized_button_normal_inactive = "@AWESOME_THEMES_PATH@/default/titlebar/maximized_normal_inactive.png" theme.titlebar_maximized_button_focus_inactive = "@AWESOME_THEMES_PATH@/default/titlebar/maximized_focus_inactive.png" theme.titlebar_maximized_button_normal_active = "@AWESOME_THEMES_PATH@/default/titlebar/maximized_normal_active.png" theme.titlebar_maximized_button_focus_active = "@AWESOME_THEMES_PATH@/default/titlebar/maximized_focus_active.png" return theme -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
yylangchen/Sample_Lua
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/AudioEngine.lua
10
6277
-------------------------------- -- @module AudioEngine -- @parent_module ccexp -------------------------------- -- -- @function [parent=#AudioEngine] lazyInit -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- Sets the current playback position of an audio instance.<br> -- param audioID an audioID returned by the play2d function<br> -- return -- @function [parent=#AudioEngine] setCurrentTime -- @param self -- @param #int audioID -- @param #float time -- @return bool#bool ret (return value: bool) -------------------------------- -- Gets the volume value of an audio instance.<br> -- param audioID an audioID returned by the play2d function<br> -- return volume value (range from 0.0 to 1.0) -- @function [parent=#AudioEngine] getVolume -- @param self -- @param #int audioID -- @return float#float ret (return value: float) -------------------------------- -- Uncache the audio data from internal buffer.<br> -- AudioEngine cache audio data on ios platform<br> -- warning This can lead to stop related audio first.<br> -- param filePath The path of an audio file -- @function [parent=#AudioEngine] uncache -- @param self -- @param #string filePath -------------------------------- -- Resume all suspended audio instances -- @function [parent=#AudioEngine] resumeAll -- @param self -------------------------------- -- Stop all audio instances -- @function [parent=#AudioEngine] stopAll -- @param self -------------------------------- -- Pause an audio instance.<br> -- param audioID an audioID returned by the play2d function -- @function [parent=#AudioEngine] pause -- @param self -- @param #int audioID -------------------------------- -- Release related objects<br> -- warning It must be called before the application exit -- @function [parent=#AudioEngine] end -- @param self -------------------------------- -- -- @function [parent=#AudioEngine] getMaxAudioInstance -- @param self -- @return int#int ret (return value: int) -------------------------------- -- Gets the current playback position of an audio instance.<br> -- param audioID an audioID returned by the play2d function<br> -- return the current playback position of an audio instance -- @function [parent=#AudioEngine] getCurrentTime -- @param self -- @param #int audioID -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#AudioEngine] setMaxAudioInstance -- @param self -- @param #int maxInstances -- @return bool#bool ret (return value: bool) -------------------------------- -- Checks whether an audio instance is loop.<br> -- param audioID an audioID returned by the play2d function<br> -- return Whether or not an audio instance is loop. -- @function [parent=#AudioEngine] isLoop -- @param self -- @param #int audioID -- @return bool#bool ret (return value: bool) -------------------------------- -- Pause all playing audio instances -- @function [parent=#AudioEngine] pauseAll -- @param self -------------------------------- -- Uncache all audio data from internal buffer.<br> -- warning All audio will be stopped first.<br> -- param -- @function [parent=#AudioEngine] uncacheAll -- @param self -------------------------------- -- Sets volume for an audio instance.<br> -- param audioID an audioID returned by the play2d function<br> -- param volume volume value (range from 0.0 to 1.0) -- @function [parent=#AudioEngine] setVolume -- @param self -- @param #int audioID -- @param #float volume -------------------------------- -- Play 2d sound<br> -- param filePath The path of an audio file<br> -- param loop Whether audio instance loop or not<br> -- param volume volume value (range from 0.0 to 1.0)<br> -- param profile a profile for audio instance<br> -- return an audio ID. It allows you to dynamically change the behavior of an audio instance on the fly. -- @function [parent=#AudioEngine] play2d -- @param self -- @param #string filePath -- @param #bool loop -- @param #float volume -- @param #cc.experimental::AudioProfile profile -- @return int#int ret (return value: int) -------------------------------- -- Returns the state of an audio instance.<br> -- param audioID an audioID returned by the play2d function<br> -- return the status of an audio instance -- @function [parent=#AudioEngine] getState -- @param self -- @param #int audioID -- @return int#int ret (return value: int) -------------------------------- -- Resume an audio instance.<br> -- param audioID an audioID returned by the play2d function -- @function [parent=#AudioEngine] resume -- @param self -- @param #int audioID -------------------------------- -- Stop an audio instance.<br> -- param audioID an audioID returned by the play2d function -- @function [parent=#AudioEngine] stop -- @param self -- @param #int audioID -------------------------------- -- Gets the duration of an audio instance.<br> -- param audioID an audioID returned by the play2d function<br> -- return the duration of an audio instance -- @function [parent=#AudioEngine] getDuration -- @param self -- @param #int audioID -- @return float#float ret (return value: float) -------------------------------- -- Sets whether an audio instance loop or not. <br> -- param audioID an audioID returned by the play2d function<br> -- param loop Whether audio instance loop or not -- @function [parent=#AudioEngine] setLoop -- @param self -- @param #int audioID -- @param #bool loop -------------------------------- -- Gets the default profile of audio instances<br> -- return the default profile of audio instances -- @function [parent=#AudioEngine] getDefaultProfile -- @param self -- @return experimental::AudioProfile#experimental::AudioProfile ret (return value: cc.experimental::AudioProfile) -------------------------------- -- @overload self, string -- @overload self, int -- @function [parent=#AudioEngine] getProfile -- @param self -- @param #int audioID -- @return experimental::AudioProfile#experimental::AudioProfile ret (return value: cc.experimental::AudioProfile) return nil
mit
hfjgjfg/mohammad
plugins/vote.lua
615
2128
do local _file_votes = './data/votes.lua' function read_file_votes () local f = io.open(_file_votes, "r+") if f == nil then print ('Created voting file '.._file_votes) serialize_to_file({}, _file_votes) else print ('Values loaded: '.._file_votes) f:close() end return loadfile (_file_votes)() end function clear_votes (chat) local _votes = read_file_votes () _votes [chat] = {} serialize_to_file(_votes, _file_votes) end function votes_result (chat) local _votes = read_file_votes () local results = {} local result_string = "" if _votes [chat] == nil then _votes[chat] = {} end for user,vote in pairs (_votes[chat]) do if (results [vote] == nil) then results [vote] = user else results [vote] = results [vote] .. ", " .. user end end for vote,users in pairs (results) do result_string = result_string .. vote .. " : " .. users .. "\n" end return result_string end function save_vote(chat, user, vote) local _votes = read_file_votes () if _votes[chat] == nil then _votes[chat] = {} end _votes[chat][user] = vote serialize_to_file(_votes, _file_votes) end function run(msg, matches) if (matches[1] == "ing") then if (matches [2] == "reset") then clear_votes (tostring(msg.to.id)) return "Voting statistics reset.." elseif (matches [2] == "stats") then local votes_result = votes_result (tostring(msg.to.id)) if (votes_result == "") then votes_result = "[No votes registered]\n" end return "Voting statistics :\n" .. votes_result end else save_vote(tostring(msg.to.id), msg.from.print_name, tostring(tonumber(matches[2]))) return "Vote registered : " .. msg.from.print_name .. " " .. tostring(tonumber(matches [2])) end end return { description = "Plugin for voting in groups.", usage = { "!voting reset: Reset all the votes.", "!vote [number]: Cast the vote.", "!voting stats: Shows the statistics of voting." }, patterns = { "^!vot(ing) (reset)", "^!vot(ing) (stats)", "^!vot(e) ([0-9]+)$" }, run = run } end
gpl-2.0
lukego/snabb
src/lib/lua/class.lua
7
3507
-- Support for basic OO programming. Apart from the usual -- incantations of setmetatable(), it implements a simple mechanism to -- avoid table allocations by recycling objects that have been -- explicitely declared to no longer be in use. An object can also be -- reused immediately by invoking the new() method on it, which avoids -- the overhead of going through the free list. -- -- All objects are descendants from a simple "elementary class" that -- implements the basic functionality for the creation and recycling -- of instance objects through the new() and free() methods. -- -- Usage: -- local require("lib.lua.class") -- local baseClass = require("baseClass") -- local myclass = subClass(baseClass) -- local instance = myclass:new() -- instance:free() -- local instance2 = myclass:new() -- instance2:new() -- -- If baseClass is nil, myclass will be a direct descendant of -- elementaryClass -- -- When called as a class method, the basic constructor new() either -- allocates a new instance or re-uses one that has been put on the -- class's freelist by a previous call of the free() instance method. -- When called as an instance method, the instance is marked for reuse -- immediately, which is equivalent to the sequence -- -- instance:free() -- instance = class:new() -- -- but it side-steps the freelist. -- -- Calls to methods of the super class must use the 'dot' notation and -- pass the object as argument itself, e.g. -- -- local myclass = subClass(someClass) -- function myclass:method(...) -- myclass:superClass().method(self, ...) -- -- Customization goes here -- end -- -- Note that the superClass method must be called with reference to -- the class in which the function is defined. Using -- self:superClass() would create a loop if the method itself was -- called from a derived class. local elementaryClass = {} elementaryClass._name = "elementary class" -- Class methods -- Create a new instance of a class or re-use one from the free list -- when called as a class method or return the instance itself when -- called as an instance method. A recycled object has its instance -- variable _recycled set to true. A class can use this, for example, -- to perform clean-up on such an object before re-use. function elementaryClass:new () assert(self ~= elementaryClass, "Can't instantiate abstract class elementaryClass") local instance if self._instance then instance = self instance._recycled = true else local freelist = self._freelist local index = freelist.index if index > 0 then instance = freelist.list[index] instance._recycled = true freelist.index = index - 1 else instance = { _recycled = false, _instance = true } setmetatable(instance, { __index = self }) end end return instance end -- Instance methods function elementaryClass:name() return self._name or nil end -- Put an instance on the free list for recycling function elementaryClass:free () local freelist = self:class()._freelist local index = freelist.index + 1 freelist.list[index] = self freelist.index = index end function subClass (baseClass) local baseClass = baseClass or elementaryClass local class = { _freelist = { index = 0, list = {} } } setmetatable(class, { __index = baseClass }) function class:class () return class end function class:superClass () return baseClass end return class end
apache-2.0
blockplanet/blockplanet
games/blockplanet/mods/default/nodes/saplings.lua
1
2215
minetest.register_node("default:sapling", { description = "Sapling", drawtype = "plantlike", visual_scale = 1.0, tiles = {"default_sapling.png"}, inventory_image = "default_sapling.png", wield_image = "default_sapling.png", paramtype = "light", sunlight_propagates = true, walkable = false, selection_box = { type = "fixed", fixed = {-0.3, -0.5, -0.3, 0.3, 0.35, 0.3} }, groups = {snappy = 2, dig_immediate = 3, flammable = 2, attached_node = 1, sapling = 1}, sounds = default.node_sound_leaves_defaults(), }) minetest.register_node("default:junglesapling", { description = "Jungle Sapling", drawtype = "plantlike", visual_scale = 1.0, tiles = {"default_junglesapling.png"}, inventory_image = "default_junglesapling.png", wield_image = "default_junglesapling.png", paramtype = "light", sunlight_propagates = true, walkable = false, selection_box = { type = "fixed", fixed = {-0.3, -0.5, -0.3, 0.3, 0.35, 0.3} }, groups = {snappy = 2, dig_immediate = 3, flammable = 2, attached_node = 1, sapling = 1}, sounds = default.node_sound_leaves_defaults(), }) minetest.register_node("default:pine_sapling", { description = "Pine Sapling", drawtype = "plantlike", visual_scale = 1.0, tiles = {"default_pine_sapling.png"}, inventory_image = "default_pine_sapling.png", wield_image = "default_pine_sapling.png", paramtype = "light", sunlight_propagates = true, walkable = false, selection_box = { type = "fixed", fixed = {-0.3, -0.5, -0.3, 0.3, 0.35, 0.3} }, groups = {snappy = 2, dig_immediate = 3, flammable = 2, attached_node = 1, sapling = 1}, sounds = default.node_sound_leaves_defaults(), }) minetest.register_node("default:acacia_sapling", { description = "Acacia Tree Sapling", drawtype = "plantlike", visual_scale = 1.0, tiles = {"default_acacia_sapling.png"}, inventory_image = "default_acacia_sapling.png", wield_image = "default_acacia_sapling.png", paramtype = "light", sunlight_propagates = true, walkable = false, selection_box = { type = "fixed", fixed = {-0.3, -0.5, -0.3, 0.3, 0.35, 0.3} }, groups = {snappy = 2, dig_immediate = 3, flammable = 2, attached_node = 1, sapling = 1}, sounds = default.node_sound_leaves_defaults(), })
gpl-3.0
czfshine/UpAndAway
code/prefabs/skyflies.lua
2
6520
BindGlobal() local assets = { Asset("ANIM", "anim/skyflies.zip"), Asset( "ATLAS", inventoryimage_atlas("skyflies") ), Asset( "IMAGE", inventoryimage_texture("skyflies") ), Asset( "ATLAS", inventoryimage_atlas("skyflies_pink") ), Asset( "IMAGE", inventoryimage_texture("skyflies_pink") ), Asset( "ATLAS", inventoryimage_atlas("skyflies_green") ), Asset( "IMAGE", inventoryimage_texture("skyflies_green") ), Asset( "ATLAS", inventoryimage_atlas("skyflies_blue") ), Asset( "IMAGE", inventoryimage_texture("skyflies_blue") ), Asset( "ATLAS", inventoryimage_atlas("skyflies_orange") ), Asset( "IMAGE", inventoryimage_texture("skyflies_orange") ), Asset( "ATLAS", inventoryimage_atlas("skyflies_purple") ), Asset( "IMAGE", inventoryimage_texture("skyflies_purple") ), Asset( "ATLAS", inventoryimage_atlas("skyflies_red") ), Asset( "IMAGE", inventoryimage_texture("skyflies_red") ), } local INTENSITY = .7 local colours = { {198/255,43/255,43/255}, {79/255,153/255,68/255}, {35/255,105/255,235/255}, {233/255,208/255,69/255}, {109/255,50/255,163/255}, {222/255,126/255,39/255}, } local itemcolours = { "pink", "green", "blue", "orange", "purple", "red", } local function fadein(inst) inst:AddTag("NOCLICK") inst.components.fader:StopAll() inst.AnimState:PlayAnimation("swarm_pre") inst.AnimState:PushAnimation("swarm_loop", true) inst.Light:Enable(true) inst.Light:SetIntensity(0) inst.components.fader:Fade(0, INTENSITY, 3+math.random()*2, function(v) inst.Light:SetIntensity(v) end, function() inst:RemoveTag("NOCLICK") end) end local function fadeout(inst) inst:AddTag("NOCLICK") inst.components.fader:StopAll() inst.Light:SetIntensity(INTENSITY) inst.components.fader:Fade(INTENSITY, 0, 3+math.random()*2, function(v) inst.Light:SetIntensity(v) end, function() inst:Remove() end) end local function updatelight(inst) if not inst.components.inventoryitem.owner then if not inst.lighton then fadein(inst) end inst.lighton = true end end local function ondropped(inst) inst.components.workable:SetWorkLeft(1) fadein(inst) inst.lighton = true inst:DoTaskInTime(2+math.random()*1, function() updatelight(inst) end) end local function getstatus(inst) if inst.components.inventoryitem.owner then return "HELD" end end local function onfar(inst) updatelight(inst) end local function onnear(inst) updatelight(inst) end local function try_remove(inst) if GetStaticGenerator() and not GetStaticGenerator():IsCharged() then fadeout(inst) end end local function onsave(inst, data) data.colour_idx = inst.colour_idx end local function onload(inst, data) if data then if data.colour_idx then inst.colour_idx = math.min(#colours, data.colour_idx) inst.AnimState:SetMultColour(colours[inst.colour_idx][1],colours[inst.colour_idx][2],colours[inst.colour_idx][3],1) inst.Light:SetColour(colours[inst.colour_idx][1],colours[inst.colour_idx][2],colours[inst.colour_idx][3]) local itemcolourid = itemcolours[inst.colour_idx] print(itemcolourid) --inst.components.inventoryitem:ChangeImageName("skyflies_"..itemcolours[inst.colour_idx]) end end end local function fn(Sim) local inst = CreateEntity() inst.entity:AddTransform() inst.entity:AddAnimState() inst.entity:AddPhysics() MakeInventoryPhysics(inst) local light = inst.entity:AddLight() light:SetFalloff(1) inst.colour_idx = math.random(#colours) inst.AnimState:SetMultColour(colours[inst.colour_idx][1],colours[inst.colour_idx][2],colours[inst.colour_idx][3],1) light:SetRadius(.5) light:SetColour(colours[inst.colour_idx][1],colours[inst.colour_idx][2],colours[inst.colour_idx][3]) inst.Light:Enable(true) inst.Light:SetIntensity(.5) inst.AnimState:SetBloomEffectHandle( "shaders/anim.ksh" ) inst.AnimState:SetBank("fireflies") inst.AnimState:SetBuild("skyflies") inst.AnimState:PlayAnimation("swarm_pre") inst.AnimState:PushAnimation("swarm_loop", true) MakeCharacterPhysics(inst, 1, .25) inst.Physics:SetCollisionGroup(COLLISION.FLYERS) inst.Physics:ClearCollisionMask() inst.Physics:CollidesWith(COLLISION.WORLD) inst.AnimState:SetRayTestOnBB(true) ------------------------------------------------------------------------ SetupNetwork(inst) ------------------------------------------------------------------------ ; inst:AddComponent("playerprox") inst:AddComponent("inspectable") inst.components.inspectable.getstatus = getstatus --We'll take care of this for beta. --inst:AddComponent("workable") --inst.components.workable:SetWorkAction(ACTIONS.NET) --inst.components.workable:SetWorkLeft(1) --inst.components.workable:SetOnFinishCallback(function(inst, worker) --if worker.components.inventory then --worker.components.inventory:GiveItem(inst, nil, Vector3(TheSim:GetScreenPos(inst.Transform:GetWorldPosition()))) --end --end) inst:AddComponent("fader") --inst:AddComponent("stackable") --inst.components.stackable.maxsize = TUNING.STACK_SIZE_SMALLITEM --inst.components.stackable.forcedropsingle = true inst:AddComponent("inventoryitem") inst.components.inventoryitem:SetOnDroppedFn(ondropped) inst.components.inventoryitem.canbepickedup = false inst.components.inventoryitem.atlasname = inventoryimage_atlas("skyflies_"..itemcolours[inst.colour_idx]) inst.components.inventoryitem:ChangeImageName("skyflies_"..itemcolours[inst.colour_idx]) inst.components.playerprox:SetDist(3,5) inst.components.playerprox:SetOnPlayerNear(onnear) inst.components.playerprox:SetOnPlayerFar(onfar) inst:AddComponent("locomotor") inst.components.locomotor:EnableGroundSpeedMultiplier(false) inst.components.locomotor:SetTriggersCreep(false) inst:SetStateGraph("SGskyfly") local brain = require "brains/skyflybrain" inst:SetBrain(brain) inst:AddTag("FX") inst:ListenForEvent("upandaway_uncharge", function() try_remove(inst) end, GetWorld()) updatelight(inst) inst.OnSave = onsave inst.OnLoad = onload return inst end return Prefab( "common/objects/skyflies", fn, assets)
gpl-2.0
czfshine/UpAndAway
wicker/game/searching.lua
5
5456
--[[ Copyright (C) 2013 simplex 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, see <http://www.gnu.org/licenses/>. ]]-- BecomePackage "common" local EntityScript = EntityScript local Point = Point local Lambda = wickerrequire 'paradigms.functional' local Logic = wickerrequire 'lib.logic' local Pred = wickerrequire 'lib.predicates' local Math = wickerrequire "math" local Algo = wickerrequire "utils.algo" local ToPoint = Math.ToPoint local ToComplex = Math.ToComplex --- local basic_finders basic_finders = { all = function(ent_gen, fn, ...) return Lambda.CompactlyFilter( function(v) return Pred.IsOk(v) and fn(v) end, ent_gen(...) ) end, any = function(ent_gen, fn, ...) return Lambda.Find( function(v) return Pred.IsOk(v) and fn(v) end, ent_gen(...) ) end, random = function(ent_gen, fn, ...) local E = basic_finders.all(ent_gen, fn, ...) local l = #E if l > 0 then return E[math.random(l)] end end, closest = function(ent_gen, fn, center, ...) local weight = Lambda.BindSecond(EntityScript.GetDistanceSqToPoint, center) return (Lambda.Minimize(weight, ipairs(basic_finders.all(ent_gen, fn, center, ...)))) end, closests = function(ent_gen, fn, center, max_count, ...) local E = basic_finders.all(ent_gen, fn, center, ...) local distSqTo = EntityScript.GetDistanceSqToPoint local function cmp(instA, instB) return distSqTo(instA, center) < distSqTo(instB, center) end return Algo.LeastElementsOf(E, max_count, cmp) end, } local function general_ent_gen(center, radius, and_tags, not_tags, or_tags) return ipairs(TheSim:FindEntities(center.x, center.y, center.z, radius, and_tags, not_tags, or_tags)) end local player_ent_gen if not IsDST() then player_ent_gen = function() return Lambda.iterator.Singleton(GetLocalPlayer()) end else player_ent_gen = function() return ipairs(_G.AllPlayers) end end local function MakeEntSearcher(basic_prototype) return function(center, radius, fn, and_tags, not_tags, or_tags) center = ToPoint(center) fn = Pred.ToPredicate(fn) return basic_prototype(general_ent_gen, fn, center, radius, and_tags, not_tags, or_tags) end end local function MakeClosestEntsSearcher() local basic_prototype = basic_finders.closests return function(center, radius, fn, max_count, and_tags, not_tags, or_tags) center = ToPoint(center) fn = Pred.ToPredicate(fn) return basic_prototype(general_ent_gen, fn, center, max_count, radius, and_tags, not_tags, or_tags) end end -- Center is only required for the "closest" search. local function MakePlayerSearcher(basic_prototype) return function(fn) fn = Pred.ToPredicate(fn) return basic_prototype(player_ent_gen, fn) end end local function MakeCenteredPlayerSearcher(basic_prototype) return function(center, fn, ...) center = ToPoint(center) fn = Pred.ToPredicate(fn) return basic_prototype(player_ent_gen, fn, center, ...) end end local function MakeBoundedPlayerSearcher(basic_prototype) return function(center, radius, fn, ...) local center = ToPoint(center) local radiussq = radius*radius local function cond(inst) return inst:GetDistanceSqToPoint(center) < radiussq end if fn then fn = Lambda.And(Pred.ToPredicate(fn), cond) else fn = cond end return basic_prototype(player_ent_gen, fn, center, ...) end end --- FindAllEntities = MakeEntSearcher(basic_finders.all) GetAllEntities = FindAllEntities FindSomeEntity = MakeEntSearcher(basic_finders.any) GetSomeEntity = FindSomeEntity FindRandomEntity = MakeEntSearcher(basic_finders.random) GetRandomEntity = FindRandomEntity FindClosestEntity = MakeEntSearcher(basic_finders.closest) GetClosestEntity = FindClosestEntity FindClosestEntities = MakeClosestEntsSearcher() GetClosestEntities = FindClosestEntities FindAllPlayers = MakePlayerSearcher(basic_finders.all) GetAllPlayers = FindAllPlayers FindSomePlayer = MakePlayerSearcher(basic_finders.any) GetSomePlayer = FindSomePlayer FindRandomPlayer = MakePlayerSearcher(basic_finders.random) GetRandomPlayer = FindRandomPlayer FindClosestPlayer = MakeCenteredPlayerSearcher(basic_finders.closest) GetClosestPlayer = FindClosestPlayer FindClosestPlayers = MakeCenteredPlayerSearcher(basic_finders.closests) GetClosestPlayers = FindClosestPlayers FindAllPlayersInRange = MakeBoundedPlayerSearcher(basic_finders.all) GetAllPlayersInRange = FindAllPlayersInRange FindSomePlayerInRange = MakeBoundedPlayerSearcher(basic_finders.any) GetSomePlayerInRange = FindSomePlayerInRange FindRandomPlayerInRange = MakeBoundedPlayerSearcher(basic_finders.random) GetRandomPlayerInRange = FindRandomPlayerInRange FindClosestPlayerInRange = MakeBoundedPlayerSearcher(basic_finders.closest) GetClosestPlayerInRange = FindClosestPlayerInRange FindClosestPlayersInRange = MakeBoundedPlayerSearcher(basic_finders.closests) GetClosestPlayersInRange = FindClosestPlayersInRange --- return _M
gpl-2.0
Andreas-Kreuz/ak-lua-skripte-fuer-eep
lua/LUA/ak/public-transport/models/SimpleStructure.lua
1
2002
local Line = require("ak.public-transport.Line") -- Simple Structure - works with any model local SimpleStructure = {} SimpleStructure.name = "SimpleStructure" SimpleStructure.initStation = function(displayStructure, stationName, platform) assert(type(displayStructure) == "string", "Need 'displayStructure' as string not as " .. type(displayStructure)) assert(type(stationName) == "string", "Need 'stationName' as string") assert(type(platform) == "string", "Need 'platform' as string") -- EEPStructureSetTextureText(displayStructure, 21, stationName) -- EEPStructureSetTextureText(displayStructure, 24, "Steig " .. platform) end SimpleStructure.displayEntries = function(displayStructure, stationQueueEntries, stationName, platform) assert(type(displayStructure) == "string", "Need 'displayStructure' as string not as " .. type(displayStructure)) assert(type(stationQueueEntries) == "table", "Need 'stationQueueEntries' as table not as " .. type(stationQueueEntries)) assert(type(stationName) == "string", "Need 'stationName' as string") assert(type(platform) == "string", "Need 'platform' as string") local text = {stationName, " (Steig ", platform, ")<br>"} table.insert(text, "Linie / Ziel / Minuten<br>") for i = 1, 5 do ---@type StationQueueEntry local entry = stationQueueEntries[i] table.insert(text, entry and entry.line or "") table.insert(text, " / ") table.insert(text, entry and entry.destination or "") table.insert(text, " / ") table.insert(text, (entry and entry.timeInMinutes > 0) and tostring(entry.timeInMinutes) or "") table.insert(text, " ") table.insert(text, (entry and entry.timeInMinutes > 0) and "min" or "") table.insert(text, "<br>") end text = table.concat(text, "") EEPChangeInfoStructure(displayStructure, text) EEPShowInfoStructure(displayStructure, Line.showDepartureTippText) end return SimpleStructure
mit
xdemolish/darkstar
scripts/globals/items/broiled_trout.lua
35
1292
----------------------------------------- -- ID: 4587 -- Item: Broiled Trout -- Food Effect: 60Min, All Races ----------------------------------------- -- Dexterity 4 -- Mind -1 -- Ranged ATT % 14 ----------------------------------------- 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,3600,4587); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 4); target:addMod(MOD_MND, -1); target:addMod(MOD_RATTP, 14); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 4); target:delMod(MOD_MND, -1); target:delMod(MOD_RATTP, 14); end;
gpl-3.0
xdemolish/darkstar
scripts/zones/Lower_Jeuno/npcs/Chululu.lua
15
5635
----------------------------------- -- Area: Lower Jeuno -- NPC: Chululu -- Starts and Finishes Quests: Collect Tarut Cards, Rubbish Day -- Optional Cutscene at end of Quest: Searching for the Right Words -- @pos -13 -6 -42 245 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(player:getQuestStatus(JEUNO,COLLECT_TARUT_CARDS) == QUEST_ACCEPTED) then if(trade:hasItemQty(558,1) == true and trade:hasItemQty(559,1) == true and trade:hasItemQty(561,1) == true and trade:hasItemQty(562,1) == true and trade:getItemCount() == 4) then player:startEvent(0x00c8); -- Finish quest "Collect Tarut Cards" end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local CollectTarutCards = player:getQuestStatus(JEUNO,COLLECT_TARUT_CARDS); local RubbishDay = player:getQuestStatus(JEUNO,RUBBISH_DAY); local SearchingForTheRightWords = player:getQuestStatus(JEUNO,SEARCHING_FOR_THE_RIGHT_WORDS); if(player:getFameLevel(JEUNO) >= 3 and CollectTarutCards == QUEST_AVAILABLE) then player:startEvent(0x001C); -- Start quest "Collect Tarut Cards" with option elseif(CollectTarutCards == QUEST_ACCEPTED) then player:startEvent(0x001B); -- During quest "Collect Tarut Cards" elseif(CollectTarutCards == QUEST_COMPLETED and RubbishDay == QUEST_AVAILABLE and player:getVar("RubbishDay_day") ~= VanadielDayOfTheYear()) then -- prog = player:getVar("RubbishDay_prog"); -- if(prog <= 2) then -- player:startEvent(0x00c7); -- Required to get compatibility 3x on 3 diff game days before quest is kicked off -- elseif(prog == 3) then player:startEvent(0x00c6); -- Start quest "Rubbish Day" with option -- end elseif(CollectTarutCards == QUEST_COMPLETED and RubbishDay == QUEST_AVAILABLE) then player:startEvent(0x0039); -- Standard dialog between 2 quests elseif(RubbishDay == QUEST_ACCEPTED and player:getVar("RubbishDayVar") == 0) then player:startEvent(0x0031); -- During quest "Rubbish Day" elseif(RubbishDay == QUEST_ACCEPTED and player:getVar("RubbishDayVar") == 1) then player:startEvent(0x00c5); -- Finish quest "Rubbish Day" elseif(SearchingForTheRightWords == QUEST_COMPLETED) then if (player:getVar("SearchingForRightWords_postcs") < -1) then player:startEvent(0x0038); else player:startEvent(0x0057); -- final state, after all quests complete end elseif(RubbishDay == QUEST_COMPLETED) then player:startEvent(0x0057); -- New standard dialog else player:startEvent(0x001A); -- Standard dialog 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 == 0x001C and option == 0) then local rand = math.random(1,4); local card = 0; if(rand == 1) then card = 559; -- Tarut: Death elseif(rand == 2) then card = 562; -- Tarut: Hermit elseif(rand == 3) then card = 561; -- Tarut: King else card = 558; -- Tarut: Fool end if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,card); else player:addQuest(JEUNO,COLLECT_TARUT_CARDS); player:addItem(card,5); player:messageSpecial(ITEM_OBTAINED,card); end elseif(csid == 0x00c8) then player:addTitle(CARD_COLLECTOR); player:addFame(JEUNO, JEUNO_FAME*30); player:tradeComplete(); player:completeQuest(JEUNO,COLLECT_TARUT_CARDS); elseif(csid == 0x00c7 and option == 0) then player:setVar("RubbishDay_prog", player:getVar("RubbishDay_prog") + 1); player:setVar("RubbishDay_day", VanadielDayOfTheYear()); -- new vanadiel day elseif(csid == 0x00c6 and option == 0) then player:addQuest(JEUNO,RUBBISH_DAY); player:addKeyItem(MAGIC_TRASH); player:messageSpecial(KEYITEM_OBTAINED,MAGIC_TRASH); player:setVar("RubbishDay_prog",0); player:setVar("RubbishDay_day",0); elseif(csid == 0x00c5) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13083); else player:addGil(GIL_RATE*6000); player:messageSpecial(GIL_OBTAINED,GIL_RATE*6000); player:addItem(13083); player:messageSpecial(ITEM_OBTAINED,13083); player:setVar("RubbishDayVar",0); player:addFame(JEUNO, JEUNO_FAME*30); player:completeQuest(JEUNO,RUBBISH_DAY); end end end;
gpl-3.0
xdemolish/darkstar
scripts/zones/Lower_Delkfutts_Tower/mobs/Disaster_Idol.lua
13
1223
----------------------------------- -- Area: Lower_Delkfutts_tower -- Mob: Disaster_Idol ----------------------------------- require("scripts/globals/missions"); ----------------------------------- -- onMobEngaged Action ----------------------------------- function onMobEngaged(mob,target) local DayofWeek = VanadielDayElement(); mob:setSpellList(118 + DayofWeek); mob:setLocalVar("Element", DayofWeek+1); end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) --TODO: Has level mimic of person who spawned it. Minimum level 65. HP should scale accordingly. local DayofWeek = VanadielDayElement(); local Element = mob:getLocalVar("Element"); if (DayofWeek + 1 ~= Element) then mob:setSpellList(118 + DayofWeek); mob:setLocalVar("Element", DayofWeek+1); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) if(killer:getCurrentMission(COP) == THREE_PATHS and killer:getVar("COP_Tenzen_s_Path") == 6)then killer:setVar("COP_Tenzen_s_Path",7); end end;
gpl-3.0
Arcscion/Shadowlyre
scripts/globals/items/serving_of_leadafry.lua
12
1190
----------------------------------------- -- ID: 5161 -- Item: serving_of_leadafry -- Food Effect: 240Min, All Races ----------------------------------------- -- Agility 5 -- Vitality 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,14400,5161); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 5); target:addMod(MOD_VIT, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 5); target:delMod(MOD_VIT, 2); end;
gpl-3.0
jono659/enko
scripts/globals/spells/absorb-str.lua
11
1195
-------------------------------------- -- Spell: Absorb-STR -- Steals an enemy's strength. -------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) if(target:hasStatusEffect(EFFECT_STR_DOWN) or caster:hasStatusEffect(EFFECT_STR_BOOST)) then spell:setMsg(75); -- no effect else local dINT = caster:getStat(MOD_INT) - target:getStat(MOD_INT); local resist = applyResistance(caster,spell,target,dINT,37,0); if(resist <= 0.125) then spell:setMsg(85); else spell:setMsg(329); caster:addStatusEffect(EFFECT_STR_BOOST,ABSORB_SPELL_AMOUNT*resist, ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK,FLAG_DISPELABLE); -- caster gains STR target:addStatusEffect(EFFECT_STR_DOWN,ABSORB_SPELL_AMOUNT*resist, ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK,FLAG_ERASBLE); -- target loses STR end end return EFFECT_STR_DOWN; end;
gpl-3.0
jono659/enko
scripts/zones/Heavens_Tower/npcs/_6q1.lua
17
1376
----------------------------------- -- Area: Heaven's Tower -- NPC: Starway Stairway -- @pos -10 0.1 30 242 ----------------------------------- package.loaded["scripts/zones/Heavens_Tower/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Heavens_Tower/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getNation() == 2) then if (player:hasKeyItem(STARWAY_STAIRWAY_BAUBLE)) then if (player:getXPos() < -14) then player:startEvent(0x006A); else player:startEvent(0x0069); end; else player:messageSpecial(STAIRWAY_LOCKED); end; else player:messageSpecial(STAIRWAY_ONLY_CITIZENS); end return 1; 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
N0U/Zero-K
scripts/gunshipheavyskirm.lua
8
4214
include 'constants.lua' local base, body, rfjet, lfjet, rffan, lffan, rgun, rbarrel, rflare1, rflare2, lgun, lbarrel, lflare1, lflare2, eye, rthruster, rrjet, rrfanbase, rrfan, lthruster, lrjet, lrfanbase, lrfan = piece('base', 'body', 'rfjet', 'lfjet', 'rffan', 'lffan', 'rgun', 'rbarrel', 'rflare1', 'rflare2', 'lgun', 'lbarrel', 'lflare1', 'lflare2', 'eye', 'rthruster', 'rrjet', 'rrfanbase', 'rrfan', 'lthruster', 'lrjet', 'lrfanbase', 'lrfan') local gun = 1 local attacking = false local spGetUnitVelocity = Spring.GetUnitVelocity local emits = { {flare = rflare1, barrel = rbarrel}, {flare = lflare1, barrel = lbarrel}, {flare = rflare2, barrel = rbarrel}, {flare = lflare2, barrel = lbarrel}, } local SIG_AIM = 1 local SIG_RESTORE = 2 local smokePiece = { base} function script.Activate() Spin(rffan, y_axis, rad(360), rad(100)) Spin(lffan, y_axis, rad(360), rad(100)) Spin(rrfan, y_axis, rad(360), rad(100)) Spin(lrfan, y_axis, rad(360), rad(100)) end function script.StopMoving() Spin(rffan, y_axis, rad(0), rad(100)) Spin(lffan, y_axis, rad(0), rad(100)) Spin(rrfan, y_axis, rad(0), rad(100)) Spin(lrfan, y_axis, rad(0), rad(100)) end local function TiltBody() while true do if attacking then Turn(body, x_axis, 0, math.rad(45)) Turn(rthruster, x_axis, 0, math.rad(45)) Turn(lthruster, x_axis, 0, math.rad(45)) Sleep(250) else local vx,_,vz = spGetUnitVelocity(unitID) local speed = vx*vx + vz*vz if speed > 0.5 then Turn(body, x_axis, math.rad(22.5), math.rad(45)) Turn(rthruster, x_axis, math.rad(22.5), math.rad(45)) Turn(lthruster, x_axis, math.rad(22.5), math.rad(45)) Sleep(250) else Turn(body, x_axis, 0, math.rad(45)) Turn(rthruster, x_axis, 0, math.rad(45)) Turn(lthruster, x_axis, 0, math.rad(45)) Sleep(250) end end end end function script.Create() Turn(rfjet, x_axis, math.rad(-90)) Turn(lfjet, x_axis, math.rad(-90)) Turn(rrjet, x_axis, math.rad(-90)) Turn(lrjet, x_axis, math.rad(-90)) Turn(rrfanbase, z_axis, math.rad(22.5)) Turn(lrfanbase, z_axis, math.rad(-22.5)) StartThread(SmokeUnit, smokePiece) StartThread(TiltBody) end local function RestoreAfterDelay() Signal(SIG_RESTORE) SetSignalMask(SIG_RESTORE) Sleep(1000) Turn(rgun, y_axis, 0, math.rad(600)) Turn(lgun, y_axis, 0, math.rad(600)) attacking = false end function script.AimWeapon(num, heading, pitch) Signal(SIG_AIM) SetSignalMask(SIG_AIM) Turn(rgun, y_axis, heading, math.rad(600)) Turn(lgun, y_axis, heading, math.rad(600)) attacking = true StartThread(RestoreAfterDelay) return true end function script.QueryWeapon(num) return emits[gun].flare end function script.AimFromWeapon(num) return eye end function script.Shot(num) EmitSfx(emits[gun].flare, 1024) EmitSfx(emits[gun].barrel, 1025) gun = (gun)%4 + 1 end function script.Killed(recentDamage, maxHealth) local severity = recentDamage / maxHealth if severity <= 0.25 then Explode(base, sfxNone) Explode(body, sfxNone) Explode(rthruster, sfxExplode) Explode(lthruster, sfxExplode) Explode(rffan, sfxExplode) Explode(lffan, sfxExplode) return 1 elseif severity <= 0.50 or ((Spring.GetUnitMoveTypeData(unitID).aircraftState or "") == "crashing") then Explode(base, sfxFall) Explode(body, sfxShatter) Explode(rthruster, sfxFall) Explode(lthruster, sfxFall) Explode(rffan, sfxShatter) Explode(lffan, sfxShatter) return 1 else Explode(body, sfxShatter) Explode(rfjet, sfxFall + sfxFire) Explode(lfjet, sfxFall + sfxFire) Explode(rffan, sfxFall + sfxFire) Explode(lffan, sfxFall + sfxFire) Explode(rgun, sfxExplode) Explode(rbarrel, sfxExplode) Explode(rflare1, sfxExplode) Explode(rflare2, sfxExplode) Explode(lgun, sfxExplode) Explode(lbarrel, sfxExplode) Explode(lflare1, sfxExplode) Explode(lflare2, sfxExplode) Explode(eye, sfxExplode) Explode(rthruster, sfxFall + sfxSmoke + sfxFire + sfxExplodeOnHit) Explode(rrjet, sfxExplode) Explode(rrfanbase, sfxExplode) Explode(rrfan, sfxExplode) Explode(lthruster, sfxFall + sfxSmoke + sfxFire + sfxExplodeOnHit) Explode(lrjet, sfxExplode) Explode(lrfanbase, sfxExplode) Explode(lrfan, sfxExplode) return 2 end end
gpl-2.0
LouisK130/Orange-Cosmos-Roleplay
ocrp/gamemode/client/professions.lua
1
27624
local vgui = vgui local surface = surface local draw = draw function CL_UpdateProf( umsg ) local Prof = umsg:ReadString() local Exp = umsg:ReadLong() local ExpM = umsg:ReadLong() local ExpP = umsg:ReadLong() if Prof == "Pro_Crafting" then OCRP_Professions[Prof] = {Exp = {Skill = Exp,Mechanical = ExpM,Practical = ExpP,}} else OCRP_Professions[Prof] = {Exp = tonumber(Exp)} end if GUI_Main_Frame != nil && GUI_Main_Frame:IsValid() then GUI_Prof_Panel_List:Remove() GUI_Rebuild_Professions(GUI_Prof_tab_Panel) end end usermessage.Hook('OCRP_UpdateProf', CL_UpdateProf); local OC_1 = Material("gui/OCRP/OCRP_Orange") function GUI_Rebuild_Professions(parent) GUI_Prof_Panel_List = vgui.Create("DPanelList") GUI_Prof_Panel_List:SetParent(parent) GUI_Prof_Panel_List:SetSize(746,480) GUI_Prof_Panel_List:SetPos(0,0) GUI_Prof_Panel_List.Paint = function() draw.RoundedBox(8,0,0,GUI_Prof_Panel_List:GetWide(),GUI_Prof_Panel_List:GetTall(),Color( 60, 60, 60, 155 )) end GUI_Prof_Panel_List:SetPadding(7.5) GUI_Prof_Panel_List:SetSpacing(5) GUI_Prof_Panel_List:EnableHorizontal(3) GUI_Prof_Panel_List:EnableVerticalScrollbar(true) local activeprof = nil for Prof,data in pairs(OCRP_Professions) do if data.Active then activeprof = tostring(Prof) end end if activeprof == nil then local GUI_Prof_Name = vgui.Create("DLabel") GUI_Prof_Name:SetColor(Color(255,255,255,255)) surface.SetFont("Trebuchet22") local x,y = surface.GetTextSize("Select A Profession") GUI_Prof_Name:SetPos(373 - x/2,25 - y/2) GUI_Prof_Name:SetFont("Trebuchet22") GUI_Prof_Name:SetText("Select A Profession") GUI_Prof_Name:SizeToContents() GUI_Prof_Name:SetParent(GUI_Prof_Panel_List) local GUI_Prof_Desc = vgui.Create("DLabel") GUI_Prof_Desc:SetColor(Color(255,255,255,255)) surface.SetFont("Trebuchet22") local x,y = surface.GetTextSize("A profession allows your character to get increased perks, Click on one to select it.") GUI_Prof_Desc:SetPos(373 - x/2,420 - y/2) GUI_Prof_Desc:SetFont("Trebuchet22") GUI_Prof_Desc:SetText("A profession allows your character to get increased perks, Click on one to select it.") GUI_Prof_Desc:SizeToContents() GUI_Prof_Desc:SetParent(GUI_Prof_Panel_List) local numb = 60 for Prof,data in pairs(OCRP_Professions || {} ) do local GUI_Prof_Bar = vgui.Create("DButton") GUI_Prof_Bar:SetParent(GUI_Prof_Panel_List) GUI_Prof_Bar:SetSize(700,40) GUI_Prof_Bar:SetPos(23,numb) GUI_Prof_Bar:SetText("") GUI_Prof_Bar:SetToolTip(GAMEMODE.OCRP_Professions[Prof].Desc) GUI_Prof_Bar.Paint = function() draw.RoundedBox(8,0,0,GUI_Prof_Bar:GetWide(),GUI_Prof_Bar:GetTall(),Color( 55, 55, 55, 255 )) draw.RoundedBox(8,1,1,GUI_Prof_Bar:GetWide()-2,GUI_Prof_Bar:GetTall()-2,Color( 180, 90, 0, 155 )) if Prof == "Pro_Crafting" then local totalxp = data.Exp.Mechanical + data.Exp.Practical if totalxp > 0 then draw.RoundedBox(8,1,1,(GUI_Prof_Bar:GetWide()-2)*(totalxp/1000),(GUI_Prof_Bar:GetTall()-2),OCRP_Options.Color) end else if data.Exp > 0 then draw.RoundedBox(8,1,1,(GUI_Prof_Bar:GetWide()-2)*(data.Exp/1000),(GUI_Prof_Bar:GetTall()-2),OCRP_Options.Color) end end local struc = {} struc.pos = {} struc.pos[1] = 350 -- x pos struc.pos[2] = 10 -- y pos struc.color = Color(255,255,255,255) -- Red struc.font = "UiBold" -- Font struc.text = GAMEMODE.OCRP_Professions[Prof].Name -- Text struc.xalign = TEXT_ALIGN_CENTER-- Horizontal Alignment struc.yalign = TEXT_ALIGN_CENTER -- Vertical Alignment draw.Text( struc ) local struc = {} struc.pos = {} struc.pos[1] = 350 -- x pos struc.pos[2] = 30 -- y pos struc.color = Color(255,255,255,255) -- Red struc.font = "UiBold" -- Font struc.text = "0/1000" -- Text struc.xalign = TEXT_ALIGN_CENTER-- Horizontal Alignment struc.yalign = TEXT_ALIGN_CENTER -- Vertical Alignment draw.Text( struc ) end GUI_Prof_Bar.DoClick = function() RunConsoleCommand("OCRP_SetProf",Prof) end numb = numb + 60 end return GUI_Prof_Panel_List elseif activeprof == "Pro_Crafting" then local GUI_Prof_Name = vgui.Create("DLabel") GUI_Prof_Name:SetColor(Color(255,255,255,255)) surface.SetFont("Trebuchet22") local x,y = surface.GetTextSize("Professional "..GAMEMODE.OCRP_Professions[activeprof].Name) GUI_Prof_Name:SetPos(373 - x/2,25 - y/2) GUI_Prof_Name:SetFont("Trebuchet22") GUI_Prof_Name:SetText("Professional "..GAMEMODE.OCRP_Professions[activeprof].Name) GUI_Prof_Name:SizeToContents() GUI_Prof_Name:SetParent(GUI_Prof_Panel_List) local GUI_Prof_Crafting_List = vgui.Create("DPanelList") GUI_Prof_Crafting_List:SetParent(GUI_Prof_Panel_List) GUI_Prof_Crafting_List:SetSize(702,310) GUI_Prof_Crafting_List:SetPos(22,80) GUI_Prof_Crafting_List.Paint = function() draw.RoundedBox(8,0,0,GUI_Prof_Crafting_List:GetWide(),GUI_Prof_Crafting_List:GetTall(),Color( 60, 60, 60, 155 )) local struc = {} struc.pos = {} struc.pos[1] = 300 -- x pos struc.pos[2] = 200 -- y pos struc.color = Color(155,155,155,155) struc.font = "UiBold" -- Font struc.text = "Earn Experiance to unlock new items" -- Text struc.xalign = TEXT_ALIGN_CENTER-- Horizontal Alignment struc.yalign = TEXT_ALIGN_CENTER -- Vertical Alignment draw.Text( struc ) end GUI_Prof_Crafting_List:SetPadding(5) GUI_Prof_Crafting_List:SetSpacing(5) GUI_Prof_Crafting_List:EnableHorizontal(3) GUI_Prof_Crafting_List:EnableVerticalScrollbar(true) local WidthSize = 100 local Craft_Icon_ent = ents.CreateClientProp("prop_physics") Craft_Icon_ent:SetPos(Vector(0,0,0)) Craft_Icon_ent:Spawn() Craft_Icon_ent:Activate() for _,data in pairs(GAMEMODE.OCRP_Professions["Pro_Crafting"].Recipies) do local GUI_Craft_Item_Panel = vgui.Create("DPanel") GUI_Craft_Item_Panel:SetParent(GUI_Prof_Crafting_List) GUI_Craft_Item_Panel:SetSize(220,150) GUI_Craft_Item_Panel:SetPos(0,0) GUI_Craft_Item_Panel.Paint = function() draw.RoundedBox(8,0,0,GUI_Craft_Item_Panel:GetWide(),GUI_Craft_Item_Panel:GetTall(),Color( 60, 60, 60, 155 )) end local GUI_Craft_Item_Icon = vgui.Create("DModelPanel") GUI_Craft_Item_Icon:SetParent(GUI_Craft_Item_Panel) GUI_Craft_Item_Icon:SetPos(10,10) GUI_Craft_Item_Icon:SetSize(WidthSize,WidthSize) GUI_Craft_Item_Icon:SetModel(GAMEMODE.OCRP_Items[data.Item].Model) Craft_Icon_ent:SetModel(GAMEMODE.OCRP_Items[data.Item].Model) if GAMEMODE.OCRP_Items[data.Item].Angle != nil then GUI_Craft_Item_Icon:GetEntity():SetAngles(GAMEMODE.OCRP_Items[data.Item].Angle) end local center = Craft_Icon_ent:OBBCenter() local dist = Craft_Icon_ent:BoundingRadius()*1.2 GUI_Craft_Item_Icon:SetLookAt(center) GUI_Craft_Item_Icon:SetCamPos(center+Vector(dist,dist,0)) local GUI_Craft_Item_Name = vgui.Create("DLabel") GUI_Craft_Item_Name:SetColor(Color(255,255,255,255)) GUI_Craft_Item_Name:SetFont("UiBold") GUI_Craft_Item_Name:SetText(GAMEMODE.OCRP_Items[data.Item].Name) GUI_Craft_Item_Name:SizeToContents() GUI_Craft_Item_Name:SetParent(GUI_Craft_Item_Panel) surface.SetFont("UiBold") local x,y = surface.GetTextSize(GAMEMODE.OCRP_Items[data.Item].Name) GUI_Craft_Item_Name:SetPos(60 - x/2,10-y/2) local GUI_Craft_Item_Desc = vgui.Create("DLabel") GUI_Craft_Item_Desc:SetColor(Color(255,255,255,255)) GUI_Craft_Item_Desc:SetFont("UiBold") GUI_Craft_Item_Desc:SetText(GAMEMODE.OCRP_Items[data.Item].Desc) GUI_Craft_Item_Desc:SizeToContents() GUI_Craft_Item_Desc:SetParent(GUI_Craft_Item_Panel) surface.SetFont("UiBold") local x,y = surface.GetTextSize(GAMEMODE.OCRP_Items[data.Item].Desc) GUI_Craft_Item_Desc:SetPos(60 - x/2,100-y/2) if data.Amount != nil && data.Amount > 1 then local GUI_Craft_Item_Amt = vgui.Create("DLabel") GUI_Craft_Item_Amt:SetColor(Color(255,255,255,255)) GUI_Craft_Item_Amt:SetFont("UiBold") GUI_Craft_Item_Amt:SetText("x"..data.Amount) GUI_Craft_Item_Amt:SizeToContents() GUI_Craft_Item_Amt:SetParent(GUI_Craft_Item_Panel) surface.SetFont("UiBold") local x,y = surface.GetTextSize("x"..data.Amount) GUI_Craft_Item_Amt:SetPos(60 - x/2,25-y/2) end if data.HeatSource != nil && data.HeatSource then local GUI_Craft_Heat = vgui.Create("DLabel") GUI_Craft_Heat:SetColor(Color(255,100,100,255)) GUI_Craft_Heat:SetFont("UiBold") GUI_Craft_Heat:SetText("Furnace Required") GUI_Craft_Heat:SizeToContents() GUI_Craft_Heat:SetParent(GUI_Craft_Item_Panel) surface.SetFont("UiBold") local x,y = surface.GetTextSize("Furnace Required") GUI_Craft_Heat:SetPos(55 - x/2,30-y/2) elseif data.WaterSource != nil && data.WaterSource then local GUI_Craft_Water = vgui.Create("DLabel") GUI_Craft_Water:SetColor(Color(100,100,255,255)) GUI_Craft_Water:SetFont("UiBold") GUI_Craft_Water:SetText("Sink Required") GUI_Craft_Water:SizeToContents() GUI_Craft_Water:SetParent(GUI_Craft_Item_Panel) surface.SetFont("UiBold") local x,y = surface.GetTextSize("Water Source Required") GUI_Craft_Water:SetPos(55 - x/2,50-y/2) elseif data.Explosive != nil && data.Explosive then local GUI_Craft_Explosive = vgui.Create("DLabel") GUI_Craft_Explosive:SetColor(Color(255,150,90,255)) GUI_Craft_Explosive:SetFont("UiBold") GUI_Craft_Explosive:SetText("WARNING Explosive") GUI_Craft_Explosive:SizeToContents() GUI_Craft_Explosive:SetParent(GUI_Craft_Item_Panel) surface.SetFont("UiBold") local x,y = surface.GetTextSize("WARNING Explosive") GUI_Craft_Explosive:SetPos(55 - x/2,50-y/2) end local GUI_Label_Requirements = vgui.Create("DLabel") GUI_Label_Requirements:SetColor(Color(255,255,255,255)) GUI_Label_Requirements:SetFont("UiBold") GUI_Label_Requirements:SetText("Requirements : ") GUI_Label_Requirements:SizeToContents() GUI_Label_Requirements:SetParent(GUI_Craft_Item_Panel) surface.SetFont("UiBold") local x,y = surface.GetTextSize("Requirements : ") GUI_Label_Requirements:SetPos(165 - x/2,10-y/2) local Number = 30 for k,reqitem in pairs(data.Requirements) do local GUI_Item_RequireMent = vgui.Create("DLabel") GUI_Item_RequireMent:SetColor(Color(255,255,255,255)) GUI_Item_RequireMent:SetFont("UiBold") GUI_Item_RequireMent:SetText(GAMEMODE.OCRP_Items[reqitem].Name) GUI_Item_RequireMent:SizeToContents() GUI_Item_RequireMent:SetParent(GUI_Craft_Item_Panel) surface.SetFont("UiBold") local x,y = surface.GetTextSize(GAMEMODE.OCRP_Items[reqitem].Name) GUI_Item_RequireMent:SetPos(165 - x/2,Number-y/2) Number = Number + 13 end local GUI_Craft_Item_Craft = vgui.Create("DButton") GUI_Craft_Item_Craft:SetParent(GUI_Craft_Item_Panel) GUI_Craft_Item_Craft:SetPos(5,120) GUI_Craft_Item_Craft:SetSize(210,20) GUI_Craft_Item_Craft:SetText("") GUI_Craft_Item_Craft.Paint = function() if OCRP_Professions[activeprof].Exp.Skill >= data.XPRequired.Skill && OCRP_Professions[activeprof].Exp.Mechanical >= data.XPRequired.Mechanical && OCRP_Professions[activeprof].Exp.Practical >= data.XPRequired.Practical then draw.RoundedBox(8,0,0,GUI_Craft_Item_Craft:GetWide(),GUI_Craft_Item_Craft:GetTall(),Color( 60, 60, 60, 155 )) draw.RoundedBox(8,1,1,GUI_Craft_Item_Craft:GetWide()-2,GUI_Craft_Item_Craft:GetTall()-2,Color(OCRP_Options.Color.r + 20,OCRP_Options.Color.g + 20,OCRP_Options.Color.b + 20,155)) local struc = {} struc.pos = {} struc.pos[1] = 105 -- x pos struc.pos[2] = 10 -- y pos struc.color = Color(255,255,255,255) -- Red struc.font = "UiBold" -- Font struc.text = "Craft" -- Text struc.xalign = TEXT_ALIGN_CENTER-- Horizontal Alignment struc.yalign = TEXT_ALIGN_CENTER -- Vertical Alignment draw.Text( struc ) local struc = {} struc.pos = {} struc.pos[1] = 150 -- x pos struc.pos[2] = 10 -- y pos struc.color = Color( 255, 255, 30, 255 ) -- Red struc.font = "UiBold" -- Font struc.text = "+"..data.XPOnDoing.Skill -- Text struc.xalign = TEXT_ALIGN_CENTER-- Horizontal Alignment struc.yalign = TEXT_ALIGN_CENTER -- Vertical Alignment draw.Text( struc ) local struc = {} struc.pos = {} struc.pos[1] = 170 -- x pos struc.pos[2] = 10 -- y pos struc.color = Color( 30, 255, 255, 255 ) -- Red struc.font = "UiBold" -- Font struc.text = "+"..data.XPOnDoing.Mechanical -- Text struc.xalign = TEXT_ALIGN_CENTER-- Horizontal Alignment struc.yalign = TEXT_ALIGN_CENTER -- Vertical Alignment draw.Text( struc ) local struc = {} struc.pos = {} struc.pos[1] = 190 -- x pos struc.pos[2] = 10 -- y pos struc.color = Color( 250, 160, 0, 255 ) -- Red struc.font = "UiBold" -- Font struc.text = "+"..data.XPOnDoing.Practical -- struc.xalign = TEXT_ALIGN_CENTER-- Horizontal Alignment struc.yalign = TEXT_ALIGN_CENTER -- Vertical Alignment draw.Text( struc ) else local struc = {} struc.pos = {} struc.pos[1] = 40 -- x pos struc.pos[2] = 10 -- y pos struc.color = Color( 255, 255, 30, 155 ) -- Red struc.font = "UiBold" -- Font struc.text = data.XPRequired.Skill.." Required" -- Text struc.xalign = TEXT_ALIGN_CENTER-- Horizontal Alignment struc.yalign = TEXT_ALIGN_CENTER -- Vertical Alignment draw.Text( struc ) local struc = {} struc.pos = {} struc.pos[1] = 110 -- x pos struc.pos[2] = 10 -- y pos struc.color = Color( 30, 155, 155, 155 ) -- Red struc.font = "UiBold" -- Font struc.text = data.XPRequired.Mechanical.." Required" -- Text struc.xalign = TEXT_ALIGN_CENTER-- Horizontal Alignment struc.yalign = TEXT_ALIGN_CENTER -- Vertical Alignment draw.Text( struc ) local struc = {} struc.pos = {} struc.pos[1] = 180 -- x pos struc.pos[2] = 10 -- y pos struc.color = Color( 180, 90, 0, 155 ) -- Red struc.font = "UiBold" -- Font struc.text = data.XPRequired.Practical.." Required" -- Text struc.xalign = TEXT_ALIGN_CENTER-- Horizontal Alignment struc.yalign = TEXT_ALIGN_CENTER -- Vertical Alignment draw.Text( struc ) end end GUI_Craft_Item_Craft.DoClick = function() if OCRP_Professions[activeprof].Exp.Skill >= data.XPRequired.Skill && OCRP_Professions[activeprof].Exp.Mechanical >= data.XPRequired.Mechanical && OCRP_Professions[activeprof].Exp.Practical >= data.XPRequired.Practical then RunConsoleCommand("OCRP_CraftItem",data.Item) end end GUI_Prof_Crafting_List:AddItem(GUI_Craft_Item_Panel) end Craft_Icon_ent:Remove() local GUI_Prof_Bar = vgui.Create("DButton") GUI_Prof_Bar:SetParent(GUI_Prof_Panel_List) GUI_Prof_Bar:SetSize(330,60) GUI_Prof_Bar:SetPos(23,400) GUI_Prof_Bar:SetText("") GUI_Prof_Bar.Paint = function() draw.RoundedBox(8,0,0,GUI_Prof_Bar:GetWide(),GUI_Prof_Bar:GetTall(),Color( 55, 55, 55, 255 )) draw.RoundedBox(8,1,1,GUI_Prof_Bar:GetWide()-2,GUI_Prof_Bar:GetTall()-2,Color( 180, 90, 0, 155 )) local totalxp = OCRP_Professions[activeprof].Exp.Mechanical + OCRP_Professions[activeprof].Exp.Practical if totalxp > 20 then draw.RoundedBox(8,1,(GUI_Prof_Bar:GetTall()-2)-(GUI_Prof_Bar:GetTall()-2)*(totalxp/1000),(GUI_Prof_Bar:GetWide()-2),(GUI_Prof_Bar:GetTall()-2)*(totalxp/1000),Color(OCRP_Options.Color.r + 20,OCRP_Options.Color.g + 20,OCRP_Options.Color.b + 20,155)) end local struc = {} struc.pos = {} struc.pos[1] = 165 -- x pos struc.pos[2] = 30 -- y pos struc.color = Color(255,255,255,255) -- Red struc.font = "UiBold" -- Font struc.text = totalxp.."/1000" -- Text struc.xalign = TEXT_ALIGN_CENTER-- Horizontal Alignment struc.yalign = TEXT_ALIGN_CENTER -- Vertical Alignment draw.Text( struc ) end local GUI_Prof_Bar = vgui.Create("DBevel") GUI_Prof_Bar:SetParent(GUI_Prof_Panel_List) GUI_Prof_Bar:SetSize(330,20) GUI_Prof_Bar:SetPos(373,400) GUI_Prof_Bar:SetText("") GUI_Prof_Bar.Paint = function() draw.RoundedBox(4,0,0,GUI_Prof_Bar:GetWide(),GUI_Prof_Bar:GetTall(),Color( 55, 55, 55, 255 )) draw.RoundedBox(4,1,1,GUI_Prof_Bar:GetWide()-2,GUI_Prof_Bar:GetTall()-2,Color( 155, 155, 30, 155 )) if OCRP_Professions[activeprof].Exp.Skill > 20 then draw.RoundedBox(4,1,(GUI_Prof_Bar:GetTall()-2)-(GUI_Prof_Bar:GetTall()-2)*(OCRP_Professions[activeprof].Exp.Skill/500),(GUI_Prof_Bar:GetWide()-2),(GUI_Prof_Bar:GetTall()-2)*(OCRP_Professions[activeprof].Exp.Skill/500),Color( 185, 185, 30, 155 )) end local struc = {} struc.pos = {} struc.pos[1] = 165 -- x pos struc.pos[2] = 10 -- y pos struc.color = Color(255,255,255,255) -- Red struc.font = "UiBold" -- Font struc.text = "Skill "..OCRP_Professions[activeprof].Exp.Skill.."/1000 xp" -- Text struc.xalign = TEXT_ALIGN_CENTER-- Horizontal Alignment struc.yalign = TEXT_ALIGN_CENTER -- Vertical Alignment draw.Text( struc ) end local GUI_Prof_Bar = vgui.Create("DBevel") GUI_Prof_Bar:SetParent(GUI_Prof_Panel_List) GUI_Prof_Bar:SetSize(330,20) GUI_Prof_Bar:SetPos(373,420) GUI_Prof_Bar:SetText("") GUI_Prof_Bar.Paint = function() draw.RoundedBox(4,0,0,GUI_Prof_Bar:GetWide(),GUI_Prof_Bar:GetTall(),Color( 55, 55, 55, 255 )) draw.RoundedBox(4,1,1,GUI_Prof_Bar:GetWide()-2,GUI_Prof_Bar:GetTall()-2,Color( 30, 155, 155, 155 )) if OCRP_Professions[activeprof].Exp.Mechanical > 20 then draw.RoundedBox(4,1,(GUI_Prof_Bar:GetTall()-2)-(GUI_Prof_Bar:GetTall()-2)*(OCRP_Professions[activeprof].Exp.Mechanical/500),(GUI_Prof_Bar:GetWide()-2),(GUI_Prof_Bar:GetTall()-2)*(OCRP_Professions[activeprof].Exp.Mechanical/500),Color( 30, 185, 185, 155 )) end local struc = {} struc.pos = {} struc.pos[1] = 165 -- x pos struc.pos[2] = 10 -- y pos struc.color = Color(255,255,255,255) -- Red struc.font = "UiBold" -- Font struc.text = "Mechanical "..OCRP_Professions[activeprof].Exp.Mechanical.."/1000 xp" -- Text struc.xalign = TEXT_ALIGN_CENTER-- Horizontal Alignment struc.yalign = TEXT_ALIGN_CENTER -- Vertical Alignment draw.Text( struc ) end local GUI_Prof_Bar = vgui.Create("DBevel") GUI_Prof_Bar:SetParent(GUI_Prof_Panel_List) GUI_Prof_Bar:SetSize(330,20) GUI_Prof_Bar:SetPos(373,440) GUI_Prof_Bar:SetText("") GUI_Prof_Bar.Paint = function() draw.RoundedBox(4,0,0,GUI_Prof_Bar:GetWide(),GUI_Prof_Bar:GetTall(),Color( 55, 55, 55, 255 )) draw.RoundedBox(4,1,1,GUI_Prof_Bar:GetWide()-2,GUI_Prof_Bar:GetTall()-2,Color( 180, 90, 0, 155 )) if OCRP_Professions[activeprof].Exp.Practical > 20 then draw.RoundedBox(4,1,(GUI_Prof_Bar:GetTall()-2)-(GUI_Prof_Bar:GetTall()-2)*(OCRP_Professions[activeprof].Exp.Practical/500),(GUI_Prof_Bar:GetWide()-2),(GUI_Prof_Bar:GetTall()-2)*(OCRP_Professions[activeprof].Exp.Practical/500),Color(OCRP_Options.Color.r + 20,OCRP_Options.Color.g + 20,OCRP_Options.Color.b + 20,155)) end local struc = {} struc.pos = {} struc.pos[1] = 165 -- x pos struc.pos[2] = 10 -- y pos struc.color = Color(255,255,255,255) -- Red struc.font = "UiBold" -- Font struc.text = "Practical "..OCRP_Professions[activeprof].Exp.Practical.."/500 xp" -- Text struc.xalign = TEXT_ALIGN_CENTER-- Horizontal Alignment struc.yalign = TEXT_ALIGN_CENTER -- Vertical Alignment draw.Text( struc ) end local GUI_Prof_Reselect = vgui.Create("DButton") GUI_Prof_Reselect:SetParent(GUI_Prof_Panel_List) GUI_Prof_Reselect:SetSize(20,20) GUI_Prof_Reselect:SetPos(716,10) GUI_Prof_Reselect:SetText("") GUI_Prof_Reselect:SetToolTip("Re-select Profession") GUI_Prof_Reselect.Paint = function() surface.SetMaterial(OC_1) surface.DrawTexturedRect(0,0,GUI_Prof_Reselect:GetWide(),GUI_Prof_Reselect:GetTall()) end GUI_Prof_Reselect.DoClick = function() net.Start("OCRP_ResetProf") net.SendToServer() end else local GUI_Prof_Name = vgui.Create("DLabel") GUI_Prof_Name:SetColor(Color(255,255,255,255)) surface.SetFont("Trebuchet22") local x,y = surface.GetTextSize("Professional "..GAMEMODE.OCRP_Professions[activeprof].Name) GUI_Prof_Name:SetPos(373 - x/2,25 - y/2) GUI_Prof_Name:SetFont("Trebuchet22") GUI_Prof_Name:SetText("Professional "..GAMEMODE.OCRP_Professions[activeprof].Name) GUI_Prof_Name:SizeToContents() GUI_Prof_Name:SetParent(GUI_Prof_Panel_List) local GUI_Prof_Bar = vgui.Create("DButton") GUI_Prof_Bar:SetParent(GUI_Prof_Panel_List) GUI_Prof_Bar:SetSize(60,400) GUI_Prof_Bar:SetPos(23,40) GUI_Prof_Bar:SetText("") GUI_Prof_Bar.Paint = function() draw.RoundedBox(8,0,0,GUI_Prof_Bar:GetWide(),GUI_Prof_Bar:GetTall(),Color( 55, 55, 55, 255 )) draw.RoundedBox(8,1,1,GUI_Prof_Bar:GetWide()-2,GUI_Prof_Bar:GetTall()-2,Color( 180, 90, 0, 155 )) if OCRP_Professions[activeprof].Exp > 20 then draw.RoundedBox(8,1,(GUI_Prof_Bar:GetTall()-2)-(GUI_Prof_Bar:GetTall()-2)*(OCRP_Professions[activeprof].Exp/1000),(GUI_Prof_Bar:GetWide()-2),(GUI_Prof_Bar:GetTall()-2)*(OCRP_Professions[activeprof].Exp/1000),Color(OCRP_Options.Color.r + 20,OCRP_Options.Color.g + 20,OCRP_Options.Color.b + 20,155)) end local struc = {} struc.pos = {} struc.pos[1] = 30 -- x pos struc.pos[2] = 200 -- y pos struc.color = Color(255,255,255,255) -- Red struc.font = "UiBold" -- Font struc.text = OCRP_Professions[activeprof].Exp.."/1000" -- Text struc.xalign = TEXT_ALIGN_CENTER-- Horizontal Alignment struc.yalign = TEXT_ALIGN_CENTER -- Vertical Alignment draw.Text( struc ) end if GAMEMODE.OCRP_Professions[activeprof].MenuFunc != nil then GAMEMODE.OCRP_Professions[activeprof].MenuFunc(GUI_Prof_Panel_List,activeprof) end local GUI_Prof_Reselect = vgui.Create("DButton") GUI_Prof_Reselect:SetParent(GUI_Prof_Panel_List) GUI_Prof_Reselect:SetSize(20,20) GUI_Prof_Reselect:SetPos(716,10) GUI_Prof_Reselect:SetText("") GUI_Prof_Reselect:SetToolTip("Re-select Profession") GUI_Prof_Reselect.Paint = function() surface.SetMaterial(OC_1) surface.DrawTexturedRect(0,0,GUI_Prof_Reselect:GetWide(),GUI_Prof_Reselect:GetTall()) end GUI_Prof_Reselect.DoClick = function() net.Start("OCRP_ResetProf") net.SendToServer() end return GUI_Prof_Panel_List end return GUI_Prof_Panel_List end
mit
Arcscion/Shadowlyre
scripts/zones/Batallia_Downs/npcs/qm4.lua
17
1589
----------------------------------- -- Area: Batallia Downs -- NPC: qm4 (???) -- ----------------------------------- package.loaded["scripts/zones/Batallia_Downs/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Batallia_Downs/TextIDs"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) local missionProgress = player:getVar("COP_Tenzen_s_Path") if (player:getCurrentMission(COP) == THREE_PATHS and missionProgress == 5) then player:startEvent(0x0000); elseif (player:getCurrentMission(COP) == THREE_PATHS and (missionProgress == 6 or missionProgress == 7) and player:hasKeyItem(DELKFUTT_RECOGNITION_DEVICE) == false) then player:addKeyItem(DELKFUTT_RECOGNITION_DEVICE); player:messageSpecial(KEYITEM_OBTAINED,DELKFUTT_RECOGNITION_DEVICE); end end; ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) 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 == 0x0000) then player:setVar("COP_Tenzen_s_Path",6); end end;
gpl-3.0
Arcscion/Shadowlyre
scripts/globals/spells/choke.lua
5
2062
----------------------------------------- -- Spell: Choke -- Deals wind damage that lowers an enemy's vitality and gradually reduces its HP. ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) if (target:getStatusEffect(EFFECT_FROST) ~= nil) then spell:setMsg(msgBasic.MAGIC_NO_EFFECT); -- no effect else local dINT = caster:getStat(MOD_INT)-target:getStat(MOD_INT); local params = {}; params.diff = nil; params.attribute = MOD_INT; params.skillType = 36; params.bonus = 0; params.effect = nil; local resist = applyResistance(caster, target, spell, params); if (resist <= 0.125) then spell:setMsg(msgBasic.MAGIC_RESIST); else if (target:getStatusEffect(EFFECT_RASP) ~= nil) then target:delStatusEffect(EFFECT_RASP); end; local sINT = caster:getStat(MOD_INT); local DOT = getElementalDebuffDOT(sINT); local effect = target:getStatusEffect(EFFECT_CHOKE); local noeffect = false; if (effect ~= nil) then if (effect:getPower() >= DOT) then noeffect = true; end; end; if (noeffect) then spell:setMsg(msgBasic.MAGIC_NO_EFFECT); -- no effect else if (effect ~= nil) then target:delStatusEffect(EFFECT_CHOKE); end; spell:setMsg(msgBasic.MAGIC_ENFEEB); local duration = math.floor(ELEMENTAL_DEBUFF_DURATION * resist); target:addStatusEffect(EFFECT_CHOKE,DOT, 3, ELEMENTAL_DEBUFF_DURATION,FLAG_ERASABLE); end; end; end; return EFFECT_CHOKE; end;
gpl-3.0
Arcscion/Shadowlyre
scripts/zones/Boneyard_Gully/npcs/_081.lua
22
1453
----------------------------------- -- Area: Boneyard_Gully -- NPC: _081 (Dark Miasma) ----------------------------------- package.loaded["scripts/zones/Boneyard_Gully/TextIDs"] = nil; ----------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Boneyard_Gully/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; else 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
Arcscion/Shadowlyre
scripts/zones/Phomiuna_Aqueducts/npcs/_0rm.lua
3
1338
----------------------------------- -- Area: Phomiuna_Aqueducts -- NPC: _0rm (Oil lamp) -- Notes: Opens South door at J-7 from inside. -- !pos -63.703 -26.227 83.000 27 ----------------------------------- package.loaded["scripts/zones/Phomiuna_Aqueducts/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Phomiuna_Aqueducts/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local DoorOffset = npc:getID() - 1; if (GetNPCByID(DoorOffset):getAnimation() == 9) then if (player:getZPos() < 84) then npc:openDoor(15); -- lamp animation GetNPCByID(DoorOffset):openDoor(7); -- _0rf 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); end;
gpl-3.0
jono659/enko
scripts/globals/abilities/pets/flaming_crush.lua
6
1348
--------------------------------------------------- -- Flaming Crush M=10, 2, 2? (STILL don't know) --------------------------------------------------- require("/scripts/globals/settings"); require("/scripts/globals/status"); require("/scripts/globals/summon"); require("/scripts/globals/magic"); require("/scripts/globals/monstertpmoves"); --------------------------------------------------- function onAbilityCheck(player, target, ability) return 0,0; end; function onPetAbility(target, pet, skill) local numhits = 3; local accmod = 1; local dmgmod = 10; local dmgmodsubsequent = 1; local totaldamage = 0; local damage = AvatarPhysicalMove(pet,target,skill,numhits,accmod,dmgmod,dmgmodsubsequent,TP_NO_EFFECT,1,2,3); --get resist multiplier (1x if no resist) local resist = applyPlayerResistance(pet,-1,target,pet:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL, ELE_FIRE); --get the resisted damage damage.dmg = damage.dmg*resist; --add on bonuses (staff/day/weather/jas/mab/etc all go in this function) damage.dmg = mobAddBonuses(pet,spell,target,damage.dmg,1); totaldamage = AvatarFinalAdjustments(damage.dmg,pet,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,numhits); target:delHP(totaldamage); target:updateEnmityFromDamage(pet,totaldamage); return totaldamage; end
gpl-3.0
MRunFoss/skynet
examples/login/client.lua
67
3950
package.cpath = "luaclib/?.so" local socket = require "clientsocket" local crypt = require "crypt" if _VERSION ~= "Lua 5.3" then error "Use lua 5.3" end local fd = assert(socket.connect("127.0.0.1", 8001)) local function writeline(fd, text) socket.send(fd, text .. "\n") end local function unpack_line(text) local from = text:find("\n", 1, true) if from then return text:sub(1, from-1), text:sub(from+1) end return nil, text end local last = "" local function unpack_f(f) local function try_recv(fd, last) local result result, last = f(last) if result then return result, last end local r = socket.recv(fd) if not r then return nil, last end if r == "" then error "Server closed" end return f(last .. r) end return function() while true do local result result, last = try_recv(fd, last) if result then return result end socket.usleep(100) end end end local readline = unpack_f(unpack_line) local challenge = crypt.base64decode(readline()) local clientkey = crypt.randomkey() writeline(fd, crypt.base64encode(crypt.dhexchange(clientkey))) local secret = crypt.dhsecret(crypt.base64decode(readline()), clientkey) print("sceret is ", crypt.hexencode(secret)) local hmac = crypt.hmac64(challenge, secret) writeline(fd, crypt.base64encode(hmac)) local token = { server = "sample", user = "hello", pass = "password", } local function encode_token(token) return string.format("%s@%s:%s", crypt.base64encode(token.user), crypt.base64encode(token.server), crypt.base64encode(token.pass)) end local etoken = crypt.desencode(secret, encode_token(token)) local b = crypt.base64encode(etoken) writeline(fd, crypt.base64encode(etoken)) local result = readline() print(result) local code = tonumber(string.sub(result, 1, 3)) assert(code == 200) socket.close(fd) local subid = crypt.base64decode(string.sub(result, 5)) print("login ok, subid=", subid) ----- connect to game server local function send_request(v, session) local size = #v + 4 local package = string.pack(">I2", size)..v..string.pack(">I4", session) socket.send(fd, package) return v, session end local function recv_response(v) local size = #v - 5 local content, ok, session = string.unpack("c"..tostring(size).."B>I4", v) return ok ~=0 , content, session end local function unpack_package(text) local size = #text if size < 2 then return nil, text end local s = text:byte(1) * 256 + text:byte(2) if size < s+2 then return nil, text end return text:sub(3,2+s), text:sub(3+s) end local readpackage = unpack_f(unpack_package) local function send_package(fd, pack) local package = string.pack(">s2", pack) socket.send(fd, package) end local text = "echo" local index = 1 print("connect") fd = assert(socket.connect("127.0.0.1", 8888)) last = "" local handshake = string.format("%s@%s#%s:%d", crypt.base64encode(token.user), crypt.base64encode(token.server),crypt.base64encode(subid) , index) local hmac = crypt.hmac64(crypt.hashkey(handshake), secret) send_package(fd, handshake .. ":" .. crypt.base64encode(hmac)) print(readpackage()) print("===>",send_request(text,0)) -- don't recv response -- print("<===",recv_response(readpackage())) print("disconnect") socket.close(fd) index = index + 1 print("connect again") fd = assert(socket.connect("127.0.0.1", 8888)) last = "" local handshake = string.format("%s@%s#%s:%d", crypt.base64encode(token.user), crypt.base64encode(token.server),crypt.base64encode(subid) , index) local hmac = crypt.hmac64(crypt.hashkey(handshake), secret) send_package(fd, handshake .. ":" .. crypt.base64encode(hmac)) print(readpackage()) print("===>",send_request("fake",0)) -- request again (use last session 0, so the request message is fake) print("===>",send_request("again",1)) -- request again (use new session) print("<===",recv_response(readpackage())) print("<===",recv_response(readpackage())) print("disconnect") socket.close(fd)
mit
Arcscion/Shadowlyre
scripts/zones/Arrapago_Reef/TextIDs.lua
3
1225
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6380; -- You cannot obtain the item <item> come back again after sorting your inventory ITEM_OBTAINED = 6386; -- Obtained: <item> GIL_OBTAINED = 6387; -- Obtained <number> gil KEYITEM_OBTAINED = 6389; -- Obtained key item: <keyitem> FISHING_MESSAGE_OFFSET = 7047; -- You can't fish here -- Assault CANNOT_ENTER = 8443; -- You cannot enter at this time. Please wait a while before trying again. AREA_FULL = 8444; -- This area is fully occupied. You were unable to enter. MEMBER_NO_REQS = 8448; -- Not all of your party members meet the requirements for this objective. Unable to enter area. MEMBER_TOO_FAR = 8452; -- One or more party members are too far away from the entrance. Unable to enter area. -- Other Texts YOU_NO_REQS = 7582; -- You do not meet the requirements to enter the battlefield NOTHING_HAPPENS = 119; -- Nothing happens... RESPONSE = 7327; -- There is no response... -- Medusa MEDUSA_ENGAGE = 8554; -- Foolish two-legs... Have you forgotten the terrible power of the gorgons you created? It is time you were reminded... MEDUSA_DEATH = 8555; -- No... I cannot leave my sisters...
gpl-3.0
Arcscion/Shadowlyre
scripts/zones/Xarcabard/npcs/Tememe_WW.lua
3
3321
----------------------------------- -- Area: Xarcabard -- NPC: Tememe, W.W. -- Type: Border Conquest Guards -- !pos -133.678 -22.517 112.224 112 ----------------------------------- package.loaded["scripts/zones/Xarcabard/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Xarcabard/TextIDs"); local guardnation = NATION_WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = VALDEAUNIA; local csid = 0x7ff6; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
Arcscion/Shadowlyre
scripts/zones/Cape_Teriggan/mobs/Tegmine.lua
3
1997
---------------------------------- -- Area: Cape Teriggan -- NM: Tegmine ----------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/msg"); ----------------------------------- -- onMobInitialize ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID()); end; ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(mob,target,damage) -- Wiki says nothing about proc rate, going with 80% for now. -- I remember it going off every hit when I fought him. local chance = 80; local LV_diff = target:getMainLvl() - mob:getMainLvl(); if (target:getMainLvl() > mob:getMainLvl()) then chance = chance - 5 * LV_diff; chance = utils.clamp(chance, 5, 95); end if (math.random(0,99) >= chance) then return 0,0,0; else local INT_diff = mob:getStat(MOD_INT) - target:getStat(MOD_INT); if (INT_diff > 20) then INT_diff = 20 + (INT_diff - 20) / 2; end local dmg = INT_diff+LV_diff+damage/2; local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(mob, ELE_WATER, target, dmg, params); dmg = dmg * applyResistanceAddEffect(mob,target,ELE_WATER,0); dmg = adjustForTarget(target,dmg,ELE_WATER); dmg = finalMagicNonSpellAdjustments(mob,target,ELE_WATER,dmg); return SUBEFFECT_WATER_DAMAGE, msgBasic.ADD_EFFECT_DMG, dmg; end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) -- UpdateNMSpawnPoint(mob:getID()); mob:setRespawnTime(math.random((7200),(7800))); -- 120 to 130 min end;
gpl-3.0
jono659/enko
scripts/zones/Chateau_dOraguille/npcs/Chalvatot.lua
9
4390
----------------------------------- -- Area: Chateau d'Oraguille -- NPC: Chalvatot -- Finish Mission "The Crystal Spring" -- Start & Finishes Quests: Her Majesty's Garden -- Involved in Quest: Lure of the Wildcat (San d'Oria) -- @pos -105 0.1 72 233 ----------------------------------- package.loaded["scripts/zones/Chateau_dOraguille/TextIDs"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/quests"); require("scripts/zones/Chateau_dOraguille/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer if(player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then player:messageSpecial(FLYER_REFUSED); end elseif(trade:hasItemQty(533,1) and trade:getItemCount() == 1) then if(player:getQuestStatus(SANDORIA,HER_MAJESTY_S_GARDEN) == QUEST_ACCEPTED) then player:startEvent(0x0053); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local herMajestysGarden = player:getQuestStatus(SANDORIA,HER_MAJESTY_S_GARDEN); local currentMission = player:getCurrentMission(SANDORIA); local MissionStatus = player:getVar("MissionStatus"); local circleOfTime = player:getQuestStatus(JEUNO,THE_CIRCLE_OF_TIME); local WildcatSandy = player:getVar("WildcatSandy"); if(player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,19) == false) then player:startEvent(0x0231); elseif(player:getCurrentMission(SANDORIA) == THE_CRYSTAL_SPRING and player:getVar("MissionStatus") == 3) then player:startEvent(0x022c); elseif(herMajestysGarden == QUEST_AVAILABLE and player:getFameLevel(SANDORIA) >= 4) then player:startEvent(0x0054); elseif(currentMission == LEAUTE_S_LAST_WISHES and MissionStatus == 4 and player:hasKeyItem(DREAMROSE)) then player:startEvent(0x006f); elseif(herMajestysGarden == QUEST_ACCEPTED) then player:startEvent(0x0052); elseif(circleOfTime == QUEST_ACCEPTED) then if (player:getVar("circleTime") == 5) then player:startEvent(0x0063); elseif (player:getVar("circleTime") == 6) then player:startEvent(0x0062); elseif (player:getVar("circleTime") == 7) then player:startEvent(0x0061); elseif (player:getVar("circleTime") == 9) then player:startEvent(0x0060); end else player:startEvent(0x0213); 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 == 0x022c or csid == 0x006f) then finishMissionTimeline(player,3,csid,option); elseif(csid == 0x0231) then player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",19,true); elseif(csid == 0x0054 and option == 1) then player:addQuest(SANDORIA,HER_MAJESTY_S_GARDEN); elseif(csid == 0x0053) then player:tradeComplete(); player:addKeyItem(MAP_OF_THE_NORTHLANDS_AREA); player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_THE_NORTHLANDS_AREA); player:addFame(SANDORIA,SAN_FAME*30); player:completeQuest(SANDORIA,HER_MAJESTY_S_GARDEN); elseif (csid == 0x0063) then if (option == 1) then player:setVar("circleTime",7); player:addKeyItem(MOON_RING); player:messageSpecial(KEYITEM_OBTAINED,MOON_RING); else player:setVar("circleTime",6); end elseif (csid == 0x0062) then if (option == 1) then player:setVar("circleTime",7); player:addKeyItem(MOON_RING); player:messageSpecial(KEYITEM_OBTAINED,MOON_RING); end elseif (csid == 0x0060) then if (player:getFreeSlotsCount() ~= 0) then player:addItem(12647); player:messageSpecial(ITEM_OBTAINED,12647) player:completeQuest(JEUNO,THE_CIRCLE_OF_TIME); player:addTitle(PARAGON_OF_BARD_EXCELLENCE); player:setVar("circleTime",0); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED); end end end;
gpl-3.0
jono659/enko
scripts/zones/Bastok_Mines/npcs/Aulavia.lua
30
1603
----------------------------------- -- Area: Bastok Mines -- NPC: Aulavia -- Regional Marchant NPC -- Only sells when Bastok controls Vollbow. ----------------------------------- require("scripts/globals/events/harvest_festivals"); require("scripts/globals/shop"); require("scripts/globals/conquest"); package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) onHalloweenTrade(player,trade,npc) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RegionOwner = GetRegionOwner(VOLLBOW); if (RegionOwner ~= BASTOK) then player:showText(npc,AULAVIA_CLOSED_DIALOG); else player:showText(npc,AULAVIA_OPEN_DIALOG); stock = { 0x27c, 119, --Chamomile 0x360, 88, --Fish Scales 0x3a8, 14, --Rock Salt 0x582, 1656 --Sweet William } showShop(player,BASTOK,stock); 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
Arcscion/Shadowlyre
scripts/zones/Upper_Jeuno/npcs/Sibila-Mobla.lua
17
1382
----------------------------------- -- Area: Upper Jeuno -- NPC: Sibila-Mobla -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Upper_Jeuno/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatJeuno = player:getVar("WildcatJeuno"); if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,5) == false) then player:startEvent(10083); else player:startEvent(0x0062); 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 == 10083) then player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",5,true); end end;
gpl-3.0