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
RedeMinas/portal
lib_main.lua
1
3013
--- main global parameteres SCREEN_WIDTH, SCREEN_HEIGHT = canvas:attrSize() GRID = SCREEN_WIDTH/32 --review!!! tcpresult = "" MENUON = false PGMON = false ICON = {} ICON.state = 1 ICON.pos =1 DEBUG = true VERSION = "1.4.12" START = false --- tcp metrics require 'lib_tcp' --- Send Info over tcpip function countMetric(param) -- ping internet --if START == false then if not param then param = "portal" end tcp.execute( function () tcp.connect('redeminas.mg.gov.br', 80) tcp.send('get /ginga.php?aplicacao=' .. param .. VERSION .. '\n') tcpresult = tcp.receive() if tcpresult then tcpresult = tcpresult or '0' else tcpresult = 'er:' .. evt.error end canvas:flush() tcp.disconnect() START = true end ) --end end --- Send Info over tcpip function connecttcp(t) -- ping internet tcp.execute( function () tcp.connect('redeminas.mg.gov.br', 80) tcp.send('get /ginga.php?aplicacao=' .. t .. '\n') tcpresult = tcp.receive() if tcpresult then tcpresult = tcpresult or '0' else tcpresult = 'er:' .. evt.error end canvas:flush() tcp.disconnect() end ) end function shift(x,v,limit) -- not as num? if v == nil then v = 0 end if x + v < 1 then return x + v + limit elseif x + v > limit then return x + v - limit else return x+v end end ---Input a text string, get a lefty list -- @parameter text (string) -- @parameter size (integer) function textWrap(text,size) local list = {} local offset = 0 local offsetSum = 0 local lasti =0 local lines = (math.floor(string.len(text)/size)+1) for i=1,lines do if (i==1) then result=string.sub(text,((i-1)*size),(i*size)) else result=string.sub(text,(((i-1)*size-offsetSum)),(i*size+offsetSum)) end -- calculate offset offset = 0 if i ~= lines then while (string.sub(result,size-offset,size-offset) ~= " " ) do if offset < size then offset = offset +1 end end end result = string.sub(result,0,size-offset) -- if line starts with space, remove it if string.sub(result,1,1) == " " or string.sub(result,1,1) == "," then result = string.sub(result,2,size+offset) -- elseif (string.sub(result,size+1,size+1) == ",") then end offsetSum = offsetSum + offset -- canvas:drawText(GRID*6, GRID*1.7+i*GRID*0.7 , result) lasti = i list[i]=result end --resto result=string.sub(text,(((lasti)*size-offsetSum)),(lasti*size+offsetSum)) list[lasti+1]=result return(list) end --based on http://lua-users.org/wiki/DayOfWeekAndDaysInMonthExample function get_day_of_week(dd, mm, yy) dw=os.date('*t',os.time{year=yy,month=mm,day=dd})['wday'] return dw,({"Dom","Seg","Ter","Qua","Qui","Sex","Sab" })[dw] end function get_days_in_month(mnth, yr) return os.date('*t',os.time{year=yr,month=mnth+1,day=0})['day'] end
agpl-3.0
Armin041/antiflood
plugins/inrealm.lua
228
16974
-- 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 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) 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/"..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/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/"..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 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 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 group_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.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 function run(msg, matches) --vardump(msg) if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] return create_group(msg) end 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_realm(msg) then return 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] == 'setting' 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_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) end 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] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then group_list(msg) send_document("chat#id"..msg.to.id, "groups.txt", ok_cb, false) return " Group list created" --group_list(msg) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
DEVll190ll/DEV_HR
plugins/DEV_4.lua
1
8423
--[[ الملف يحتوي ع 11 ملفات مدموجة سوة وصايرة عبارة عن سوبر كروب ؟ تقريبا للمطورين الي يفتهمون !! وتم صنع الملف من قبل حسين محمد اختصرت الكم الملفات اهنا علمود ميوكف البوت بسرعة ولسهولة تغيير الحقوق ]] do -- هذا ملف المطور وتغيير حقوقة سهلة حييل شيل اسمي وخلي اسمك وشيل معرفي وخلي معرفك وقناتي اذا عندك قناة تطوير واذا معندك قناة تطوير عيف قناتي local function Ch_Dev(msg, matches) local reply_id = msg['id'] if matches[1] == "المطور" then local ii02ii = [[يہۧعہۧمہۧل بہۧوتہۧ سہۧآقہۧط ع مہۧجہۧمہۧوعآت 5K 🌞✨ ≪ تہۧم صہۧنہۧع آلہۧبہۧوتہۧ مہۧن قہۧبہۧل آلہۧمہۧطور 🙁🍷 ≫ الز؏ــــيـم❙#حسين_محمد👨🏼‍💻🥇 ≪مہۧعہۧرفہۧ آلہۧمہۧطہۧور 🐸🎈 ≫ 『 @ll190ll 』 ≪بہۧوتہۧ آلہۧتہۧوآصہۧل 😚≫ 『 @MX313_BOT 』 ≪مہۧعہۧرفہۧ آلہۧمہۧطہۧور الثاني 🌞✨ ≫ 『 @llSNll 』 ]] reply_msg(reply_id, ii02ii, ok_cb, false) end -- ملف معلومات سيرفرك ينطيك حجم الورك وكلشي if is_sudo(msg) and matches[1] == 'معلومات السيرفر' then local text = io.popen("sh ./data/cmd.sh"):read('*all') return text end -- ملف موقعي للمطور والاونر (المدير) والادمن والعضو if is_sudo(msg) and matches[1] == 'شنو اني' then local text = " آنہۧتہ بہۧآبہۧآ آلہۧمہۧطہۧور 🌞✨ ".."\n".."🆔 - آيہۧديكہۧ : "..msg.from.id.."\n".."✍🏻✨ - آسہۧمہۧكہۧ : "..msg.from.first_name.."\n".." مہۧعہۧرفہۧكہۧ ↩️👲🏻 : @"..msg.from.username.."\n".."🔝 - آسہۧم آلہۧمہجہۧمہۧوعہۧةة ✅ : "..msg.to.title.."\n"..'📱 - رقہۧمہۧكہۧ 😜🙈 : '..(msg.from.phone or "مآ مہۧحہۧتہۧرمہۧة ومہۧحہۧآفہۧظ رقہۧمہۧة ⛔️‼️") return reply_msg(msg.id, text, ok_cb, false) end if is_owner(msg) and matches[1] == 'شنو اني' then local text = " آنہۧتہ عہۧمہۧو آلہۧمہۧديہۧر 🙇🏻🍷 ".."\n".."🆔 - آيہۧديكہۧ : "..msg.from.id.."\n".."✍🏻✨ - آسہۧمہۧكہۧ : "..msg.from.first_name.."\n".." مہۧعہۧرفہۧكہۧ ↩️👲🏻 : @"..msg.from.username.."\n".."🔝 - آسہۧم آلہۧمہجہۧمہۧوعہۧةة ✅ : "..msg.to.title.."\n"..'📱 - رقہۧمہۧكہۧ 😜🙈 : '..(msg.from.phone or "مآ مہۧحہۧتہۧرمہۧة ومہۧحہۧآفہۧظ رقہۧمہۧة ⛔️‼️") return reply_msg(msg.id, text, ok_cb, false) end if is_momod(msg) and matches[1] == 'شنو اني' then local text = " آنہۧتہ بہۧن عہۧمہۧيے آلآدمہۧن 🐸🍷 ".."\n".."🆔 - آيہۧديكہۧ : "..msg.from.id.."\n".."✍🏻✨ - آسہۧمہۧكہۧ : "..msg.from.first_name.."\n".." مہۧعہۧرفہۧكہۧ ↩️👲🏻 : @"..msg.from.username.."\n".."🔝 - آسہۧم آلہۧمہجہۧمہۧوعہۧةة ✅ : "..msg.to.title.."\n"..'📱 - رقہۧمہۧكہۧ 😜🙈 : '..(msg.from.phone or "مآ مہۧحہۧتہۧرمہۧة ومہۧحہۧآفہۧظ رقہۧمہۧة ⛔️‼️") return reply_msg(msg.id, text, ok_cb, false) end if not is_momod(msg) and matches[1] == 'شنو اني' then local text = " آنہۧتہ ولہۧيہۧديے آلعہۧضہۧو 🐸🍷 ".."\n".."🆔 - آيہۧديكہۧ : "..msg.from.id.."\n".."✍🏻✨ - آسہۧمہۧكہۧ : "..msg.from.first_name.."\n".." مہۧعہۧرفہۧكہۧ ↩️👲🏻 : @"..msg.from.username.."\n".."🔝 - آسہۧم آلہۧمہجہۧمہۧوعہۧةة ✅ : "..msg.to.title.."\n"..'📱 - رقہۧمہۧكہۧ 😜🙈 : '..(msg.from.phone or "مآ مہۧحہۧتہۧرمہۧة ومہۧحہۧآفہۧظ رقہۧمہۧة ⛔️‼️") return reply_msg(msg.id, text, ok_cb, false) end -- للفوك انتهينا من ملف شنو اني -- ملف المطور ينادي المطور خلي ايديك ومعرفك if matches[1] == "@llSNll" then -- خلي معرفك مكان معرفي local sudo = 295669242 -- خلي الايدي مالتك مكان ايديي local r = get_receiver(msg) send_large_msg(r, "آنہٰتہٰظہٰر حہٰبہٰيہٰبہٰيے 🙂⁉️هہٰسہٰه آروح آصہٰيہٰحہٰلہٰكہٰ مہٰطہٰوريے 🙊🤖") send_large_msg("user#id"..sudo, "📝 لہٰك آسہٰتہٰآذيے 🕵 يہٰردوكہٰ ضہٰروريے 🤖🍷\n\n ".." 👲🏻 مہٰعہٰرفہٰ آلہٰمہٰحہٰتآجہٰك : @"..msg.from.username.."\n 🆔 آلآيہٰديے : "..msg.from.id.."\n 📝 آسہٰم آلہٰمہٰجہٰمہٰوعہٰة : "..msg.to.title.."\n 🆔 آيہٰديے آلہٰمہٰجہٰمہٰوعہٰة : "..msg.from.id..'\n 🕑 آلہٰوقہٰت : '..os.date(' %T*', os.time())..'\n 📅 آلہٰتہٰآريہٰخ : '..os.date('!%A, %B %d, %Y*\n', timestamp)) end if matches[1] == "كرر" then -- هذا ملف تكرار بامر كرر + الكلام = البوت يكتبة local Memo = matches[2] return Memo end if matches[1] == "جلب ملف" then -- هذا الملف هو يجيبلك ملف من السيرفر بدون متدخل عليه local file = matches[2] if is_sudo(msg) then --sudo only ! local receiver = get_receiver(msg) send_document(receiver, "./plugins/"..file..".lua", ok_cb, false) else return nil end end if matches[1] == "send" then local file = matches[2] if is_sudo(msg) then local receiver = get_receiver(msg) send_document(receiver, "./plugins/"..file..".lua", ok_cb, false) end end local reply_id = msg ['id'] -- ملف الي يحجي ويه البوت خاص انسخ السطر وخلي معرفك وبوت تواصل والقناة اذا عندك if ( msg.text ) then if ( msg.to.type == "user" ) then local text = "آهہۧلآ وسہۧهہۧلآ بہۧكہ/ي 🌞✨ @"..msg.from.username..'\n\n آنہۧتہ آلآن🏃🏻تہۧتہۧحہۧدثہ مہۧع بہۧوتہ SAQT 🤖✅ \n\n لہۧلتہۧحہۧدث مہۧع آلہۧمہۧطہۧور 🕵️ \n\n 🌞☄️ Dev @llSNll \n\n لہۧسہۧتہ آنہۧآ آلہۧمہۧطہۧور آلہۧوحہۧيہكہۧننہۧيے آفہۧضہلہۧهم 🐸🍷 \n\nآلہۧقہۧناة الہۧيے تہۧسہۧآهہۧم بہۧمہۧسہۧآعہۧدتہۧكہ🤖🔝\n\n📡 # @DEV_HR وخہۧآصہۧة لہۧلہۧشہٰروحہٰآتہٰ 💋😻\n' reply_msg(reply_id, text, ok_cb, false) end if matches[1] == "شغل" and is_sudo(msg) then -- ملف رست وحدث وريديس اذا كان البوت شغال استخدمها تفيدك يعني اذا ساعتين وبوتك يوكف return os.execute("./launch.sh"):read('*all') -- اكتب رست قبل متصيرين ساعتين حيزيد ساعتين elseif matches[1] == "حدث" and is_sudo(msg) then return io.popen("git pull"):read('*all') elseif matches[1] == "تحديث" and is_sudo(msg) then return io.popen("redis-server"):read('*all') end end end return { patterns = { "^(المطور)$", "^(معلومات السيرفر)$", "^(شنو اني)$", "^(@llSNll)$", "^(الاصدار)$", "^(معلوماتي)$", "^(كرر)(.+)", "^(جلب ملف) (.*)$", "^(send) (.*)$", "^(تحديث)$", "^(حدث)$", "^(شغل)$", "(.*)$", }, run = Ch_Dev } end --[[ الى كل مطور ؟ سوي هيج ملفات بس لا تنكر ! اذكر الي سواه بالاول حسين محمد @LL190LL ]]--
gpl-2.0
Ninjistix/darkstar
scripts/zones/Lower_Jeuno/npcs/Aldo.lua
5
1622
----------------------------------- -- Area: Lower Jeuno -- NPC: Aldo -- Involved in Mission: Magicite, Return to Delkfutt's Tower (Zilart) -- !pos 20 3 -58 245 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local ZilartMission = player:getCurrentMission(ZILART); local ZilartStatus = player:getVar("ZilartStatus"); if (player:hasKeyItem(LETTERS_TO_ALDO)) then player:startEvent(152); elseif (player:getCurrentMission(player:getNation()) == 13 and player:getVar("MissionStatus") == 3) then player:startEvent(183); elseif (ZilartMission == RETURN_TO_DELKFUTTS_TOWER and ZilartStatus == 0) then player:startEvent(104); elseif (ZilartMission == THE_SEALED_SHRINE and ZilartStatus == 1) then player:startEvent(111); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 152) then player:delKeyItem(LETTERS_TO_ALDO); player:addKeyItem(SILVER_BELL); player:messageSpecial(KEYITEM_OBTAINED,SILVER_BELL); player:setVar("MissionStatus",3); elseif (csid == 104) then player:setVar("ZilartStatus",1); end end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/spells/absorb-int.lua
4
1565
-------------------------------------- -- Spell: Absorb-INT -- Steals an enemy's intelligence. -------------------------------------- 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:hasStatusEffect(EFFECT_INT_DOWN) or caster:hasStatusEffect(EFFECT_INT_BOOST)) 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 = 37; params.bonus = 0; params.effect = nil; local resist = applyResistance(caster, target, spell, params); if (resist <= 0.125) then spell:setMsg(msgBasic.MAGIC_RESIST); else spell:setMsg(msgBasic.MAGIC_ABSORB_INT); caster:addStatusEffect(EFFECT_INT_BOOST,ABSORB_SPELL_AMOUNT*resist*((100+(caster:getMod(MOD_AUGMENTS_ABSORB)))/100), ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK,FLAG_DISPELABLE); -- caster gains INT target:addStatusEffect(EFFECT_INT_DOWN,ABSORB_SPELL_AMOUNT*resist*((100+(caster:getMod(MOD_AUGMENTS_ABSORB)))/100), ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK,FLAG_ERASABLE); -- target loses INT end end return EFFECT_INT_DOWN; end;
gpl-3.0
premake/premake-4.x
src/actions/xcode/_xcode.lua
15
2759
-- -- _xcode.lua -- Define the Apple XCode action and support functions. -- Copyright (c) 2009 Jason Perkins and the Premake project -- premake.xcode = { } newaction { trigger = "xcode3", shortname = "Xcode 3", description = "Generate Apple Xcode 3 project files (experimental)", os = "macosx", valid_kinds = { "ConsoleApp", "WindowedApp", "SharedLib", "StaticLib" }, valid_languages = { "C", "C++" }, valid_tools = { cc = { "gcc" }, }, valid_platforms = { Native = "Native", x32 = "Native 32-bit", x64 = "Native 64-bit", Universal32 = "32-bit Universal", Universal64 = "64-bit Universal", Universal = "Universal", }, default_platform = "Universal", onsolution = function(sln) -- Assign IDs needed for inter-project dependencies premake.xcode.preparesolution(sln) end, onproject = function(prj) premake.generate(prj, "%%.xcodeproj/project.pbxproj", premake.xcode.project) end, oncleanproject = function(prj) premake.clean.directory(prj, "%%.xcodeproj") end, oncheckproject = function(prj) -- Xcode can't mix target kinds within a project local last for cfg in premake.eachconfig(prj) do if last and last ~= cfg.kind then error("Project '" .. prj.name .. "' uses more than one target kind; not supported by Xcode", 0) end last = cfg.kind end end, } newaction { trigger = "xcode4", shortname = "Xcode 4", description = "Generate Apple Xcode 4 project files (experimental)", os = "macosx", valid_kinds = { "ConsoleApp", "WindowedApp", "SharedLib", "StaticLib" }, valid_languages = { "C", "C++" }, valid_tools = { cc = { "gcc" }, }, valid_platforms = { Native = "Native", x32 = "Native 32-bit", x64 = "Native 64-bit", Universal32 = "32-bit Universal", Universal64 = "64-bit Universal", Universal = "Universal", }, default_platform = "Universal", onsolution = function(sln) premake.generate(sln, "%%.xcworkspace/contents.xcworkspacedata", premake.xcode4.workspace_generate) end, onproject = function(prj) premake.generate(prj, "%%.xcodeproj/project.pbxproj", premake.xcode.project) end, oncleanproject = function(prj) premake.clean.directory(prj, "%%.xcodeproj") premake.clean.directory(prj, "%%.xcworkspace") end, oncheckproject = function(prj) -- Xcode can't mix target kinds within a project local last for cfg in premake.eachconfig(prj) do if last and last ~= cfg.kind then error("Project '" .. prj.name .. "' uses more than one target kind; not supported by Xcode", 0) end last = cfg.kind end end, }
bsd-3-clause
Ninjistix/darkstar
scripts/zones/Bastok_Markets/npcs/Wulfnoth.lua
3
1477
----------------------------------- -- Area: Bastok Markets -- NPC: Wulfnoth -- Type: Goldsmithing Synthesis Image Support -- !pos -211.937 -7.814 -56.292 235 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local guildMember = isGuildMember(player,6); local SkillCap = getCraftSkillCap(player, SKILL_GOLDSMITHING); local SkillLevel = player:getSkillLevel(SKILL_GOLDSMITHING); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_GOLDSMITHING_IMAGERY) == false) then player:startEvent(303,SkillCap,SkillLevel,1,201,player:getGil(),0,3,0); else player:startEvent(303,SkillCap,SkillLevel,1,201,player:getGil(),7054,3,0); end else player:startEvent(303); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 303 and option == 1) then player:messageSpecial(GOLDSMITHING_SUPPORT,0,3,1); player:addStatusEffect(EFFECT_GOLDSMITHING_IMAGERY,1,0,120); end end;
gpl-3.0
jokersso3/joker
plugins/supergroup.lua
3
124287
local function check_member_super(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg if success == 0 then send_large_msg(receiver, "Promote me to admin first!") end for k,v in pairs(result) do local member_id = v.peer_id if member_id ~= our_id then -- SuperGroup configuration data[tostring(msg.to.id)] = { group_type = 'SuperGroup', long_id = msg.to.peer_id, moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.title, '_', ' '), lock_arabic = 'no', lock_link = "no", flood = 'yes', lock_spam = 'yes', lock_sticker = 'no', member = 'no', public = 'no', lock_rtl = 'no', lock_tgservice = 'yes', lock_contacts = 'no', strict = 'no' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) local text = 'bot has been added ✅ in Group'..msg.to.title return reply_msg(msg.id, text, ok_cb, false) end end end --Check Members #rem supergroup local function check_member_superrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = 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(msg.to.id)] = nil save_data(_config.moderation.data, data) local text = 'bot has been removed ❎ in Group'..msg.to.title return reply_msg(msg.id, text, ok_cb, false) end end end --Function to Add supergroup local function superadd(msg) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) channel_get_users(receiver, check_member_super,{receiver = receiver, data = data, msg = msg}) end --Function to remove supergroup local function superrem(msg) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) channel_get_users(receiver, check_member_superrem,{receiver = receiver, data = data, msg = msg}) end --Get and output admins and bots in supergroup local function callback(cb_extra, success, result) local i = 1 local chat_name = string.gsub(cb_extra.msg.to.print_name, "_", " ") local member_type = cb_extra.member_type local text = member_type.." for "..chat_name..":\n" for k,v in pairsByKeys(result) do if not v.first_name then name = " " else vname = v.first_name:gsub("‮", "") name = vname:gsub("_", " ") end text = text.."\n"..i.." - "..name.."["..v.peer_id.."]" i = i + 1 end send_large_msg(cb_extra.receiver, text) end --Get and output info about supergroup local function callback_info(cb_extra, success, result) local title ="Info for SuperGroup: ["..result.title.."]\n\n" local admin_num = "Admin count: "..result.admins_count.."\n" local user_num = "User count: "..result.participants_count.."\n" local kicked_num = "Kicked user count: "..result.kicked_count.."\n" local channel_id = "ID: "..result.peer_id.."\n" if result.username then channel_username = "Username: @"..result.username else channel_username = "" end local text = title..admin_num..user_num..kicked_num..channel_id..channel_username send_large_msg(cb_extra.receiver, text) end --Get and output members of supergroup local function callback_who(cb_extra, success, result) local text = "Members for "..cb_extra.receiver local i = 1 for k,v in pairsByKeys(result) do if not v.print_name then name = " " else vname = v.print_name:gsub("‮", "") name = vname:gsub("_", " ") end if v.username then username = " @"..v.username else username = "" end text = text.."\n"..i.." - "..name.." "..username.." [ "..v.peer_id.." ]\n" --text = text.."\n"..username Channel : - - i = i + 1 end local file = io.open("./groups/lists/supergroups/"..cb_extra.receiver..".txt", "w") file:write(text) file:flush() file:close() send_document(cb_extra.receiver,"./groups/lists/supergroups/"..cb_extra.receiver..".txt", ok_cb, false) post_msg(cb_extra.receiver, text, ok_cb, false) end --Get and output list of kicked users for supergroup local function callback_kicked(cb_extra, success, result) --vardump(result) local text = "Kicked Members for SuperGroup "..cb_extra.receiver.."\n\n" local i = 1 for k,v in pairsByKeys(result) do if not v.print_name then name = " " else vname = v.print_name:gsub("‮", "") name = vname:gsub("_", " ") end if v.username then name = name.." @"..v.username end text = text.."\n"..i.." - "..name.." [ "..v.peer_id.." ]\n" i = i + 1 end local file = io.open("./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", "w") file:write(text) file:flush() file:close() send_document(cb_extra.receiver,"./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", ok_cb, false) --send_large_msg(cb_extra.receiver, text) end --Begin supergroup locks local function lock_group_links(msg, data, target) if not is_momod(msg) then return end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'yes' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return reply_msg(msg.id,'🔒قفل لینڪ دَږ سۅپږگږۊه ازقبل فَعال بود🔒', ok_cb, false) else return reply_msg(msg.id,'🔐Link Posting is already locked🔒', ok_cb, false) end end data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return reply_msg(msg.id,'🔒قفل لینڪ دَږ سۅپږگږۊه فعال شُد🔒', ok_cb, false) else return reply_msg(msg.id,'🔐Link Posting Has Been Locked🔒', ok_cb, false) end end local function unlock_group_links(msg, data, target) if not is_momod(msg) then return end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'no' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return reply_msg(msg.id,'🔒قفل لینڪ دَږ سۅپږگږۊه غیږفعال شُده بود🔓', ok_cb, false) else return reply_msg(msg.id,'🔐Link Posting is already Unlocked🔓', ok_cb, false) end end data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return reply_msg(msg.id,'🔒قفل لینڪ دَږ سۅپږگږۊه غیږفعال شُد🔓', ok_cb, false) else return reply_msg(msg.id,'🔐Link Posting Hasbeen unLocked🔓', ok_cb, false) end end local function lock_group_cmds(msg, data, target) if not is_momod(msg) then return end local group_cmds_lock = data[tostring(target)]['settings']['cmds'] if group_cmds_lock == 'yes' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قفل دستورات بسته بود🔒' else return '🔐cmds Posting is already locked🔒' end end data[tostring(target)]['settings']['cmds'] = 'yes' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قفل دستورات بسته شد🔒' else return '🔐cmds Posting Has Been Locked🔒' end end local function unlock_group_cmds(msg, data, target) if not is_momod(msg) then return end local group_cmds_lock = data[tostring(target)]['settings']['cmds'] if group_cmds_lock == 'no' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قفل دستورات غیرفعال بود🔓' else return '🔐cmds Posting is already Unlocked🔓' end end data[tostring(target)]['settings']['cmds'] = 'no' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قفل دستورات فعال شد🔓' else return '🔐cmds Posting Hasbeen unLocked🔓' end end local function lock_group_leave(msg, data, target) if not is_momod(msg) then return end local group_leave_lock = data[tostring(target)]['settings']['leave'] if group_leave_lock == 'yes' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return ' 🔐قُفل ترک گروه=ban فعال بۅڍ🔒' else return '🔐leave is already locked🔐' end end data[tostring(target)]['settings']['leave'] = 'yes' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return ' 🔐قُفل ترک گروه=ban فعال شد🔒' else return '🔐leave has been locked🔐' end end local function unlock_group_leave(msg, data, target) if not is_momod(msg) then return end local group_leave_lock = data[tostring(target)]['settings']['leave'] if group_leave_lock == 'no' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return ' 🔐قُفل تږک گږوه=ban غیږ فعال بۅد🔒' else return '🔓leave is not locked🔓' end end data[tostring(target)]['settings']['leave'] = 'no' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return ' 🔐قُفل تږک گږوه=ban غیږ فعال شُد🔒' else return '🔓leave has been unlocked🔓' end end local function lock_group_operator(msg, data, target) if not is_momod(msg) then return end local group_operator_lock = data[tostring(target)]['settings']['operator'] if group_operator_lock == 'yes' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return ' 🔐قُفل تبلیغات شارژ(ایرانسل،همراه،رایتل)فعال بود🔒' else return '🔐Operator is already locked🔐' end end data[tostring(target)]['settings']['operator'] = 'yes' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return ' 🔐قُفل تبلیغات شارژ(ایرانسل،همراه،رایتل)فعال شد🔒' else return '🔐Operator has been locked🔐' end end local function unlock_group_operator(msg, data, target) if not is_momod(msg) then return end local group_operator_lock = data[tostring(target)]['settings']['operator'] if group_operator_lock == 'no' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return ' 🔐قُفل تبلیغات شارژ(ایرانسل،همراه،رایتل)غیرفعال بود🔒' else return '🔓Operator is not locked🔓' end end data[tostring(target)]['settings']['operator'] = 'no' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return ' 🔐قُفل تبلیغات شارژ(ایرانسل،همراه،رایتل)غیرفعال شد🔒' else return '🔓Operator has been unlocked🔓' end end local function lock_group_username(msg, data, target) if not is_momod(msg) then return end local group_username_lock = data[tostring(target)]['settings']['username'] if group_username_lock == 'yes' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل یوزرنیم(@) دږ سوپرگږوه فعال بود🔒' else return '🔒Username is already locked🔒' end end data[tostring(target)]['settings']['username'] = 'yes' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل یوزرنیم(@) دږ سوپرگږوه فعال شد🔒' else return '🔒Username has been locked🔒' end end local function unlock_group_username(msg, data, target) if not is_momod(msg) then return end local group_username_lock = data[tostring(target)]['settings']['username'] if group_username_lock == 'no' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل یوزرنیم(@) دږ سوپرگږوه غیږفعال بود🔒' else return '🔓Username is not locked🔓' end end data[tostring(target)]['settings']['username'] = 'no' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل یوزرنیم(@) دږ سوپرگږوه غیږفعال شد🔒' else return '🔓Username has been unlocked🔓' end end local function lock_group_media(msg, data, target) if not is_momod(msg) then return end local group_media_lock = data[tostring(target)]['settings']['media'] if group_media_lock == 'yes' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل فیلم،عکس،آهنگ دږ سۅپږگږوه فعال بود🔒' else return '🔒Media is already locked🔒' end end data[tostring(target)]['settings']['media'] = 'yes' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل فیلم،عکس،آهنگ دږ سۅپږگږوه فعال شُڍ🔒' else return '🔒Media has been locked🔒' end end local function unlock_group_media(msg, data, target) if not is_momod(msg) then return end local group_media_lock = data[tostring(target)]['settings']['media'] if group_media_lock == 'no' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل فیلم،عکس،آهنگ دږ سۅپږگږوه غیر فعال بود🔓' else return '🔓Media is not locked🔓' end end data[tostring(target)]['settings']['media'] = 'no' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل فیلم،عکس،آهنگ دږ سۅپږگږوه غیر فعال شُڍ🔓' else return '🔓Media has been unlocked🔓' end end local function lock_group_fosh(msg, data, target) if not is_momod(msg) then return end local group_fosh_lock = data[tostring(target)]['settings']['fosh'] if group_fosh_lock == 'yes' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐فیلتږینگ کلماټ +18 دږ سوپږ گږۅه فعاڶ شُده بۅد🔒' else return '🔒Fosh is already locked🔒' end end data[tostring(target)]['settings']['fosh'] = 'yes' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐فیلتږینگ کلماټ +18 دږ سوپږ گږۅه فعاڶ شُد🔒' else return '🔒Fosh has been locked🔒' end end local function unlock_group_fosh(msg, data, target) if not is_momod(msg) then return end local group_fosh_lock = data[tostring(target)]['settings']['fosh'] if group_fosh_lock == 'no' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐فیلتږینگ کلماټ +18 دږ سوپږ گږۅه غیږ فعاڶ شُدة بۅڊ🔓' else return '🔓Fosh is not locked🔓' end end data[tostring(target)]['settings']['fosh'] = 'no' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐فیلتږینگ کلماټ +18 دږ سوپږ گږۅه غیږ فعاڶ شُد🔓' else return '🔓Fosh has been unlocked🔓' end end local function lock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'yes' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل Rtl دږ سوپږ گروه فعال بود🔒' else return '*RTL is already locked' end end data[tostring(target)]['settings']['lock_rtl'] = 'yes' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل Rtl دږ سوپږ گروه فعال شد🔒' else return '*RTL has been locked' end end local function unlock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'no' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return ' 🔐قُفل Rtl دږ سوپږ گروه غیر فعال بود🔒' else return '*RTL is already unlocked' end end data[tostring(target)]['settings']['lock_rtl'] = 'no' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return ' 🔐قُفل Rtl دږ سوپږ گروه غیر فعال شد🔒' else return '*RTL has been unlocked' end end local function lock_group_join(msg, data, target) if not is_momod(msg) then return end local group_join_lock = data[tostring(target)]['settings']['join'] if group_join_lock == 'yes' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل وږۅڍ افږاڍ از طریق لینک فعال بود🔒' else return '🔒Join is already locked🔒' end end data[tostring(target)]['settings']['join'] = 'yes' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل وږۅڍ افږاڍ از طریق لینک فعال شُد🔒' else return '🔒Join has been locked🔒' end end local function unlock_group_join(msg, data, target) if not is_momod(msg) then return end local group_join_lock = data[tostring(target)]['settings']['join'] if group_join_lock == 'no' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل وږۅڍ افږاڍ از طریق لینک غیر فعال بود🔒' else return '🔓Join is not locked🔓' end end data[tostring(target)]['settings']['join'] = 'no' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل وږۅڍ افږاڍ از طریق لینک غیر فعال شُد🔒' else return '🔓Join has been unlocked🔓' end end local function lock_group_welcome(msg, data, target) if not is_momod(msg) then return "شما مدیر گروه نیستید" end local welcoms = data[tostring(target)]['settings']['welcome'] if welcoms == 'yes' then return 'پیام خوش امد گویی فعال است' else data[tostring(target)]['settings']['welcome'] = 'yes' save_data(_config.moderation.data, data) return 'پیام خوش امد گویی فعال شد\nبرای تغییر این پیام از دستور زیر استفاده کنید\n/set welcome <welcomemsg>' end end local function unlock_group_welcome(msg, data, target) if not is_momod(msg) then return "شما مدیر گروه نیستید" end local welcoms = data[tostring(target)]['settings']['welcome'] if welcoms == 'no' then return 'پیام خوش امد گویی غیر فعال است' else data[tostring(target)]['settings']['welcome'] = 'no' save_data(_config.moderation.data, data) return 'پیام خوش امد گویی غیر فعال شد' end end local function lock_group_fwd(msg, data, target) if not is_momod(msg) then return end local group_fwd_lock = data[tostring(target)]['settings']['lock_fwd'] if group_fosh_lock == 'yes' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return ' 🔐قُفل فۅږواږد دږ سوپږ گرۅه فعال بود🔒' else return 'fwd posting is already locked' end end data[tostring(target)]['settings']['lock_fwd'] = 'yes' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قفل فۅږۅاږد دږ سۅپږ گږۅة فعاڶ شُد🔒' else return ' 🔐Fwd has been locked🔐' end end local function unlock_group_fwd(msg, data, target) if not is_momod(msg) then return end local group_fwd_lock = data[tostring(target)]['settings']['lock_fwd'] if group_fwd_lock == 'no' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قفل فۅږۅاږد دږ سۅپږگږۅة از قبل غیږ فعاڶ شُدہ بۅڍ🔒' else return ' 🔓Fwd is not locked🔓' end end data[tostring(target)]['settings']['lock_fwd'] = 'no' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قفل فۅږۅاږد دږ سۅپږ گږۅة غیرفعاڶ شُد🔒' else return ' 🔓Fwd has been unlocked🔓' end end local function lock_group_english(msg, data, target) if not is_momod(msg) then return end local group_english_lock = data[tostring(target)]['settings']['english'] if group_english_lock == 'yes' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل چَت ڪږدڹ بہ زبان انگلیسے فعال بود🔒' else return '🔒English is already locked🔒' end end data[tostring(target)]['settings']['english'] = 'yes' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل چَت ڪږدڹ بہ زبان انگلیسے فعال شُد🔒' else return '🔒English has been locked🔒' end end local function unlock_group_english(msg, data, target) if not is_momod(msg) then return end local group_english_lock = data[tostring(target)]['settings']['english'] if group_english_lock == 'no' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل چَت ڪږدڹ بہ زبان انگلیسے غیږ فعال بود🔒' else return '🔓English is not locked🔓' end end data[tostring(target)]['settings']['english'] = 'no' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل چَت ڪږدڹ بہ زبان انگلیسے غیږ فعال شُد🔒' else return '🔓English has been unlocked🔓' end end local function lock_group_emoji(msg, data, target) if not is_momod(msg) then return end local group_emoji_lock = data[tostring(target)]['settings']['lock_emoji'] if group_emoji_lock == 'yes' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قـفـل اموجی در سـوپـرگـروه از قـبـل فـعـال بـود🔒' else return '🔒emoji is already locked🔒' end end data[tostring(target)]['settings']['lock_emoji'] = 'yes' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قـفـل اموجی در سـوپـرگـروه فـعـال شـد🔒' else return '🔒emoji has been locked🔒' end end local function unlock_group_emoji(msg, data, target) if not is_momod(msg) then return end local group_emoji_lock = data[tostring(target)]['settings']['lock_emoji'] if group_emoji_lock == 'no' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔓قـفـل اموجی در سـوپـرگـروه از قـبـل غـیـرفـعـال بـوده🔓' else return '🔓emoji is not locked🔓' end end data[tostring(target)]['settings']['lock_emoji'] = 'no' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔓قـفـل اموجی در سـوپـرگـروه غـیـرفـعـال شـد🔓' else return '🔓emoji has been unlocked🔓' end end local function lock_group_tag(msg, data, target) if not is_momod(msg) then return end local group_tag_lock = data[tostring(target)]['settings']['tag'] if group_tag_lock == 'yes' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل هشتگ(#) دږ سوپږگږوه فعال بود🔒' else return '🔒Tag is already locked🔒' end end data[tostring(target)]['settings']['tag'] = 'yes' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل هشتگ(#) دږ سوپږگږوه فعال شُد🔒' else return '🔒Tag has been locked🔒' end end local function unlock_group_tag(msg, data, target) if not is_momod(msg) then return end local group_tag_lock = data[tostring(target)]['settings']['tag'] if group_tag_lock == 'no' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل هشتگ(#) دږ سوپږگږوه غیر فعال بود🔓' else return 'Tag is not locked' end end data[tostring(target)]['settings']['tag'] = 'no' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل هشتگ(#) دږ سوپږگږوه غیر فعال شُد🔓' else return '🔓Tag has been unlocked🔓' end end local function lock_group_spam(msg, data, target) if not is_momod(msg) then return end if not is_owner(msg) then return " 🔒قُفل اِسپَم دَږ سۅپږگږۅہ فعاڶ شد🔐 " end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'yes' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قُفل اِسپَم دَږ سۅپږگږۅہ از قَبڶ فعاڶ بۅد🔐' else return '🔒spam posting is already locked🔒' end end data[tostring(target)]['settings']['lock_spam'] = 'yes' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قُفل اِسپَم دَږ سۅپږ گږۅہ فعاڶ شُڍ🔐' else return '🔒spam posting hasBeen locked🔒' end end local function unlock_group_spam(msg, data, target) if not is_momod(msg) then return end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'no' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قُفل اِسپَم دَږ سۅپږگږۅہ از قَبڶ غیږ فعاڶ بۅد🔓' else return '🔒spam posting is already Unlocked🔓' end end data[tostring(target)]['settings']['lock_spam'] = 'no' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قُفل اِسپَم دَږ سۅپږگږۅہ غیږ فعاڶ شُد🔓' else return '🔒spam posting HasBeen Unlocked🔓' end end local function lock_group_flood(msg, data, target) if not is_momod(msg) then return end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return ' 🔒قُفل فِلۅڍ دَږ سۅپږ گږۅہ از قبل فعاڶ شُڍه بود🔐 ' else return '🔒flood is already locked🔒' end end data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قُفل فِلۅڍ دَږ سۅپږ گږۅہ فعاڶ شُڍ🔐' else return '🔒flood has been locked🔒' end end local function unlock_group_flood(msg, data, target) if not is_momod(msg) then return end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قُفل فِلۅڍ دَږ سۅپږ گږۅہ ازقبڶ غیږفعاڶ شُڍه بۏد🔓 ' else return '🔓flood is not locked🔓' end end data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قُفل فِلۅڍ دَږ سۅپږ گږۅہ غیږفعاڶ شُڍ🔓' else return '🔓flood has been unlocked🔓' end end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قُفل چت ڪردن به زبان فارسے از قبڶ دږ سوپږگږۅه فعاڶ شده بۅڍ🔐' else return '🔒arabic posting is already locked🔒' end end data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قُفل چت ڪردن به زبان فارسے دږ سوپږگږۅه فعاڶ🔐شد ' else return '🔒arabic posting hasBeen locked🔒' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قُفل چت ڪردن بہ زبان فارسے از قبڶ دږ سوپږگږۅه غیږفعاڶ شده بۅد🔓' else return '🔒arabic posting is already Unlocked🔓' end end data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قُفل چت ڪردن بہ زبان فارسے دږ سوپږگږۅه غیږفعاڶ شد🔓' else return '🔒arabic posting HasBeen Unlocked🔓' end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قفل اضافہ ڪردن اعضٵ بہ سۅپږ گږۅه از قبڶ فعاڶ شُده بۅڍ🔒' else return ' 🔒addMember is already locked🔒' end end data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قفل اضافہ ڪردن اعضٵ بہ سۅپږ گږۅه فعاڶ شُد🔒' else return '🔒addMember HasBeen locked🔒' end end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قفل اضافہ ڪردن اعضٵ بہ سۅپږ گږۅه از قَبڶ غیږفعاڶ شُده بۅد🔓' else return '🔓AddMember is not locked🔓' end end data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قفل اضافہ ڪردن اعضٵ بہ سۅپږ گږۅه غیرفعاڶ شُد🔓' else return ' 🔓AddMember hasBeen UNlocked🔓' end end local function lock_group_tgservice(msg, data, target) if not is_momod(msg) then return end local group_tgservice_lock = data[tostring(target)]['settings']['lock_tgservice'] if group_tgservice_lock == 'yes' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return ' 🔐قُفل Tgservice در سوپږ گږوه فعال بود🔒' else return '*TGservice is already locked' end end data[tostring(target)]['settings']['lock_tgservice'] = 'yes' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return ' 🔐قُفل Tgservice در سوپږ گږوه فعال شد🔒' else return '*TGservice has been locked' end end local function unlock_group_tgservice(msg, data, target) if not is_momod(msg) then return end local group_tgservice_lock = data[tostring(target)]['settings']['lock_tgservice'] if group_tgservice_lock == 'no' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل Tgservice در سوپږ گږوه غیر فعال بود🔓' else return '*TGService Is Not Locked!' end end data[tostring(target)]['settings']['lock_tgservice'] = 'no' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return ' 🔐قُفل Tgservice در سوپږ گږوه غیر فعال شد🔓' else return '*TGservice has been unlocked' end end local function lock_group_sticker(msg, data, target) if not is_momod(msg) then return end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'yes' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قفل استیڪږ دږ سۅپږ گږۅه از قبڶ فعاڶ شُڍه بۅڍ🔐' else return '🔒sticker posting is already locked🔒' end end data[tostring(target)]['settings']['lock_sticker'] = 'yes' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قفل استیڪږ دږ سۅپږ گږۅه فعاڶ شُڍ🔐' else return '🔒sticker posting HasBeen locked🔒' end end local function unlock_group_sticker(msg, data, target) if not is_momod(msg) then return end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'no' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قفل استیڪږ دږ سۅپږ گږۅه از قبڶ غیږ فعاڶ شُڍه بۅڍ🔓' else return '🔒sticker posting is already Unlocked🔓' end end data[tostring(target)]['settings']['lock_sticker'] = 'no' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قفل استیڪږ دږ سۅپږ گږۅه غیږ فعاڶ شُڍ🔓' else return '🔒sticker posting HasBeen Unlocked🔓' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قفل وږوڍ رباټ هاے مُخَرِب بہ سوپږگږۅه فعال شُده بوڍ🔒' else return ' 🔐Bots protection is already enabled🔐' end end data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قفل وږوڍ رباټ هاے مُخَرِب بہ سوپږگږۅه فعال شُد🔒' else return ' 🔐Bots protection has been enabled🔐' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قفل وږوڍ رباټ هاے مُخَرِب بہ سوپږگږۅه غیر فعال شُده بود🔓' else return ' 🔓Bots protection is already disabled🔓' end end data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قفل وږوڍ رباټ هاے مُخَرِب بہ سوپږگږۅه غیر فعال شُد🔓' else return ' 🔓Bots protection has been disabled🔓' end end local function lock_group_contacts(msg, data, target) if not is_momod(msg) then return end local group_contacts_lock = data[tostring(target)]['settings']['lock_contacts'] if group_contacts_lock == 'yes' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قفل اږسالہ کانتڪت دږ سۅپږگږۅه ازقبڶ فعاڶ شڍه بۅڍ🔒' else return ' 🔒Contact posting is already locked🔒' end end data[tostring(target)]['settings']['lock_contacts'] = 'yes' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قفل اږسالہ کانتڪت دږ سۅپږگږۅه فعاڶ شڍ🔒' else return ' 🔒Contact posting HasBeen locked🔒' end end local function unlock_group_contacts(msg, data, target) if not is_momod(msg) then return end local group_contacts_lock = data[tostring(target)]['settings']['lock_contacts'] if group_contacts_lock == 'no' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قفل اږسالہ کانتڪت دږ سۅپږگږۅه از قبڶ غیږ فعاڶ شڍه بۅڍ🔓' else return ' 🔒contact posting is already Unlocked🔓' end end data[tostring(target)]['settings']['lock_contacts'] = 'no' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔒قفل اږسالہ کانتڪت دږ سۅپږگږۅه غیږ فعاڶ شڍ🔓 ' else return ' 🔒contact posting HasBeen Unlocked🔓' end end local function enable_strict_rules(msg, data, target) if not is_momod(msg) then return end local group_strict_lock = data[tostring(target)]['settings']['strict'] if group_strict_lock == 'yes' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return ' 🔐قُفل تنظیماټ سختگیږانہ فعال بود🔒' else return '*Settings are already strictly enforced' end end data[tostring(target)]['settings']['strict'] = 'yes' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return ' 🔐قُفل تنظیماټ سختگیږانہ فعال شد🔒' else return '*Settings will be strictly enforced' end end local function disable_strict_rules(msg, data, target) if not is_momod(msg) then return end local group_strict_lock = data[tostring(target)]['settings']['strict'] if group_strict_lock == 'no' then local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return '🔐قُفل تنظیماټ سختگیږانہ غیر فعال بود🔓' else return '*Settings are not strictly enforced' end end data[tostring(target)]['settings']['strict'] = 'no' save_data(_config.moderation.data, data) local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return ' 🔐قُفل تنظیماټ سختگیږانہ غیر فعال شُد🔓' else return '*Settings will not be strictly enforced' end end --End supergroup locks local function callback_clean_bots (extra, success, result) local msg = extra.msg local receiver = 'channel#id'..msg.to.id local channel_id = msg.to.id for k,v in pairs(result) do local bot_id = v.peer_id kick_user(bot_id,channel_id) end end --'Set supergroup rules' function local function set_rulesmod(msg, data, target) if not is_momod(msg) then return end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'SuperGroup rules set' end --'Get supergroup rules' function local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local group_name = data[tostring(msg.to.id)]['settings']['set_name'] local rules = group_name..' rules:\n\n'..rules:gsub("/n", " ") return rules end --Set supergroup to public or not public function local function set_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_public_lock = data[tostring(target)]['settings']['public'] local long_id = data[tostring(target)]['long_id'] if not long_id then data[tostring(target)]['long_id'] = msg.to.peer_id save_data(_config.moderation.data, data) end if group_public_lock == 'yes' then return 'Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'SuperGroup is now: public' end local function unset_public_membermod(msg, data, target) if not is_momod(msg) then return end local group_public_lock = data[tostring(target)]['settings']['public'] local long_id = data[tostring(target)]['long_id'] if not long_id then data[tostring(target)]['long_id'] = msg.to.peer_id save_data(_config.moderation.data, data) end if group_public_lock == 'no' then return 'Group is not public' else data[tostring(target)]['settings']['public'] = 'no' data[tostring(target)]['long_id'] = msg.to.long_id save_data(_config.moderation.data, data) return 'SuperGroup is now: not public' end end --Show supergroup settings; function function show_supergroup_settingsmod(msg, target) if not is_momod(msg) then return end local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(target)]['settings']['lock_bots'] then bots_protection = data[tostring(target)]['settings']['lock_bots'] end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_bots'] then data[tostring(target)]['settings']['lock_bots'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['public'] then data[tostring(target)]['settings']['public'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_rtl'] then data[tostring(target)]['settings']['lock_rtl'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_tgservice'] then data[tostring(target)]['settings']['lock_tgservice'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['tag'] then data[tostring(target)]['settings']['tag'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_emoji'] then data[tostring(target)]['settings']['lock_emoji'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['english'] then data[tostring(target)]['settings']['english'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_fwd'] then data[tostring(target)]['settings']['lock_fwd'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['reply'] then data[tostring(target)]['settings']['reply'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['join'] then data[tostring(target)]['settings']['join'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['fosh'] then data[tostring(target)]['settings']['fosh'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['cmds'] then data[tostring(target)]['settings']['cmds'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['username'] then data[tostring(target)]['settings']['username'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['media'] then data[tostring(target)]['settings']['media'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['leave'] then data[tostring(target)]['settings']['leave'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_member'] then data[tostring(target)]['settings']['lock_member'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['all'] then data[tostring(target)]['settings']['all'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['operator'] then data[tostring(target)]['settings']['operator'] = 'no' end end local lock_edit = "Yes" if not redis:get("lock:edit:"..msg.to.id) then lock_edit = "No" end local gp_type = data[tostring(msg.to.id)]['group_type'] local settings = data[tostring(target)]['settings'] local hash = 'group:'..msg.to.id local group_lang = redis:hget(hash,'lang') if group_lang then return reply_msg(msg.id,"✔️نام سوپرگروه:\n》"..msg.to.title.."\n✔️ایدی سوپرگروه:\n》"..msg.to.id.."\n✔️ایدی شما:\n》"..msg.from.id.."\n✔️یوزرنیم:\n》@"..(msg.from.username or '').."\n⚙تظیمات سوپرگروه⚙:\n➖➖➖➖➖➖➖\n💎قفل لینک: [ "..settings.lock_link.." ]\n🛡قفل مخاطب ها: [ "..settings.lock_contacts.." ]\n💎 قفل فلود: [ "..settings.flood.." ]\n🛡تعداد فلود: [ "..NUM_MSG_MAX.." ]\n💎قفل اسپم: [ "..settings.lock_spam.." ]\n🛡قفل چت عربی: [ "..settings.lock_arabic.." ]\n💎قفل ممبر: [ "..settings.lock_member.." ]\n🛡قفل راست به چپ: [ "..settings.lock_rtl.." ]\n💎قفل ورودوخروج: [ "..settings.lock_tgservice.." ]\n🛡قفل استیکر: [ "..settings.lock_sticker.." ]\n💎قفل هشتگ(#): [ "..settings.tag.." ]\n🛡قفل شکلک: [ "..settings.lock_emoji.." ]\n💎قفل چت انگلیسی: [ "..settings.english.." ]\n🛡قفل دستورات: [ "..settings.cmds.." ]\n💎قفل فوروارد: [ "..settings.lock_fwd.." ]\n🛡قفل ورود بالینک: [ "..settings.join.." ]\n💎قفل یوزرنیم(@): [ "..settings.username.." ]\n🛡قفل رسانه: [ "..settings.media.." ]\n💎قفل فحش: [ "..settings.fosh.." ]\n🛡قفل خروج: [ "..settings.leave.." ]\n💎قفل ربات: [ "..bots_protection.." ]\n🛡قفل اپراتور: [ "..settings.operator.." ]\n➖➖➖➖➖➖➖\n✨درباره سوپرگروه✨:\n➖➖➖➖➖➖➖\n🌟نوع گروه:\n》[ "..gp_type.." ]\n🌟عمومی بودن:\n》[ "..settings.public.." ]\n🌟تنظیمات سختگیرانه:\n》[ "..settings.strict.." ]\n➖➖➖➖\n#Protective\n➖➖➖➖\n", ok_cb, false) else return reply_msg(msg.id,"\n⚙ЅυρεгGгσυρ Ѕεττιπɢ\n➖➖➖➖➖➖➖\n🎗locĸ #cм∂➣[ "..settings.cmds.." ] \n 💢 locĸ #lιɴĸѕ➣[ "..settings.lock_link.." ]\n🎗locĸ #coɴтαcтѕ➣["..settings.lock_contacts.."]\n💢 locĸ #ғlood➣[ "..settings.flood.." ]\n🎗ғlood #eɴѕιтιvιтy➣["..NUM_MSG_MAX.."]\n💢locĸ #ѕpαм➣[ "..settings.lock_spam.." ]\n🎗locĸ #αrαвιc➣[ "..settings.lock_arabic.." ]\n💢locĸ #мeмвer➣[ "..settings.lock_member.." ]\n🎗locĸ #rтl➣[ "..settings.lock_rtl.." ]\n💢locĸ #тɢѕervιce➣["..settings.lock_tgservice.."]\n🎗locĸ #ѕтιcĸer➣[ "..settings.lock_sticker.." ]\n💢locĸ #тαɢ➣[ "..settings.tag.." ]\n🎗locĸ #eмojι➣[ "..settings.lock_emoji.." ]\n💢locĸ #eɴɢlιѕн➣[ "..settings.english.." ]\n🎗locĸ #ғorwαrd➣[ "..settings.lock_fwd.." ]\n💢locĸ #joιɴ➣[ "..settings.join.." ]\n🎗locĸ #υѕerɴαмe➣["..settings.username.."]\n💢locĸ #мedια➣[ "..settings.media.." ]\n🎗locĸ #ғoѕн➣[ "..settings.fosh.." ]\n💢locĸ #leαve➣[ "..settings.leave.." ]\n🎗locĸ #вoтѕ➣[ "..bots_protection.." ]\n💢locĸ #operαтor ➣["..settings.operator.."]\n➖➖➖➖➖➖➖\n🏵ɢroυp #тype\n》➣[ "..gp_type.." ]\n⭕️pυвlιc\n》➣[ "..settings.public.." ]\n🏵ѕтrιcт #ѕeттιɴɢѕ\n》➣[ "..settings.strict.." ]\n➖➖➖➖➖➖➖\n⭕️#ѕυperɢroυpɴαмe ➣["..msg.to.title.."]️\n🏵ѕυperɢroυpιd ➣["..msg.to.id.."]\n⭕️#yoυrιd ➣["..msg.from.id.."]\n🏵#υѕerɴαмe ➣[@"..(msg.from.username or '').."]\n➖➖➖➖➖➖➖", ok_cb, false) end end local function promote_admin(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') local member_tag_username = string.gsub(member_username, '@', '(at)') if not data[group] then return end if data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(user_id)] = member_tag_username save_data(_config.moderation.data, data) end local function demote_admin(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') if not data[group] then return end if not data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_tag_username..' is not a moderator.') end data[group]['moderators'][tostring(user_id)] = nil save_data(_config.moderation.data, data) end local function promote2(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') local member_tag_username = string.gsub(member_username, '@', '(at)') if not data[group] then return send_large_msg(receiver, 'SuperGroup is not added.') end if data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(user_id)] = member_tag_username save_data(_config.moderation.data, data) send_large_msg(receiver, member_username..' has been promoted.') end local function demote2(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_tag_username..' is not a moderator.') end data[group]['moderators'][tostring(user_id)] = nil save_data(_config.moderation.data, data) send_large_msg(receiver, member_username..' has been demoted.') end local function modlist(msg) local data = load_data(_config.moderation.data) local groups = "groups" if not data[tostring(groups)][tostring(msg.to.id)] then return 'SuperGroup is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - '..v..' [' ..k.. '] \n' i = i + 1 end return message end -- Start by reply actions function get_message_callback(extra, success, result) local get_cmd = extra.get_cmd local msg = extra.msg local data = load_data(_config.moderation.data) local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") if get_cmd == "id" and not result.action then local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for: ["..result.from.peer_id.."]") id1 = send_large_msg(channel, result.from.peer_id) elseif get_cmd == 'id' and result.action then local action = result.action.type if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then if result.action.user then user_id = result.action.user.peer_id else user_id = result.peer_id end local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id by service msg for: ["..user_id.."]") id1 = send_large_msg(channel, user_id) end elseif get_cmd == "idfrom" then local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for msg fwd from: ["..result.fwd_from.peer_id.."]") id2 = send_large_msg(channel, result.fwd_from.peer_id) elseif get_cmd == 'channel_block' and not result.action then local member_id = result.from.peer_id local channel_id = result.to.peer_id if member_id == msg.from.id then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end --savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply") kick_user(member_id, channel_id) local kickedhash = 'kicked:'..msg.from.id..':'..msg.to.id redis:incr(kickedhash) local kickedhash = 'kicked:'..msg.from.id..':'..msg.to.id local kicked = redis:get(kickedhash) elseif get_cmd == 'channel_block' and result.action and result.action.type == 'chat_add_user' then local user_id = result.action.user.peer_id local channel_id = result.to.peer_id if member_id == msg.from.id then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply to sev. msg.") kick_user(user_id, channel_id) local kickedhash = 'kicked:'..msg.from.id..':'..msg.to.id redis:incr(kickedhash) local kickedhash = 'kicked'..msg.from.id..':'..msg.to.id local kicked = redis:get(kickedhash) elseif get_cmd == "del" then delete_msg(result.id, ok_cb, false) savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted a message by reply") elseif get_cmd == "setadmin" then local user_id = result.from.peer_id local channel_id = "channel#id"..result.to.peer_id channel_set_admin(channel_id, "user#id"..user_id, ok_cb, false) if result.from.username then text = "@"..result.from.username.." set as an admin" else text = "[ "..user_id.." ]set as an admin" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..user_id.."] as admin by reply") send_large_msg(channel_id, text) elseif get_cmd == "demoteadmin" then local user_id = result.from.peer_id local channel_id = "channel#id"..result.to.peer_id if is_admin2(result.from.peer_id) then return send_large_msg(channel_id, "You can't demote global admins!") end channel_demote(channel_id, "user#id"..user_id, ok_cb, false) if result.from.username then text = "@"..result.from.username.." has been demoted from admin" else text = "[ "..user_id.." ] has been demoted from admin" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted: ["..user_id.."] from admin by reply") send_large_msg(channel_id, text) elseif get_cmd == "setowner" then local group_owner = data[tostring(result.to.peer_id)]['set_owner'] if group_owner then local channel_id = 'channel#id'..result.to.peer_id if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(channel_id, user, ok_cb, false) end local user_id = "user#id"..result.from.peer_id channel_set_admin(channel_id, user_id, ok_cb, false) data[tostring(result.to.peer_id)]['set_owner'] = tostring(result.from.peer_id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..result.from.peer_id.."] as owner by reply") if result.from.username then text = "@"..result.from.username.." [ "..result.from.peer_id.." ] added as owner" else text = "[ "..result.from.peer_id.." ] added as owner" end send_large_msg(channel_id, text) end elseif get_cmd == "promote" then local receiver = result.to.peer_id local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '') local member_name = full_name:gsub("‮", "") local member_username = member_name:gsub("_", " ") if result.from.username then member_username = '@'.. result.from.username end local member_id = result.from.peer_id if result.to.peer_type == 'channel' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted mod: @"..member_username.."["..result.from.peer_id.."] by reply") promote2("channel#id"..result.to.peer_id, member_username, member_id) --channel_set_mod(channel_id, user, ok_cb, false) end elseif get_cmd == "demote" then local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '') local member_name = full_name:gsub("‮", "") local member_username = member_name:gsub("_", " ") if result.from.username then member_username = '@'.. result.from.username end local member_id = result.from.peer_id --local user = "user#id"..result.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted mod: @"..member_username.."["..user_id.."] by reply") demote2("channel#id"..result.to.peer_id, member_username, member_id) --channel_demote(channel_id, user, ok_cb, false) elseif get_cmd == 'mute_user' then if result.service then local action = result.action.type if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then if result.action.user then user_id = result.action.user.peer_id end end if action == 'chat_add_user_link' then if result.from then user_id = result.from.peer_id end end else user_id = result.from.peer_id end local receiver = extra.receiver local chat_id = msg.to.id print(user_id) print(chat_id) if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) send_large_msg(receiver, "["..user_id.."] removed from the muted user list") elseif is_admin1(msg) then mute_user(chat_id, user_id) local mutedhash = 'muted:'..msg.from.id..':'..msg.to.id redis:incr(mutedhash) local mutedhash = 'muted:'..msg.from.id..':'..msg.to.id local muted = redis:get(mutedhash) send_large_msg(receiver, " ["..user_id.."] added to the muted user list") end end end -- End by reply actions --By ID actions local function cb_user_info(extra, success, result) local receiver = extra.receiver local user_id = result.peer_id local get_cmd = extra.get_cmd local data = load_data(_config.moderation.data) --[[if get_cmd == "setadmin" then local user_id = "user#id"..result.peer_id channel_set_admin(receiver, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been set as an admin" else text = "[ "..result.peer_id.." ] has been set as an admin" end send_large_msg(receiver, text)]] if get_cmd == "demoteadmin" then if is_admin2(result.peer_id) then return send_large_msg(receiver, "You can't demote global admins!") end local user_id = "user#id"..result.peer_id channel_demote(receiver, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been demoted from admin" send_large_msg(receiver, text) else text = "[ "..result.peer_id.." ] has been demoted from admin" send_large_msg(receiver, text) end elseif get_cmd == "promote" then if result.username then member_username = "@"..result.username else member_username = string.gsub(result.print_name, '_', ' ') end promote2(receiver, member_username, user_id) elseif get_cmd == "demote" then if result.username then member_username = "@"..result.username else member_username = string.gsub(result.print_name, '_', ' ') end demote2(receiver, member_username, user_id) end end -- Begin resolve username actions local function callbackres(extra, success, result) local member_id = result.peer_id local member_username = "@"..result.username local get_cmd = extra.get_cmd if get_cmd == "res" then local user = result.peer_id local name = string.gsub(result.print_name, "_", " ") local channel = 'channel#id'..extra.channelid send_large_msg(channel, user..'\n'..name) return user elseif get_cmd == "id" then local user = result.peer_id local channel = 'channel#id'..extra.channelid send_large_msg(channel, user) return user elseif get_cmd == "invite" then local receiver = extra.channel local user_id = "user#id"..result.peer_id channel_invite(receiver, user_id, ok_cb, false) --[[elseif get_cmd == "channel_block" then local user_id = result.peer_id local channel_id = extra.channelid local sender = extra.sender if member_id == sender then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(sender) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end kick_user(user_id, channel_id) elseif get_cmd == "setadmin" then local user_id = "user#id"..result.peer_id local channel_id = extra.channel channel_set_admin(channel_id, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been set as an admin" send_large_msg(channel_id, text) else text = "@"..result.peer_id.." has been set as an admin" send_large_msg(channel_id, text) end elseif get_cmd == "setowner" then local receiver = extra.channel local channel = string.gsub(receiver, 'channel#id', '') local from_id = extra.from_id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then local user = "user#id"..group_owner if not is_admin2(group_owner) and not is_support(group_owner) then channel_demote(receiver, user, ok_cb, false) end local user_id = "user#id"..result.peer_id channel_set_admin(receiver, user_id, ok_cb, false) data[tostring(channel)]['set_owner'] = tostring(result.peer_id) save_data(_config.moderation.data, data) savelog(channel, name_log.." ["..from_id.."] set ["..result.peer_id.."] as owner by username") if result.username then text = member_username.." [ "..result.peer_id.." ] added as owner" else text = "[ "..result.peer_id.." ] added as owner" end send_large_msg(receiver, text) end]] elseif get_cmd == "promote" then local receiver = extra.channel local user_id = result.peer_id --local user = "user#id"..result.peer_id promote2(receiver, member_username, user_id) --channel_set_mod(receiver, user, ok_cb, false) elseif get_cmd == "demote" then local receiver = extra.channel local user_id = result.peer_id local user = "user#id"..result.peer_id demote2(receiver, member_username, user_id) elseif get_cmd == "demoteadmin" then local user_id = "user#id"..result.peer_id local channel_id = extra.channel if is_admin2(result.peer_id) then return send_large_msg(channel_id, "You can't demote global admins!") end channel_demote(channel_id, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been demoted from admin" send_large_msg(channel_id, text) else text = "@"..result.peer_id.." has been demoted from admin" send_large_msg(channel_id, text) end local receiver = extra.channel local user_id = result.peer_id demote_admin(receiver, member_username, user_id) elseif get_cmd == 'mute_user' then local user_id = result.peer_id local receiver = extra.receiver local chat_id = string.gsub(receiver, 'channel#id', '') if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] removed from muted user list") elseif is_owner(extra.msg) then mute_user(chat_id, user_id) local mutedhash = 'muted:'..msg.from.id..':'..msg.to.id redis:incr(mutedhash) local mutedhash = 'muted:'..msg.from.id..':'..msg.to.id local muted = redis:get(mutedhash) send_large_msg(receiver, " ["..user_id.."] added to muted user list") end end end --End resolve username actions --Begin non-channel_invite username actions local function in_channel_cb(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local msg = cb_extra.msg local data = load_data(_config.moderation.data) local print_name = user_print_name(cb_extra.msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") local member = cb_extra.username local memberid = cb_extra.user_id if member then text = 'No user @'..member..' in this SuperGroup.' else text = 'No user ['..memberid..'] in this SuperGroup.' end if get_cmd == "channel_block" then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local user_id = v.peer_id local channel_id = cb_extra.msg.to.id local sender = cb_extra.msg.from.id if user_id == sender then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(user_id, channel_id) and not is_admin2(sender) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(user_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end if v.username then text = "." savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..v.username.." ["..v.peer_id.."]") else text = "." savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..v.peer_id.."]") end kick_user(user_id, channel_id) local kickedhash = 'kicked:'..msg.from.id..':'..msg.to.id redis:incr(kickedhash) local kickedhash = 'kicked:'..msg.from.id..':'..msg.to.id local kicked = redis:get(kickedhash) return end end elseif get_cmd == "setadmin" then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local user_id = "user#id"..v.peer_id local channel_id = "channel#id"..cb_extra.msg.to.id channel_set_admin(channel_id, user_id, ok_cb, false) if v.username then text = "@"..v.username.." ["..v.peer_id.."] has been set as an admin" savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..v.username.." ["..v.peer_id.."]") else text = "["..v.peer_id.."] has been set as an admin" savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin "..v.peer_id) end if v.username then member_username = "@"..v.username else member_username = string.gsub(v.print_name, '_', ' ') end local receiver = channel_id local user_id = v.peer_id promote_admin(receiver, member_username, user_id) end send_large_msg(channel_id, text) return end elseif get_cmd == 'setowner' then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local channel = string.gsub(receiver, 'channel#id', '') local from_id = cb_extra.msg.from.id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(receiver, user, ok_cb, false) end local user_id = "user#id"..v.peer_id channel_set_admin(receiver, user_id, ok_cb, false) data[tostring(channel)]['set_owner'] = tostring(v.peer_id) save_data(_config.moderation.data, data) savelog(channel, name_log.."["..from_id.."] set ["..v.peer_id.."] as owner by username") if result.username then text = member_username.." ["..v.peer_id.."] added as owner" else text = "["..v.peer_id.."] added as owner" end end elseif memberid and vusername ~= member and vpeer_id ~= memberid then local channel = string.gsub(receiver, 'channel#id', '') local from_id = cb_extra.msg.from.id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(receiver, user, ok_cb, false) end data[tostring(channel)]['set_owner'] = tostring(memberid) save_data(_config.moderation.data, data) savelog(channel, name_log.."["..from_id.."] set ["..memberid.."] as owner by username") text = "["..memberid.."] added as owner" end end end end send_large_msg(receiver, text) end --End non-channel_invite username actions --'Set supergroup photo' function local function set_supergroup_photo(msg, success, result) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return end local receiver = get_receiver(msg) if success then local file = 'data/photos/channel_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) channel_set_photo(receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end --Run function local function run(msg, matches) if msg.to.type == 'chat' then if matches[1] == 'tosuper' or matches[1] =='تبدیل' then if not is_admin1(msg) then return end local receiver = get_receiver(msg) chat_upgrade(receiver, ok_cb, false) end elseif msg.to.type == 'channel' then if matches[1] == 'tosuper' or matches[1] =='تبدیل' then if not is_admin1(msg) then return end return "Already a SuperGroup" end end if msg.to.type == 'channel' then local support_id = msg.from.id local receiver = get_receiver(msg) local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") local data = load_data(_config.moderation.data) if matches[1] == 'add' or matches[1] =='اد شو' and not matches[2] then if not is_admin1(msg) and not is_support(support_id) then return end if is_super_group(msg) then return reply_msg(msg.id, 'SuperGroup is already added.', ok_cb, false) end print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") added") savelog(msg.to.id, name_log.." ["..msg.from.id.."] added SuperGroup") superadd(msg) set_mutes(msg.to.id) channel_set_admin(receiver, 'user#id'..msg.from.id, ok_cb, false) end if matches[1] == 'rem' and is_admin1(msg) and not matches[2] then if not is_super_group(msg) then return reply_msg(msg.id, 'SuperGroup is not added.', ok_cb, false) end print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") removed") superrem(msg) rem_mutes(msg.to.id) end if matches[1] == 'حذف شو' and is_admin1(msg) and not matches[2] then if not is_super_group(msg) then return reply_msg(msg.id, 'SuperGroup is not added.', ok_cb, false) end print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") removed") superrem(msg) rem_mutes(msg.to.id) end if not data[tostring(msg.to.id)] then return end if matches[1] == "gpinfo" or matches[1] =='اطلاعات گپ' then if not is_owner(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup info") channel_info(receiver, callback_info, {receiver = receiver, msg = msg}) end if matches[1] == "admins" or matches[1] =="ادمین ها" then if not is_owner(msg) and not is_support(msg.from.id) then return end member_type = 'Admins' savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup Admins list") admins = channel_get_admins(receiver,callback, {receiver = receiver, msg = msg, member_type = member_type}) end if matches[1] == "owner" or matches[1] =="ایدی صاحب" then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "no owner,ask admins in support groups to set owner for your SuperGroup" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "SuperGroup owner is ["..group_owner..']' end if matches[1] == "modlist" or matches[1] =="لیست مدیران" then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) -- channel_get_admins(receiver,callback, {receiver = receiver}) end if matches[1] == "bots" and is_momod(msg) or matches[1] =="ربات ها" and is_momod(msg) then member_type = 'Bots' savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup bots list") channel_get_bots(receiver, callback, {receiver = receiver, msg = msg, member_type = member_type}) end if matches[1] == "who" or matches[1] =="اعضای گروه" and not matches[2] and is_momod(msg) then local user_id = msg.from.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup users list") channel_get_users(receiver, callback_who, {receiver = receiver}) end if matches[1] == "kicked" and is_momod(msg) or matches[1] =="اخراج شد" and is_momod(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested Kicked users list") channel_get_kicked(receiver, callback_kicked, {receiver = receiver}) end if matches[1] == 'del' and is_momod(msg) or matches[1] =='حذف' and is_momod(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'del', msg = msg } delete_msg(msg.id, ok_cb, false) get_message(msg.reply_id, get_message_callback, cbreply_extra) end end if matches[1] == 'block' and is_momod(msg) or matches[1] =='بن' and is_momod(msg) or matches[1] == 'kick' and is_momod(msg) or matches[1] =='اخراج' and is_momod(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'channel_block', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'block' or matches[1] =='بن' or matches[1] == 'kick' or matches[1] =='اخراج' and string.match(matches[2], '^%d+$') then --[[local user_id = matches[2] local channel_id = msg.to.id if is_momod2(user_id, channel_id) and not is_admin2(user_id) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: [ user#id"..user_id.." ]") kick_user(user_id, channel_id)]] local get_cmd = 'channel_block' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif msg.text:match("@[%a%d]") then --[[local cbres_extra = { channelid = msg.to.id, get_cmd = 'channel_block', sender = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..username) resolve_username(username, callbackres, cbres_extra)]] local get_cmd = 'channel_block' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1] == 'id'or matches[1] =='ایدی' then if type(msg.reply_id) ~= "nil" and is_momod(msg) and not matches[2] then local cbreply_extra = { get_cmd = 'id', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif type(msg.reply_id) ~= "nil" and matches[2] == "from" and is_momod(msg) then local cbreply_extra = { get_cmd = 'idfrom', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif msg.text:match("@[%a%d]") then local cbres_extra = { channelid = msg.to.id, get_cmd = 'id' } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested ID for: @"..username) resolve_username(username, callbackres, cbres_extra) else savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup ID") text = "👤ɴαмɛ: " ..string.gsub(msg.from.print_name, "_", " ").. "\n👤ʊsɛʀɴαмɛ: @"..(msg.from.username or '----').."\n🆔уσυя ι∂: "..msg.from.id.."\n-------------------------------------\n⚫sυpεʀɢʀoυ℘ ɴαмɛ: " ..string.gsub(msg.to.print_name, "_", " ").. "\n⚫️sυpεʀɢʀoυ℘ iÐ: "..msg.to.id reply_msg(msg.id, text, ok_cb, false) end end if matches[1] == 'kickme' then if msg.to.type == 'channel' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] left via kickme") channel_kick("channel#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if matches[1] == 'newlink' and is_momod(msg) or matches[1] =='لینک جدید' and is_momod(msg)then local function callback_link (extra , success, result) local receiver = get_receiver(msg) if success == 0 then send_large_msg(receiver, '*Error: Failed to retrieve link* \nReason: Not creator.\n\nIf you have the link, please use /setlink to set it') data[tostring(msg.to.id)]['settings']['set_link'] = nil save_data(_config.moderation.data, data) else send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to create a new SuperGroup link") export_channel_link(receiver, callback_link, false) end if matches[1] == 'setlink' and is_owner(msg) or matches[1] =='نشاندن لینک' and is_owner(msg) then data[tostring(msg.to.id)]['settings']['set_link'] = 'waiting' save_data(_config.moderation.data, data) return '》Please send the new group link now\n》اکنون لینک گروه خود را ارسال کنید.' end if msg.text then if msg.text:match("^(https://telegram.me/joinchat/%S+)$") and data[tostring(msg.to.id)]['settings']['set_link'] == 'waiting' and is_owner(msg) then data[tostring(msg.to.id)]['settings']['set_link'] = msg.text save_data(_config.moderation.data, data) return "》New link set\n》لینک ثبت شد." end end if matches[1] == 'link'or matches[1] =='لینک' then if not is_momod(msg) then return end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first!\n\nOr if I am not creator use /setlink to set your link\n___________________\nبرای ساختن لینک جدید ابتدا دستور 'لینک جدید' را بزنید.\nدرصورتی که ربات سازنده گروه نیست دستور 'نشاندن لینک' را بزنید." end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end if matches[1] == "invite" and is_sudo(msg) or matches[1] =='دعوت' and is_sudo(msg) then local cbres_extra = { channel = get_receiver(msg), get_cmd = "invite" } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] invited @"..username) resolve_username(username, callbackres, cbres_extra) end if matches[1] == 'res' and is_owner(msg) then local cbres_extra = { channelid = msg.to.id, get_cmd = 'res' } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] resolved username: @"..username) resolve_username(username, callbackres, cbres_extra) end --[[if matches[1] == 'kick' and is_momod(msg) or matches[1] =='اخراج' and is_momod(msg) then local receiver = channel..matches[3] local user = "user#id"..matches[2] chaannel_kick(receiver, user, ok_cb, false) end]] if matches[1] == 'setadmin'or matches[1] =='ادمین' then if not is_support(msg.from.id) and not is_owner(msg) then return end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'setadmin', msg = msg } setadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'setadmin' and string.match(matches[2], '^%d+$') then --[[] local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'setadmin' user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})]] local get_cmd = 'setadmin' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif matches[1] == 'setadmin'or matches[1] =='ادمین' and not string.match(matches[2], '^%d+$') then --[[local cbres_extra = { channel = get_receiver(msg), get_cmd = 'setadmin' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..username) resolve_username(username, callbackres, cbres_extra)]] local get_cmd = 'setadmin' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1] == 'demoteadmin'or matches[1] =='تنزل ادمین' then if not is_support(msg.from.id) and not is_owner(msg) then return end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'demoteadmin', msg = msg } demoteadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'demoteadmin'or matches[1] =='تنزل ادمین' and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'demoteadmin' user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif matches[1] == 'demoteadmin'or matches[1] =='تنزل ادمین' and not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'demoteadmin' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted admin @"..username) resolve_username(username, callbackres, cbres_extra) end end if matches[1] == 'setowner' and is_owner(msg) or matches[1] =='صاحب' and is_owner(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'setowner', msg = msg } setowner = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'setowner' and string.match(matches[2], '^%d+$') then --[[ local group_owner = data[tostring(msg.to.id)]['set_owner'] if group_owner then local receiver = get_receiver(msg) local user_id = "user#id"..group_owner if not is_admin2(group_owner) and not is_support(group_owner) then channel_demote(receiver, user_id, ok_cb, false) end local user = "user#id"..matches[2] channel_set_admin(receiver, user, ok_cb, false) data[tostring(msg.to.id)]['set_owner'] = tostring(matches[2]) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = "[ "..matches[2].." ] added as owner" return text end]] local get_cmd = 'setowner' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif matches[1] == 'setowner'or matches[1] =='صاحب' and not string.match(matches[2], '^%d+$') then local get_cmd = 'setowner' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1] == 'promote' then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner/admin can promote" end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'promote', msg = msg } promote = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'promote' and matches[2] and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'promote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted user#id"..matches[2]) user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif matches[1] == 'promote' and matches[2] and not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'promote', } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @"..username) return resolve_username(username, callbackres, cbres_extra) end end if matches[1] == 'mp' and is_sudo(msg) then channel = get_receiver(msg) user_id = 'user#id'..matches[2] channel_set_mod(channel, user_id, ok_cb, false) return "ok" end if matches[1] == 'md' and is_sudo(msg) then channel = get_receiver(msg) user_id = 'user#id'..matches[2] channel_demote(channel, user_id, ok_cb, false) return "ok" end if matches[1] == 'demote' then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner/support/admin can promote" end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'demote', msg = msg } demote = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'demote' and matches[2] and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'demote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted user#id"..matches[2]) user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif matches[1] == 'demote' and matches[2] and not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'demote' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @"..username) return resolve_username(username, callbackres, cbres_extra) end end if matches[1] == 'مدیر' then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner/admin can promote" end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'promote', msg = msg } promote = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'مدیر' and matches[2] and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'promote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted user#id"..matches[2]) user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif matches[1] == 'مدیر' and matches[2] and not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'promote', } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @"..username) return resolve_username(username, callbackres, cbres_extra) end end if matches[1] == 'تنزل مدیر' then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner/support/admin can promote" end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'demote', msg = msg } demote = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'تنزل مدیر' and matches[2] and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'demote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted user#id"..matches[2]) user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif matches[1] == 'تنزل مدیر' and matches[2] and not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'demote' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @"..username) return resolve_username(username, callbackres, cbres_extra) end end if matches[1] == "setname" and is_momod(msg) or matches[1] =="نشاندن اسم" and is_momod(msg) then local receiver = get_receiver(msg) local set_name = string.gsub(matches[2], '_', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..matches[2]) rename_channel(receiver, set_name, ok_cb, false) end if msg.service and msg.action.type == 'chat_rename' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..msg.to.title) data[tostring(msg.to.id)]['settings']['set_name'] = msg.to.title save_data(_config.moderation.data, data) end if matches[1] == "setabout" and is_momod(msg) or matches[1] =="نشاندن درباره گروه" and is_momod(msg) then local receiver = get_receiver(msg) local about_text = matches[2] local data_cat = 'description' local target = msg.to.id data[tostring(target)][data_cat] = about_text save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup description to: "..about_text) channel_set_about(receiver, about_text, ok_cb, false) return "Description has been set.\n\nSelect the chat again to see the changes." end if matches[1] == "setusername" and is_admin1(msg) then local function ok_username_cb (extra, success, result) local receiver = extra.receiver if success == 1 then send_large_msg(receiver, "SuperGroup username Set.\n\nSelect the chat again to see the changes.") elseif success == 0 then send_large_msg(receiver, "Failed to set SuperGroup username.\nUsername may already be taken.\n\nNote: Username can use a-z, 0-9 and underscores.\nMinimum length is 5 characters.") end end local username = string.gsub(matches[2], '@', '') channel_set_username(receiver, username, ok_username_cb, {receiver=receiver}) end if matches[1] == 'setrules' and is_momod(msg) or matches[1] =='نشاندن قوانین' and is_momod(msg) then rules = matches[2] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[2].."]") return set_rulesmod(msg, data, target) end if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_momod(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set new SuperGroup photo") load_photo(msg.id, set_supergroup_photo, msg) return end end if matches[1] == 'setphoto' and is_momod(msg) or matches[1] =='نشاندن عکس' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] started setting new SuperGroup photo") return 'Please send the new group photo now' end if matches[1] == 'clean'or matches[1] =='حذف' then if not is_momod(msg) then return end if not is_momod(msg) then return "Only owner can clean" end if matches[2] == 'modlist'or matches[2] =='مدیران' then if next(data[tostring(msg.to.id)]['moderators']) == nil then return 'No moderator(s) in this SuperGroup.' end for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") return 'Modlist has been cleaned' end if matches[2] == 'rules'or matches[2] =='قوانین' then local data_cat = 'rules' if data[tostring(msg.to.id)][data_cat] == nil then return "Rules have not been set" end data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") return 'Rules have been cleaned' end if matches[2] == 'about'or matches[2] =='درباره گروه' then local receiver = get_receiver(msg) local about_text = ' ' local data_cat = 'description' if data[tostring(msg.to.id)][data_cat] == nil then return 'About is not set' end data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") channel_set_about(receiver, about_text, ok_cb, false) return "About has been cleaned" end if matches[2] == 'silentlist'or matches[2] =='لیست صامت شدگان' then chat_id = msg.to.id local hash = 'mute_user:'..chat_id redis:del(hash) return "silentlist Cleaned" end if matches[2] == 'username' and is_admin1(msg) then local function ok_username_cb (extra, success, result) local receiver = extra.receiver if success == 1 then send_large_msg(receiver, "SuperGroup username cleaned.") elseif success == 0 then send_large_msg(receiver, "Failed to clean SuperGroup username.") end end local username = "" channel_set_username(receiver, username, ok_username_cb, {receiver=receiver}) end end if matches[1] == 'lock'or matches[1] =='قفل کردن' and is_momod(msg) then local target = msg.to.id if matches[2] == 'links'or matches[2] =='لینک' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link posting ") return lock_group_links(msg, data, target) end if matches[2] == 'join'or matches[2] =='ورود' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked join ") return lock_group_join(msg, data, target) end if matches[2] == 'tag'or matches[2] =='تگ' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked tag ") return lock_group_tag(msg, data, target) end if matches[2] == 'spam'or matches[2] =='اسپم' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked spam ") return lock_group_spam(msg, data, target) end if matches[2] == 'flood'or matches[2] =='فلود' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_flood(msg, data, target) end if matches[2] == 'arabic'or matches[2] =='عربی' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'member'or matches[2] =='ممبر' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2]:lower() == 'rtl'or matches[2] =='راست به چپ' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked rtl chars. in names") return lock_group_rtl(msg, data, target) end if matches[2] == 'tgservice'or matches[2] =='ورودوخروج' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked Tgservice Actions") return lock_group_tgservice(msg, data, target) end if matches[2] == 'sticker'or matches[2] =='استیکر' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked sticker posting") return lock_group_sticker(msg, data, target) end if matches[2] == 'contacts'or matches[2] =='مخاطب ها' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked contact posting") return lock_group_contacts(msg, data, target) end if matches[2] == 'strict'or matches[2] =='سختگیرانه' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked enabled strict settings") return enable_strict_rules(msg, data, target) end if matches[2] == 'english'or matches[2] =='انگلیسی' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked english") return lock_group_english(msg, data, target) end if matches[2] == 'fwd'or matches[2] =='فوروارد' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked fwd") return lock_group_fwd(msg, data, target) end if matches[2] == 'emoji'or matches[2] =='شکلک' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked emoji") return lock_group_emoji(msg, data, target) end if matches[2] == 'cmd' or matches[2] == 'دستورات' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked cmds") return lock_group_cmds(msg, data, target) end if matches[2] == 'fosh'or matches[2] =='فحش' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked fosh") return lock_group_fosh(msg, data, target) end if matches[2] == 'media'or matches[2] =='رسانه' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked media") return lock_group_media(msg, data, target) end if matches[2] == 'username'or matches[2] =='ایدی' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked username") return lock_group_username(msg, data, target) end if matches[2] == 'leave'or matches[2] =='خروج' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leave") return lock_group_leave(msg, data, target) end if matches[2] == 'bots'or matches[2] =='ربات ها' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots and kicked all SuperGroup bots") channel_get_bots(receiver, callback_clean_bots, {msg = msg}) return lock_group_bots(msg, data, target) end if matches[2] == 'operator'or matches[2] =='اپراتور' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked operator") return lock_group_operator(msg, data, target) end end if matches[1] == 'unlock'or matches[1] =='بازکردن' and is_momod(msg) then local target = msg.to.id if matches[2] == 'links'or matches[2] =='لینک' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link posting") return unlock_group_links(msg, data, target) end if matches[2] == 'join'or matches[2] =='ورود' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked join") return unlock_group_join(msg, data, target) end if matches[2] == 'tag'or matches[2] =='تگ' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tag") return unlock_group_tag(msg, data, target) end if matches[2] == 'spam'or matches[2] =='اسپم' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked spam") return unlock_group_spam(msg, data, target) end if matches[2] == 'flood'or matches[2] =='فلود' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood") return unlock_group_flood(msg, data, target) end if matches[2] == 'arabic'or matches[2] =='عربی' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked Arabic") return unlock_group_arabic(msg, data, target) end if matches[2] == 'member'or matches[2] =='ممبر' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2]:lower() == 'rtl'or matches[2] =='راست به چب' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked RTL chars. in names") return unlock_group_rtl(msg, data, target) end if matches[2] == 'tgservice'or matches[2] =='ورودوخروج' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tgservice actions") return unlock_group_tgservice(msg, data, target) end if matches[2] == 'sticker'or matches[2] =='استیکر' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked sticker posting") return unlock_group_sticker(msg, data, target) end if matches[2] == 'contacts'or matches[2] =='مخاطب ها' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked contact posting") return unlock_group_contacts(msg, data, target) end if matches[2] == 'strict'or matches[2] =='سختگیرانه' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled strict settings") return disable_strict_rules(msg, data, target) end if matches[2] == 'english'or matches[2] =='انگلیسی' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked english") return unlock_group_english(msg, data, target) end if matches[2] == 'fwd'or matches[2] =='فوروارد' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked fwd") return unlock_group_fwd(msg, data, target) end if matches[2] == 'cmd' or matches[2] == 'دستورات' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked cmds") return unlock_group_cmds(msg, data, target) end if matches[2] == 'emoji'or matches[2] =='شکلک' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled emoji") return unlock_group_emoji(msg, data, target) end if matches[2] == 'fosh'or matches[2] =='فحش' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked fosh") return unlock_group_fosh(msg, data, target) end if matches[2] == 'media'or matches[2] =='رسانه' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked media") return unlock_group_media(msg, data, target) end if matches[2] == 'username'or matches[2] =='ایدی' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled username") return unlock_group_username(msg, data, target) end if matches[2] == 'leave' or matches[2] =='خروج' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leave") return unlock_group_leave(msg, data, target) end if matches[2] == 'bots'or matches[2] =='ربات ها' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots") return unlock_group_bots(msg, data, target) end if matches[2] == 'operator'or matches[2] =='اپراتور' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked operator") return unlock_group_operator(msg, data, target) end end if matches[1] == 'setflood'or matches[1] =='تنظیم حساسیت' then if not is_momod(msg) then return end if tonumber(matches[2]) < 4 or tonumber(matches[2]) > 25 then return "Wrong number,range is [4-25]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Flood has been set to: '..matches[2] end if matches[1] == 'public'or matches[1] =='عمومی' and is_owner(msg) then local target = msg.to.id if matches[2] == 'yes'or matches[2] =='باشد' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public") return set_public_membermod(msg, data, target) end if matches[2] == 'no'or matches[2] =='نباشد' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: not public") return unset_public_membermod(msg, data, target) end end if matches[1] == 'mute'and is_momod(msg) or matches[1] =='قفل کردن' and is_momod(msg) then local chat_id = msg.to.id if matches[2] == 'audio'or matches[2] =='آهنگ' then local msg_type = 'Audio' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." has been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'photo'or matches[2] =='عکس' then local msg_type = 'Photo' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." has been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'video'or matches[2] =='فیلم' then local msg_type = 'Video' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." has been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'gifs'or matches[2] =='گیف' then local msg_type = 'Gifs' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." have been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'documents'or matches[2] =='فایل' then local msg_type = 'Documents' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." have been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'text'or matches[2] =='چت' then local msg_type = 'Text' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." has been muted" else return "Mute "..msg_type.." is already on" end end if matches[2] == 'all'or matches[2] =='همه چت ها' then local msg_type = 'All' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return "Mute "..msg_type.." has been enabled" else return "Mute "..msg_type.." is already on" end end end if matches[1] == 'unmute' and is_momod(msg) or matches[1] =='بازکردن' and is_momod(msg) then local chat_id = msg.to.id if matches[2] == 'audio'or matches[2] =='آهنگ' then local msg_type = 'Audio' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." has been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'photo'or matches[2] =='عکس' then local msg_type = 'Photo' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." has been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'video'or matches[2] =='فیلم' then local msg_type = 'Video' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." has been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'gifs'or matches[2] =='گیف' then local msg_type = 'Gifs' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." have been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'documents'or matches[2] =='فایل' then local msg_type = 'Documents' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." have been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'text'or matches[2] =='چت' then local msg_type = 'Text' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute message") unmute(chat_id, msg_type) return msg_type.." has been unmuted" else return "Mute text is already off" end end if matches[2] == 'all'or matches[2] =='همه چت ها' then local msg_type = 'All' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return "Mute "..msg_type.." has been disabled" else return "Mute "..msg_type.." is already disabled" end end end if matches[1] == "silent" and is_momod(msg) or matches[1] =='صامت' and is_momod(msg) or matches[1] == "unsilent" and is_momod(msg) or matches[1] =='مصوت' and is_momod(msg) then local chat_id = msg.to.id local hash = "mute_user"..chat_id local user_id = "" if type(msg.reply_id) ~= "nil" then local receiver = get_receiver(msg) local get_cmd = "mute_user" muteuser = get_message(msg.reply_id, get_message_callback, {receiver = receiver, get_cmd = get_cmd, msg = msg}) elseif matches[1] == "silent"or matches[1] =='صامت' or matches[1] == "unsilent"or matches[1] =='مصوت' and string.match(matches[2], '^%d+$') then local user_id = matches[2] if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) savelog(msg.to.id, name_log.." ["..msg.from.id.."] removed ["..user_id.."] from the muted users list") return "["..user_id.."] removed from the muted users list" elseif is_momod(msg) then mute_user(chat_id, user_id) local mutedhash = 'muted:'..msg.from.id..':'..msg.to.id redis:incr(mutedhash) local mutedhash = 'muted:'..msg.from.id..':'..msg.to.id local muted = redis:get(mutedhash) --savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."] to the muted users list") return "["..user_id.."] added to the muted user list" end elseif matches[1] == "silent"or matches[1] =='صامت' or matches[1] == "unsilent" and not string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local get_cmd = "mute_user" local username = matches[2] local username = string.gsub(matches[2], '@', '') resolve_username(username, callbackres, {receiver = receiver, get_cmd = get_cmd, msg=msg}) end end if matches[1] == "muteslist" and is_momod(msg) or matches[1] =='لیست اعضای صامت' and is_momod(msg) then local chat_id = msg.to.id if not has_mutes(chat_id) then set_mutes(chat_id) return mutes_list(chat_id) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup muteslist") return mutes_list(chat_id) end if matches[1] == "silentlist" and is_momod(msg) or matches[1] =='لبست صامت شدگان' and is_momod(msg) then local chat_id = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup mutelist") return muted_user_list(chat_id) end if matches[1] == 'settings' and is_momod(msg) or matches[1] =='تنظیمات' and is_momod(msg) then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup settings ") return show_supergroup_settingsmod(msg, target) end if matches[1] == 'rules'or matches[1] =='قوانین' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'help' and not is_momod(msg) then text = "Message /superhelp in private for SuperGroup help" reply_msg(msg.id, text, ok_cb, false) elseif matches[1] == 'help' and is_momod(msg) then local name_log = user_print_name(msg.from) --savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /superhelp") return super_help() end if matches[1] == 'peer_id' and is_admin1(msg)then text = msg.to.peer_id reply_msg(msg.id, text, ok_cb, false) post_large_msg(receiver, text) end if matches[1] == 'msg.to.id' and is_admin1(msg) then text = msg.to.id reply_msg(msg.id, text, ok_cb, false) post_large_msg(receiver, text) end --Admin Join Service Message if msg.service then local action = msg.action.type if action == 'chat_add_user_link' then if is_owner2(msg.from.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.from.id savelog(msg.to.id, name_log.." Admin ["..msg.from.id.."] joined the SuperGroup via link") channel_set_admin(receiver, user, ok_cb, false) end if is_support(msg.from.id) and not is_owner2(msg.from.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.from.id savelog(msg.to.id, name_log.." Support member ["..msg.from.id.."] joined the SuperGroup") channel_set_mod(receiver, user, ok_cb, false) end end if action == 'chat_add_user' then if is_owner2(msg.action.user.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.action.user.id savelog(msg.to.id, name_log.." Admin ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]") channel_set_admin(receiver, user, ok_cb, false) end if is_support(msg.action.user.id) and not is_owner2(msg.action.user.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.action.user.id savelog(msg.to.id, name_log.." Support member ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]") channel_set_mod(receiver, user, ok_cb, false) end end end if matches[1] == 'msg.to.peer_id' then post_large_msg(receiver, msg.to.peer_id) end end end local function pre_process(msg) if not msg.text and msg.media then msg.text = '['..msg.media.type..']' end return msg end return { patterns = { "^[#!/]([Aa]dd)$", "^[#!/]([Rr]em)$", "^[#!/]([Mm]ove) (.*)$", "^[#!/]([Gg]pinfo)$", "^[#!/]([Aa]dmins)$", "^[#!/]([Oo]wner)$", "^[#!/]([Mm]odlist)$", "^[#!/]([Bb]ots)$", "^[!#/](لیست مدیران)$", "^(اد شو)$", "^(حذف شو)$", "^(اطلاعات گپ)$", "^(ادمین ها)$", "^(ایدی صاحب)$", "^(لیست مدیران)$", "^(ربات ها)$", "^(درباره گروه)$", "^[#!/]([Ww]ho)$", "^[#!/]([Kk]icked)$", "^[#!/]([Bb]lock) (.*)", "^[#!/]([Bb]lock)", "^[#!/]([Kk]ick) (.*)", "^[#!/]([Kk]ick)", "^[#!/]([Tt]osuper)$", "^[#!/]([Ii][Dd])$", "^[#!/]([Ii][Dd]) (.*)$", "^[#!/]([Kk]ickme)$", "^[#!/]([Nn]ewlink)$", "^[#!/]([Ss]etlink)$", "^[#!/]([Ll]ink)$", "^[#!/]([Rr]es) (.*)$", "^[#!/]([Ss]etadmin) (.*)$", "^[#!/]([Ss]etadmin)", "^[#!/]([Dd]emoteadmin) (.*)$", "^[#!/]([Dd]emoteadmin)", "^[#!/]([Ss]etowner) (.*)$", "^[#!/]([Ss]etowner)$", "^[#!/]([Pp]romote) (.*)$", "^[#!/]([Pp]romote)", "^[#!/]([Dd]emote) (.*)$", "^[#!/]([Dd]emote)", "^[#!/]([Ss]etname) (.*)$", "^[#!/]([Ss]etabout) (.*)$", "^[#!/]([Ss]etrules) (.*)$", "^[#!/]([Ss]etphoto)$", "^(ادمین) (.*)$", "^(ادمین)", "^(تنزل ادمین) (.*)$", "^(تنزل ادمین)", "^(صاحب) (.*)$", "^(صاحب)$", "^(مدیر) (.*)$", "^(مدیر)", "^(تنزل مدیر) (.*)$", "^(تنزل مدیر)", "^(نشاندن اسم) (.*)$", "^(نشاندن درباره گروه) (.*)$", "^(نشاندن قوانین) (.*)$", "^(نشاندن عکس)$", "^(اعضای گروه)$", "^(اخراج شد)$", "^(بن) (.*)", "^(بن)", "^(اخراج) (.*)", "^(اخراج)", "^(تبدیل)$", "^(ایدی)$", "^(ایدی) (.*)$", "^(لینک جدید)$", "^(نشاندن لینک)$", "^(لینک)$", "^(نشاندن قوانین) (.*)$", "^(نشاندن عکس)$", "^[#!/]([Ss]etusername) (.*)$", "^(نشاندن ایدی) (.*)$", "^[#!/]([Dd]el)$", "^(حذف)$", "^[#!/]([Ll]ock) (.*)$", "^(قفل کردن) (.*)$", "^(بازکردن) (.*)$", "^[#!/]([Uu]nlock) (.*)$", "^[#!/]([Mm]ute) ([^%s]+)$", "^[#!/]([Uu]nmute) ([^%s]+)$", "^(قفل کردن) ([^%s]+)$", "^(بازکردن) ([^%s]+)$", "^[#!/]([Ss]ilent)$", "^[#!/]([Ss]ilent) (.*)$", "^[#!/]([Uu]nsilent)$", "^[#!/]([Uu]nsilent) (.*)$", "^[#!/]([Pp]ublic) (.*)$", "^(عمومی) (.*)$", "^[#!/]([Ss]ettings)$", "^[#!/]([Rr]ules)$", "^(صامت)$", "^(صامت) (.*)$", "^(مصوت)$", "^(مصوت) (.*)$", "^(تنظیمات)$", "^(قوانین)$", "^[#!/]([Ss]etflood) (%d+)$", "^(تنظیم حساسیت) (%d+)$", "^[#!/]([Cc]lean) (.*)$", "^(حذف) (.*)$", "^[#!/]([Hh]elp)$", "^[#!/]([Mm]uteslist)$", "^[#!/]([Ss]ilentlist)$", "^(لیست اعضای صامت)$", "^(لیست صامت شدگان)$", "[#!/](mp) (.*)", "[#!/](md) (.*)", "^(https://telegram.me/joinchat/%S+)$", "%[(document)%]", "%[(photo)%]", "%[(video)%]", "%[(audio)%]", "%[(contact)%]", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process }
gpl-2.0
frugalware/frugalware-current
source/xapps-extra/texlive/texmfcnf.lua
9
8268
-- public domain -- ConTeXt needs a properly expanded TEXMFLOCAL, so here is a -- bit of lua code to make that happen local texmflocal = resolvers.prefixes.selfautoparent(); texmflocal = string.gsub(texmflocal, "20%d%d$", "texmf-local"); return { type = "configuration", version = "1.1.0", date = "2012-05-24", time = "12:12:12", comment = "ConTeXt MkIV configuration file", author = "Hans Hagen, PRAGMA-ADE, Hasselt NL", content = { -- Originally there was support for engines and progname but I don't expect -- other engines to use this file, so first engines were removed. After that -- if made sense also to get rid of progname. At some point specific formats -- will be supported but then as a subtable with fallbacks, which sounds more -- natural. Also, at some point the paths will become tables. For the moment -- I don't care too much about it as extending is easy. variables = { -- The following variable is predefined (but can be overloaded) and in -- most cases you can leve this one untouched. The built-in definition -- permits relocation of the tree. -- -- TEXMFCNF = "{selfautodir:,selfautoparent:}{,{/share,}/texmf{-local,}/web2c}" -- -- more readable than "selfautoparent:{/texmf{-local,}{,/web2c},}}" is: -- -- TEXMFCNF = { -- "selfautoparent:/texmf-local", -- "selfautoparent:/texmf-local/web2c", -- "selfautoparent:/texmf-dist", -- "selfautoparent:/texmf/web2c", -- "selfautoparent:", -- } -- only used for FONTCONFIG_PATH & TEXMFCACHE in TeX Live TEXMFSYSVAR = "/var/lib/texmf", TEXMFVAR = "home:.texlive/texmf-var", -- We have only one cache path but there can be more. The first writable one -- will be chosen but there can be more readable paths. TEXMFCACHE = "$TEXMFSYSVAR;$TEXMFVAR", TEXMFCONFIG = "home:.texlive/texmf-config", -- I don't like this texmf under home and texmf-home would make more -- sense. One never knows what installers put under texmf anywhere and -- sorting out problems will be a pain. But on the other hand ... home -- mess is normally under the users own responsibility. -- -- By using prefixes we don't get expanded paths in the cache __path__ -- entry. This makes the tex root relocatable. TEXMFOS = "selfautodir:share", TEXMFDIST = "selfautodir:share/texmf-dist", TEXMFLOCAL = texmflocal, TEXMFSYSCONFIG = "/etc/texmf", TEXMFFONTS = "selfautoparent:texmf-fonts", TEXMFPROJECT = "selfautoparent:texmf-project", TEXMFHOME = "home:texmf", -- TEXMFHOME = os.name == "macosx" and "home:Library/texmf" or "home:texmf", -- We need texmfos for a few rare files but as I have a few more bin trees -- a hack is needed. Maybe other users also have texmf-platform-new trees. TEXMF = "{$TEXMFCONFIG,$TEXMFHOME,!!$TEXMFSYSCONFIG,!!$TEXMFSYSVAR,!!$TEXMFPROJECT,!!$TEXMFFONTS,!!$TEXMFLOCAL,!!$TEXMFDIST}", TEXFONTMAPS = ".;$TEXMF/fonts/data//;$TEXMF/fonts/map/{pdftex,dvips}//", ENCFONTS = ".;$TEXMF/fonts/data//;$TEXMF/fonts/enc/{dvips,pdftex}//", VFFONTS = ".;$TEXMF/fonts/{data,vf}//", TFMFONTS = ".;$TEXMF/fonts/{data,tfm}//", T1FONTS = ".;$TEXMF/fonts/{data,type1}//;$OSFONTDIR", AFMFONTS = ".;$TEXMF/fonts/{data,afm}//;$OSFONTDIR", TTFONTS = ".;$TEXMF/fonts/{data,truetype}//;$OSFONTDIR", OPENTYPEFONTS = ".;$TEXMF/fonts/{data,opentype}//;$OSFONTDIR", CMAPFONTS = ".;$TEXMF/fonts/cmap//", FONTFEATURES = ".;$TEXMF/fonts/{data,fea}//;$OPENTYPEFONTS;$TTFONTS;$T1FONTS;$AFMFONTS", FONTCIDMAPS = ".;$TEXMF/fonts/{data,cid}//", OFMFONTS = ".;$TEXMF/fonts/{data,ofm,tfm}//", OVFFONTS = ".;$TEXMF/fonts/{data,ovf,vf}//", TEXINPUTS = ".;$TEXMF/tex/{context,plain/base,generic}//", MPINPUTS = ".;$TEXMF/metapost/{context,base,}//", -- In the next variable the inputs path will go away. TEXMFSCRIPTS = ".;$TEXMF/scripts/context/{lua,ruby,python,perl}//;$TEXINPUTS", PERLINPUTS = ".;$TEXMF/scripts/context/perl", PYTHONINPUTS = ".;$TEXMF/scripts/context/python", RUBYINPUTS = ".;$TEXMF/scripts/context/ruby", LUAINPUTS = ".;$TEXINPUTS;$TEXMF/scripts/context/lua//", CLUAINPUTS = ".;$SELFAUTOLOC/lib/{context,luatex,}/lua//", -- Not really used by MkIV so they might go away. BIBINPUTS = ".;$TEXMF/bibtex/bib//", BSTINPUTS = ".;$TEXMF/bibtex/bst//", -- Experimental ICCPROFILES = ".;$TEXMF/tex/context/colors/{icc,profiles}//;$OSCOLORDIR", -- A few special ones that will change some day. FONTCONFIG_FILE = "fonts.conf", FONTCONFIG_PATH = "$TEXMFSYSVAR/fonts/conf", }, -- We have a few reserved subtables. These control runtime behaviour. The -- keys have names like 'foo.bar' which means that you have to use keys -- like ['foo.bar'] so for convenience we also support 'foo_bar'. directives = { -- There are a few variables that determine the engines -- limits. Most will fade away when we close in on version 1. ["luatex.expanddepth"] = "10000", -- 10000 ["luatex.hashextra"] = "100000", -- 0 ["luatex.nestsize"] = "1000", -- 50 ["luatex.maxinopen"] = "500", -- 15 ["luatex.maxprintline"] = " 10000", -- 79 ["luatex.maxstrings"] = "500000", -- 15000 -- obsolete ["luatex.paramsize"] = "25000", -- 60 ["luatex.savesize"] = "50000", -- 4000 ["luatex.stacksize"] = "10000", -- 300 -- A few process related variables come next. -- ["system.checkglobals"] = "10", -- ["system.nostatistics"] = "yes", ["system.errorcontext"] = "10", ["system.compile.cleanup"] = "no", -- remove tma files ["system.compile.strip"] = "yes", -- strip tmc files -- The io modes are similar to the traditional ones. Possible values -- are all, paranoid and restricted. ["system.outputmode"] = "restricted", ["system.inputmode"] = "any", -- The following variable is under consideration. We do have protection -- mechanims but it's not enabled by default. ["system.commandmode"] = "any", -- any none list ["system.commandlist"] = "mtxrun, convert, inkscape, gs, imagemagick, curl, bibtex, pstoedit", -- The mplib library support mechanisms have their own -- configuration. Normally these variables can be left as -- they are. ["mplib.texerrors"] = "yes", -- Normally you can leave the font related directives untouched -- as they only make sense when testing. -- ["fonts.autoreload"] = "no", -- ["fonts.otf.loader.method"] = "table", -- table mixed sparse -- ["fonts.otf.loader.cleanup"] = "0", -- 0 1 2 3 -- In an edit cycle it can be handy to launch an editor. The -- preferred one can be set here. -- ["pdfview.method"] = "okular", -- default (often acrobat) xpdf okular }, experiments = { ["fonts.autorscale"] = "yes", }, trackers = { }, }, }
gpl-2.0
wounds1/zaza2
plugins/lock_fwd.lua
4
1716
--[[ # #ـــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ #:(( # For More Information ....! # Developer : Aziz < @TH3_GHOST > # our channel: @DevPointTeam # Version: 1.1 #:)) #ــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ # ]] do local function pre_process(msg) --Checking mute local hash = 'mate:'..msg.to.id if redis:get(hash) and msg.fwd_from and not is_sudo(msg) and not is_owner(msg) and not is_momod(msg) and not is_admin1(msg) then delete_msg(msg.id, ok_cb, true) send_large_msg(get_receiver(msg), 'عزيزي '..msg.from.first_name..'\nممنوع عمل اعادة توجيه من القنوات هنا التزم بقوانين المجموعة 👋👮\n#username @'..msg.from.username) return "done" end return msg end local function DevPoint(msg, matches) chat_id = msg.to.id if is_momod(msg) and matches[1] == 'قفل' then local hash = 'mate:'..msg.to.id redis:set(hash, true) return "" elseif is_momod(msg) and matches[1] == 'فتح' then local hash = 'mate:'..msg.to.id redis:del(hash) return "" end end return { patterns = { '^(قفل) اعادة توجيه$', '^(فتح) اعادة توجيه$' }, run = DevPoint, pre_process = pre_process } end
gpl-2.0
Ninjistix/darkstar
scripts/zones/Quicksand_Caves/npcs/qm6.lua
7
1569
----------------------------------- -- Area: Quicksand Caves -- NPC: ??? (qm6) -- Bastok Mission 8.1 "The Chains That Bind Us" -- !pos -469 0 620 208 ----------------------------------- package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Quicksand_Caves/TextIDs"); require("scripts/zones/Quicksand_Caves/MobIDs"); require("scripts/globals/missions"); function onTrade(player,npc,trade) end; function onTrigger(player,npc) -- THE CHAINS THAT BIND US if (player:getCurrentMission(player:getNation()) == THE_CHAINS_THAT_BIND_US and player:getVar("MissionStatus") == 1) then if (os.time() >= npc:getLocalVar("cooldown")) then if (GetMobByID(CENTURIO_IV_VII):isSpawned() or GetMobByID(TRIARIUS_IV_XIV):isSpawned() or GetMobByID(PRINCEPS_IV_XLV):isSpawned()) then player:messageSpecial(NOW_IS_NOT_THE_TIME); else player:messageSpecial(SENSE_OF_FOREBODING); SpawnMob(CENTURIO_IV_VII):updateClaim(player); SpawnMob(TRIARIUS_IV_XIV):updateClaim(player); SpawnMob(PRINCEPS_IV_XLV):updateClaim(player); end else player:startEvent(11); end -- DEFAULT DIALOG else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) -- THE CHAINS THAT BIND US if (csid == 11) then player:setVar("MissionStatus", 2); end end;
gpl-3.0
jagu-sayan/42Premake
src/base/table.lua
7
2374
-- -- table.lua -- Additions to Lua's built-in table functions. -- Copyright (c) 2002-2008 Jason Perkins and the Premake project -- -- -- Returns true if the table contains the specified value. -- function table.contains(t, value) for _,v in pairs(t) do if (v == value) then return true end end return false end -- -- Enumerates an array of objects and returns a new table containing -- only the value of one particular field. -- function table.extract(arr, fname) local result = { } for _,v in ipairs(arr) do table.insert(result, v[fname]) end return result end -- -- Flattens a hierarchy of tables into a single array containing all -- of the values. -- function table.flatten(arr) local result = { } local function flatten(arr) for _, v in ipairs(arr) do if type(v) == "table" then flatten(v) else table.insert(result, v) end end end flatten(arr) return result end -- -- Merges an array of items into a string. -- function table.implode(arr, before, after, between) local result = "" for _,v in ipairs(arr) do if (result ~= "" and between) then result = result .. between end result = result .. before .. v .. after end return result end -- -- Returns true if the table is empty, and contains no indexed or keyed values. -- function table.isempty(t) return not next(t) end -- -- Adds the values from one array to the end of another and -- returns the result. -- function table.join(...) local result = { } for _,t in ipairs(arg) do if type(t) == "table" then for _,v in ipairs(t) do table.insert(result, v) end else table.insert(result, t) end end return result end -- -- Return a list of all keys used in a table. -- function table.keys(tbl) local keys = {} for k, _ in pairs(tbl) do table.insert(keys, k) end return keys end -- -- Translates the values contained in array, using the specified -- translation table, and returns the results in a new array. -- function table.translate(arr, translation) local result = { } for _, value in ipairs(arr) do local tvalue if type(translation) == "function" then tvalue = translation(value) else tvalue = translation[value] end if (tvalue) then table.insert(result, tvalue) end end return result end
bsd-3-clause
BooM-amour/bomb
plugins/music.lua
1
2325
do -- Base search URL local BASE_URL = 'http://pleer.com/mobile/search?q=' -- Base download URL local BASE_DL_URL = 'http://pleer.com/mobile/files_mobile/' local htmlparser = require 'htmlparser' -- Provide download link local function getDownloadLink(id) return BASE_DL_URL .. id .. '.mp3' end local function getLyrics(q) local b, c = http.request(BASE_URL .. URL.escape(q)) if c ~= 200 then return "Oops! Network errors! Try again later." end local root = htmlparser.parse(b) local tracks = root('.track') local output = 'برای دانلود لینک دانلود رو به صورت \n/getmusic [URL]\n نویسید.\n' -- If no tracks found if #tracks < 1 then return 'اهنگ مورد نظر پیدا نشد :( به زودی API تغییر میکند.' end for i, track in pairs(tracks) do -- Track id local trackId = track.id -- Remove that starting 't' in the id of element trackId = trackId:sub(2) -- Parse track track = track:getcontent() track = htmlparser.parse(track) -- Track artist local artist = track:select('.artist')[1] artist = unescape_html(artist:getcontent()) -- Track title local title = track:select('.title')[1] title = unescape_html(title:getcontent()) -- Track time local time = track:select('.time')[1] time = time:getcontent() time = time:sub(-5) -- Track specs local specs = track:select('.specs')[1] specs = specs:getcontent() specs = specs:split(',') -- Size local size = specs[1]:trim() -- Bitrate local bitrate = specs[2]:trim() -- Generate an awesome, well formated output output = output .. i .. '. ' .. artist ..'\n' .. '🕚 ' .. time .. ' | ' .. ' 🎧 ' .. bitrate .. ' | ' .. ' 📎 ' .. size .. '\n' .. '💾 : ' .. getDownloadLink(trackId) .. '\n\n ' end return output end local function run(msg, matches) return getLyrics(matches[1]) end return { description = 'Search and get music from pleer', usage = '!music [track name or artist and track name]: Search and get the music', patterns = { '^music (.*)$' }, run = run } end
gpl-2.0
Ninjistix/darkstar
scripts/globals/spells/meteor.lua
4
2084
----------------------------------------- -- Spell: Meteor -- Deals non-elemental damage to an enemy. ----------------------------------------- require("scripts/globals/monstertpmoves"); require("scripts/globals/settings"); require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) -- TODO: Correct message is "Incorrect job, job level too low, or required ability not activated." Unable to locate this in our basic or system message functions. -- The client blocks the spell via menus, but it can still be cast via text commands, so we have to block it here, albiet with the wrong message. if (caster:isMob()) then return 0; elseif (caster:hasStatusEffect(EFFECT_ELEMENTAL_SEAL) == true) then return 0; else return msgBasic.STATUS_PREVENTS; end end; function onSpellCast(caster,target,spell) --calculate raw damage --Byrthnoth @ Random Facts Thread: Magic @ BG: --Spell Base Damage = MAB/MDB*floor(Int + Elemental Magic Skill/6)*3.5 --NOT AFFECTED BY DARK BONUSES (bonus ETC) --I'll just point this out again. It can't resist, there's no dINT, and the damage is non-elemental. The only terms that affect it for monsters (that we know of) are MDB and MDT. If a --normal monster would take 50k damage from your group, Botulus would take 40k damage. Every. Time. local dmg = 0; if (caster:isPC()) then dmg = ((100+caster:getMod(MOD_MATT))/(100+target:getMod(MOD_MDEF))) * (caster:getStat(MOD_INT) + caster:getSkillLevel(ELEMENTAL_MAGIC_SKILL)/6) * 3.5; else dmg = ((100+caster:getMod(MOD_MATT))/(100+target:getMod(MOD_MDEF))) * (caster:getStat(MOD_INT) + (caster:getMaxSkillLevel(caster:getMainLvl(), JOBS.BLM, ELEMENTAL_MAGIC_SKILL))/6) * 9.4; end --add in target adjustment dmg = adjustForTarget(target,dmg,spell:getElement()); --add in final adjustments dmg = finalMagicAdjustments(caster,target,spell,dmg); return dmg; end;
gpl-3.0
wangyi0226/skynet
service/wsgate.lua
1
2433
local skynet = require "skynet" local gateserver = require "snax.wsgateserver" local netpack = require "websocketnetpack" local watchdog local connection = {} -- fd -> connection : { fd , client, agent , ip, mode } local forwarding = {} -- agent -> connection skynet.register_protocol { name = "client", id = skynet.PTYPE_CLIENT, } local handler = {} function handler.open(source, conf) watchdog = conf.watchdog or source end function handler.message(fd, msg, sz) -- recv a package, forward it local c = connection[fd] if c == nil then skynet.redirect(watchdog, fd, "client", fd, msg, sz) return end local agent = c.agent if agent then skynet.redirect(agent, c.client, "client", fd, msg, sz) else --最初的 --skynet.redirect(watchdog, fd, "client", fd, msg, sz) --三国的 skynet.send(watchdog, "lua", "socket", "data", fd, netpack.tostring(msg, sz)) --云风最新的 --skynet.send(watchdog, "lua", "socket", "data", fd, skynet.tostring(msg, sz)) --skynet.tostring will copy msg to a string, so we must free msg here. --skynet.trash(msg,sz) end end function handler.connect(fd, addr) local c = { fd = fd, ip = addr, } connection[fd] = c skynet.send(watchdog, "lua", "socket", "open", fd, addr) end local function unforward(c) if c.agent then forwarding[c.agent] = nil c.agent = nil c.client = nil end end local function close_fd(fd) local c = connection[fd] if c then unforward(c) connection[fd] = nil end end function handler.disconnect(fd) close_fd(fd) skynet.send(watchdog, "lua", "socket", "close", fd) end function handler.error(fd, msg) close_fd(fd) skynet.send(watchdog, "lua", "socket", "error", fd, msg) end function handler.warning(fd, size) skynet.send(watchdog, "lua", "socket", "warning", fd, size) end local CMD = {} function CMD.forward(source, fd, client, address) local c = connection[fd] if c == nil then return false end unforward(c) if watchdog == source then return gateserver.openclient(fd) end c.client = client or 0 c.agent = address or source forwarding[c.agent] = c return gateserver.openclient(fd) end function CMD.accept(source, fd) local c = assert(connection[fd]) unforward(c) gateserver.openclient(fd) end function CMD.kick(source, fd) gateserver.closeclient(fd) end function handler.command(cmd, source, ...) local f = assert(CMD[cmd]) return f(source, ...) end gateserver.start(handler)
mit
Ninjistix/darkstar
scripts/zones/Meriphataud_Mountains/npcs/Buliame_RK.lua
3
2992
----------------------------------- -- Area: Meriphataud Mountains -- NPC: Buliame, R.K. -- Type: Border Conquest Guards -- !pos -120.393 -25.822 -592.604 119 ----------------------------------- package.loaded["scripts/zones/Meriphataud_Mountains/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Meriphataud_Mountains/TextIDs"); local guardnation = NATION_SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = ARAGONEU; local csid = 0x7ffa; function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; 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; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; 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
Ninjistix/darkstar
scripts/zones/Heavens_Tower/Zone.lua
5
2310
----------------------------------- -- -- Zone: Heavens_Tower -- ----------------------------------- package.loaded["scripts/zones/Heavens_Tower/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Heavens_Tower/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/missions"); ----------------------------------- function onInitialize(zone) zone:registerRegion(1, -1,-1,-35, 1,1,-33); zone:registerRegion(2, 6,-46,-30, 8,-44,-28); end; function onZoneIn(player,prevZone) local cs = -1; if (player:getCurrentMission(SANDORIA) == JOURNEY_TO_WINDURST and player:getVar("MissionStatus") == 3) then cs = 42; elseif (player:getCurrentMission(BASTOK) == THE_EMISSARY_WINDURST and player:getVar("MissionStatus") == 2) then cs = 42; elseif (player:getCurrentMission(WINDURST) == DOLL_OF_THE_DEAD and player:getVar("MissionStatus") == 1) then cs = 335; end return cs; end; function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; function onRegionEnter(player,region) switch (region:GetRegionID()): caseof { --------------------------------- [1] = function (x) -- Heaven's Tower exit portal player:startEvent(41); end, --------------------------------- [2] = function (x) -- Warp directly back to the first floor. player:startEvent(83); end, --------------------------------- } end; function onRegionLeave(player,region) end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 41) then player:setPos(0,-17,135,60,239); elseif (csid == 335) then player:setVar("MissionStatus",2); elseif (csid == 42) then -- This cs should only play if you visit Windurst first. if (player:getNation() == NATION_SANDORIA) then player:setVar("MissionStatus",4); else player:setVar("MissionStatus",3); end end end;
gpl-3.0
premake/premake-4.x
tests/actions/vstudio/vc2010/test_config_props.lua
52
2040
-- -- tests/actions/vstudio/vc2010/test_config_props.lua -- Validate generation of the configuration property group. -- Copyright (c) 2011-2013 Jason Perkins and the Premake project -- T.vstudio_vs2010_config_props = { } local suite = T.vstudio_vs2010_config_props local vc2010 = premake.vstudio.vc2010 local project = premake.project -- -- Setup -- local sln, prj function suite.setup() sln, prj = test.createsolution() end local function prepare(platform) premake.bake.buildconfigs() sln.vstudio_configs = premake.vstudio.buildconfigs(sln) local cfginfo = sln.vstudio_configs[1] local cfg = premake.getconfig(prj, cfginfo.src_buildcfg, cfginfo.src_platform) vc2010.configurationPropertyGroup(cfg, cfginfo) end -- -- Check the structure with the default project values. -- function suite.structureIsCorrect_onDefaultValues() prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <CharacterSet>MultiByte</CharacterSet> </PropertyGroup> ]] end -- -- Visual Studio 2012 adds a platform toolset. -- function suite.structureIsCorrect_onDefaultValues() _ACTION = "vs2012" prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <CharacterSet>MultiByte</CharacterSet> <PlatformToolset>v110</PlatformToolset> </PropertyGroup> ]] end function suite.structureIsCorrect_onDefaultValues_on2013() _ACTION = "vs2013" prepare() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <CharacterSet>MultiByte</CharacterSet> <PlatformToolset>v120</PlatformToolset> </PropertyGroup> ]] end
bsd-3-clause
garlick/flux-sched
rdl/RDL/types/Socket.lua
2
2433
--/***************************************************************************\ -- Copyright (c) 2014 Lawrence Livermore National Security, LLC. Produced at -- the Lawrence Livermore National Laboratory (cf, AUTHORS, DISCLAIMER.LLNS). -- LLNL-CODE-658032 All rights reserved. -- -- This file is part of the Flux resource manager framework. -- For details, see https://github.com/flux-framework. -- -- 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. -- -- Flux 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 terms and conditions of 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. -- See also: http://www.gnu.org/licenses/ --\***************************************************************************/ Socket = Resource:subclass ('Socket') function Socket:initialize (arg) local cpuset = require 'flux.affinity'.cpuset.new assert (tonumber(arg.id), "Required Socket arg `id' missing") assert (type(arg.cpus) == "string", "Required Socket arg `cpus' missing") Resource.initialize (self, { "socket", id = arg.id, properties = { cpus = arg.cpus }, tags = arg.tags or {} } ) -- -- Add all child cores: -- local id = 0 local cset = cpuset (arg.cpus) local num_cores = 0 for _ in cset:iterator() do num_cores = num_cores + 1 end local bw_per_core = 0 if arg.tags ~=nil and arg.tags['max_bw'] ~= nil then bw_per_core = arg.tags.max_bw / num_cores end for core in cset:iterator() do self:add_child ( Resource{ "core", id = core, properties = { localid = id }, tags = { ["max_bw"] = bw_per_core, ["alloc_bw"] = 0 }} ) id = id + 1 end if arg.memory and tonumber (arg.memory) then self:add_child ( Resource{ "memory", size = arg.memory } ) end end return Socket -- vi: ts=4 sw=4 expandtab
gpl-2.0
Ninjistix/darkstar
scripts/zones/Qufim_Island/npcs/Matica_RK.lua
3
2965
----------------------------------- -- Area: Qufim Island -- NPC: Matica, R.K. -- Type: Border Conquest Guards -- !pos 179.093 -21.575 -15.282 126 ----------------------------------- package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Qufim_Island/TextIDs"); local guardnation = NATION_SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = QUFIMISLAND; local csid = 0x7ffa; function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; 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; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; 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
Ninjistix/darkstar
scripts/globals/magic_maps.lua
35
9801
--------------------------------------------- -- -- Function that all map NPCS use. -- SE updated the map NPCs to sell maps from the normal areas, RoZ, and CoP areas (Update was in Nov 5, 2013) --------------------------------------------- require("scripts/globals/keyitems"); local Maps = {MAP_OF_THE_SAN_DORIA_AREA, MAP_OF_THE_BASTOK_AREA, MAP_OF_THE_WINDURST_AREA, MAP_OF_THE_JEUNO_AREA, MAP_OF_ORDELLES_CAVES, MAP_OF_GHELSBA, MAP_OF_DAVOI, MAP_OF_CARPENTERS_LANDING, MAP_OF_THE_ZERUHN_MINES, MAP_OF_THE_PALBOROUGH_MINES, MAP_OF_BEADEAUX, MAP_OF_GIDDEUS, MAP_OF_CASTLE_OZTROJA, MAP_OF_THE_MAZE_OF_SHAKHRAMI, MAP_OF_THE_LITELOR_REGION, MAP_OF_BIBIKI_BAY, MAP_OF_QUFIM_ISLAND, MAP_OF_THE_ELDIEME_NECROPOLIS, MAP_OF_THE_GARLAIGE_CITADEL, MAP_OF_THE_ELSHIMO_REGIONS, MAP_OF_THE_NORTHLANDS_AREA, MAP_OF_KING_RANPERRES_TOMB, MAP_OF_THE_DANGRUF_WADI, MAP_OF_THE_HORUTOTO_RUINS, MAP_OF_BOSTAUNIEUX_OUBLIETTE, MAP_OF_THE_TORAIMARAI_CANAL, MAP_OF_THE_GUSGEN_MINES, MAP_OF_THE_CRAWLERS_NEST, MAP_OF_THE_RANGUEMONT_PASS, MAP_OF_DELKFUTTS_TOWER, MAP_OF_FEIYIN, MAP_OF_CASTLE_ZVAHL, MAP_OF_THE_KUZOTZ_REGION, MAP_OF_THE_RUAUN_GARDENS, MAP_OF_NORG, MAP_OF_THE_TEMPLE_OF_UGGALEPIH, MAP_OF_THE_DEN_OF_RANCOR, MAP_OF_THE_KORROLOKA_TUNNEL, MAP_OF_THE_KUFTAL_TUNNEL, MAP_OF_THE_BOYAHDA_TREE, MAP_OF_THE_VELUGANNON_PALACE, MAP_OF_IFRITS_CAULDRON, MAP_OF_THE_QUICKSAND_CAVES, MAP_OF_THE_SEA_SERPENT_GROTTO, MAP_OF_THE_VOLLBOW_REGION, MAP_OF_THE_LABYRINTH_OF_ONZOZO, MAP_OF_THE_ULEGUERAND_RANGE, MAP_OF_THE_ATTOHWA_CHASM, MAP_OF_PSOXJA, MAP_OF_OLDTON_MOVALPOLOS, MAP_OF_NEWTON_MOVALPOLOS, MAP_OF_TAVNAZIA, MAP_OF_THE_AQUEDUCTS, MAP_OF_THE_SACRARIUM, MAP_OF_CAPE_RIVERNE, MAP_OF_ALTAIEU, MAP_OF_HUXZOI, MAP_OF_RUHMET, MAP_OF_AL_ZAHBI, MAP_OF_NASHMAU, MAP_OF_WAJAOM_WOODLANDS, MAP_OF_CAEDARVA_MIRE, MAP_OF_MOUNT_ZHAYOLM, MAP_OF_AYDEEWA_SUBTERRANE, MAP_OF_MAMOOK, MAP_OF_HALVUNG, MAP_OF_ARRAPAGO_REEF, MAP_OF_ALZADAAL_RUINS, MAP_OF_BHAFLAU_THICKETS, MAP_OF_VUNKERL_INLET, MAP_OF_GRAUBERG, MAP_OF_FORT_KARUGONARUGO}; local Uoption = { --User option selected. 1, --SanDoria Area 65537, --Bastok Area 131073, --Windurst Area 196609, --Jeuno Area 262145, --Ordelles Caves 327681, --Ghelsba 393217, --Davoi 458753, --Carpenters Landing 524289, --Zeruhn Mines 589825, --Palborough Mines 655361, --Beadeaux 720897, --Giddeus 786433, --Castle Oztroja 851969, --Maze of Shakhrami 917505, --Li'Telor Region 983041, --Bibiki Bay 1048577, --Qufim Island 1114113, --Eldieme Necropolis 1179649, --Garlaige Citadel 1245185, --Elshimo Regions 1310721, --Northlands Area 1376257, --King Ranperres Tomb 1441793, --Dangruf Wadi 1507329, --Horutoto Ruins 1572865, --Bostaunieux Oubliette 1638401, --Toraimarai Canal 1703937, --Gusgen Mines 1769473, --Crawlers Nest 1835009, --Ranguemont Pass 1900545, --Delkfutts Tower 1966081, --Feiyin 2031617, --Castle Zvahl 2097153, --Kuzotz region 2162689, --Ru'Aun Gardens 2228225, --Norg 2293761, --Temple of Uggalepih 2359297, --Den of Rancor 2424833, --Korroloka Tunnel 2490369, --Kuftal Tunnel 2555905, --Boyahda Tree 2621441, --Ve'Lugannon Palace 2686977, --Ifrit's Cauldron 2752513, --Quicksand Caves 2818049, --Sea Serpent Grotto 2883585, --Vollbow region 2949121, --Labyrinth of Onzozo 3014657, --Uleguerand Range 3080193, --Attohwa Chasm 3145729, --Pso'Xja 3211265, --Oldton Movalpolos 3276801, --Newton Movalpolos 3342337, --Tavnazia 3407873, --Aqueducts 3473409, --Sacrarium 3538945, --Cape Riverne 3604481, --Al'Taieu 3670017, --Hu'Xzoi 3735553, --Ru'Hmet 3801089, --Al Zahbi 3866625, --Nashmau 3932161, --Wajaom Woodlands 3997697, --Caedarva Mire 4063233, --Mount Zhayolm 4128769, --Aydeewa Subterrane 4194305, --Mamook 4259841, --Halvung 4325377, --Arrapago Reef 4390913, --Alzadall Ruins 4456449, --Bhaflau Thickets 4521985, --Vunkerl Inlet 4587521, --Grauberg 4653057 --Fort Karugo-Narugo }; --Groups maps by price, based off the user option. local p2 = { --Maps that are price at 200 gil Uoption[1], --SanDoria Area Uoption[2], --Bastok Area Uoption[3], --Windurst Area Uoption[9] --Zeruhn Mines }; local p6 = { --Maps that are price at 600 gil Uoption[4], --Jeuno Area Uoption[5], --Ordelles Caves Uoption[6], --Ghelsba Uoption[10], --Palborough Mines Uoption[11], --Beadeaux Uoption[12], --Giddeus Uoption[14], --Maze of Shakhrami Uoption[22], --King Ranperres Tomb Uoption[23], --Dangruf Wadi Uoption[24], --Horutoto Ruins Uoption[27], --Gusgen Mines Uoption[59] --Al Zahbi }; local p3 = { --Maps that are price at 3000 gil Uoption[7], --Davoi Uoption[8], --Carpenters Landing Uoption[13], --Castle Oztroja Uoption[15], --Li'Telor Region Uoption[16], --Bibiki Bay Uoption[17], --Qufim Island Uoption[18], --Eldieme Necropolis Uoption[19], --Garlaige Citadel Uoption[20], --Elshimo Regions Uoption[21], --Northlands Area Uoption[25], --Bostaunieux Oubliette Uoption[26], --Toraimarai Canal Uoption[28], --Crawlers Nest Uoption[29], --Ranguemont Pass Uoption[30], --Delkfutts Tower Uoption[31], --Feiyin Uoption[32], --Castle Zvahl Uoption[33], --Kuzotz region Uoption[34], --Ru'Aun Gardens Uoption[35], --Norg Uoption[36], --Temple of Uggalepih Uoption[37], --Den of Rancor Uoption[38], --Korroloka Tunnel Uoption[39], --Kuftal Tunnel Uoption[40], --Boyahda Tree Uoption[41], --Ve'Lugannon Palace Uoption[42], --Ifrit's Cauldron Uoption[43], --Quicksand Caves Uoption[44], --Sea Serpent Grotto Uoption[45], --Vollbow region Uoption[46], --Labyrinth of Onzozo Uoption[47], --Uleguerand Range Uoption[48], --Attohwa Chasm Uoption[49], --Pso'Xja Uoption[50], --Oldton Movalpolos Uoption[51], --Newton Movalpolos Uoption[52], --Tavnazia Uoption[53], --Aqueducts Uoption[54], --Sacrarium Uoption[55], --Cape Riverne Uoption[56], --Al'Taieu Uoption[57], --Hu'Xzoi Uoption[58], --Ru'Hmet Uoption[60], --Nashmau Uoption[61], --Wajaom Woodlands Uoption[62], --Caedarva Mire Uoption[63], --Mount Zhayolm Uoption[64], --Aydeewa Subterrane Uoption[65], --Mamook Uoption[66], --Halvung Uoption[67], --Arrapago Reef Uoption[68], --Alzadall Ruins Uoption[69] --Bhaflau Thickets }; local p30 = { --Maps that are price at 30,000 gil Uoption[70], --Vunkerl Inlet Uoption[71], --Grauberg Uoption[72] --Fort Karugo-Narugo }; function CheckMaps(player, npc, csid) local i = 0; local mapVar1 = 0; local mapVar2 = 0; local mapVar3 = 0; while i <= 31 do if player:hasKeyItem(Maps[i+1]) then mapVar1 = bit.bor(mapVar1, bit.lshift(1,i)); end i = i + 1; end while i <= 63 do if player:hasKeyItem(Maps[i+1]) then mapVar2 = bit.bor(mapVar2, bit.lshift(1,i)); end i = i + 1; end while i <= 71 do if player:hasKeyItem(Maps[i+1]) then mapVar3 = bit.bor(mapVar3, bit.lshift(1,i)); end i = i + 1; end player:startEvent(csid, mapVar1, mapVar2, mapVar3); end; function CheckMapsUpdate (player, option, NOT_HAVE_ENOUGH_GIL, KEYITEM_OBTAINED) local price = 0; local MadePurchase = false; local KI = 0; local i = 0; local mapVar1 = 0; local mapVar2 = 0; local mapVar3 = 0; while i <= 71 do if (option == Uoption[i+1]) then local x = 1; while x <= 53 do if (x <= 4 and option == p2[x]) then price = 200; elseif (x <= 12 and option == p6[x]) then price = 600; elseif (x <= 53 and option == p3[x]) then price = 3000; elseif (x <= 3 and option == p30[x]) then price = 30000; end x=x+1; end MadePurchase = true; KI = Maps[i+1]; end i = i + 1; end if (price > player:getGil()) then player:messageSpecial(NOT_HAVE_ENOUGH_GIL); MadePurchase = false; price = 0; elseif (price > 0 and MadePurchase == true) then player:delGil(price); MadePurchase = false; player:addKeyItem(KI); player:messageSpecial(KEYITEM_OBTAINED, KI); end i=0; while i <= 31 do if player:hasKeyItem(Maps[i+1]) then mapVar1 = bit.bor(mapVar1, bit.lshift(1,i)); end i = i + 1; end while i <= 63 do if player:hasKeyItem(Maps[i+1]) then mapVar2 = bit.bor(mapVar2, bit.lshift(1,i)); end i = i + 1; end while i <= 71 do if player:hasKeyItem(Maps[i+1]) then mapVar3 = bit.bor(mapVar3, bit.lshift(1,i)); end i = i + 1; end player:updateEvent(mapVar1, mapVar2, mapVar3); end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/items/ragnarok.lua
3
2848
----------------------------------------- -- ID: 18282, 18283, 18640, 18654, 18668, 19749, 19842, 20745, 20746, 21683 -- Item: Ragnarok ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/msg"); require("scripts/globals/weaponskills"); require("scripts/globals/weaponskillids"); ----------------------------------- local NAME_WEAPONSKILL = "AFTERMATH_RAGNAROK"; local NAME_EFFECT_LOSE = "AFTERMATH_LOST_RAGNAROK"; -- https://www.bg-wiki.com/bg/Relic_Aftermath local aftermathTable = {}; -- Ragnarok 75 aftermathTable[18282] = { power=1, duration = function(tp) return math.floor(0.02 * tp); end, mods = { { id=MOD_CRITHITRATE, power=5 } } }; aftermathTable[18283] = aftermathTable[18282]; -- Ragnarok (80) aftermathTable[18640] = aftermathTable[18282]; -- Ragnarok (85) aftermathTable[18654] = aftermathTable[18282]; -- Ragnarok (90) aftermathTable[18668] = aftermathTable[18282]; -- Ragnarok (95) aftermathTable[19749] = aftermathTable[18282]; -- Ragnarok (99) aftermathTable[19842] = aftermathTable[18282]; -- Ragnarok (99/II) aftermathTable[20745] = aftermathTable[18282]; -- Ragnarok (119) aftermathTable[20746] = aftermathTable[18282]; -- Ragnarok (119/II) -- Ragnarok (119/III) aftermathTable[21683] = { power=2, duration = function(tp) return math.floor(0.06 * tp); end, mods = { { id=MOD_CRITHITRATE, power=10 }, { id=MOD_ACC, power=15 } } }; function onWeaponskill(user, target, wsid, tp, action) if (wsid == WEAPONSKILL_SCOURGE) then -- Scourge onry local itemId = user:getEquipID(SLOT_MAIN); if (aftermathTable[itemId]) then -- Apply the effect and add mods addAftermathEffect(user, tp, aftermathTable[itemId]); -- Add a listener for when aftermath wears (to remove mods) user:addListener("EFFECT_LOSE", NAME_EFFECT_LOSE, aftermathLost); end end end function aftermathLost(target, effect) if (effect:getType() == EFFECT_AFTERMATH) then local itemId = target:getEquipID(SLOT_MAIN); if (aftermathTable[itemId]) then -- Remove mods removeAftermathEffect(target, aftermathTable[itemId]); -- Remove the effect listener target:removeListener(NAME_EFFECT_LOSE); end end end function onItemCheck(player, param, caster) if (param == ITEMCHECK_EQUIP) then player:addListener("WEAPONSKILL_USE", NAME_WEAPONSKILL, onWeaponskill); elseif (param == ITEMCHECK_UNEQUIP) then -- Make sure we clean up the effect and mods if (player:hasStatusEffect(EFFECT_AFTERMATH)) then aftermathLost(player, player:getStatusEffect(EFFECT_AFTERMATH)); end player:removeListener(NAME_WEAPONSKILL); end return 0; end
gpl-3.0
jinks/LuaMeat
plugin/seen.lua
1
1331
DB:exec([[CREATE TABLE IF NOT EXISTS seen ( nick VARCHAR(100) PRIMARY KEY, channel VARCHAR(100) NOT NULL, action VARCHAR(20) NOT NULL, time INTEGER NOT NULL)]]) local function update (channel, from, action) local stmt = DB:prepare("INSERT OR REPLACE INTO seen VALUES (?, ?, ?, ?)") stmt:bind_values(from, channel, action, os.time()) stmt:step() stmt:finalize() end on_join.seen = function(target, from) update(target, from, "joining") end on_part.seen = function (target, from, msg) update(target, from, "leaving") end callback.seen = function (target, from, msg) update(target, from, "talking") end plugin.seen = function (target, from, arg) if not arg or arg == "" then irc.say(target, "Give me a name plz!") return end local stmt = DB:prepare("SELECT * FROM seen WHERE NICK = ?") stmt:bind_values(arg:lower()) local status = stmt:step() local result = nil if status == sqlite3.ROW then result = stmt:get_named_values() end stmt:finalize() if status and result then local c = " " if result.action == "talking" then c = " in " end irc.say(target, result.nick.." was last seen "..result.action..c..result.channel.." "..elapsed(os.date("!%Y-%m-%dT%H:%M:%SZ",result.time)).." ago.") else irc.say(target, "I cannot find anything about "..arg) end end
apache-2.0
nimaghorbani/dozdi7
plugins/slap.lua
17
4304
local command = 'slap [target]' local doc = [[``` /slap [target] Slap somebody. ```]] local triggers = { '^/slap[@'..bot.username..']*' } local slaps = { '$victim was shot by $victor.', '$victim was pricked to death.', '$victim walked into a cactus while trying to escape $victor.', '$victim drowned.', '$victim drowned whilst trying to escape $victor.', '$victim blew up.', '$victim was blown up by $victor.', '$victim hit the ground too hard.', '$victim fell from a high place.', '$victim fell off a ladder.', '$victim fell into a patch of cacti.', '$victim was doomed to fall by $victor.', '$victim was blown from a high place by $victor.', '$victim was squashed by a falling anvil.', '$victim went up in flames.', '$victim burned to death.', '$victim was burnt to a crisp whilst fighting $victor.', '$victim walked into a fire whilst fighting $victor.', '$victim tried to swim in lava.', '$victim tried to swim in lava while trying to escape $victor.', '$victim was struck by lightning.', '$victim was slain by $victor.', '$victim got finished off by $victor.', '$victim was killed by magic.', '$victim was killed by $victor using magic.', '$victim starved to death.', '$victim suffocated in a wall.', '$victim fell out of the world.', '$victim was knocked into the void by $victor.', '$victim withered away.', '$victim was pummeled by $victor.', '$victim was fragged by $victor.', '$victim was desynchronized.', '$victim was wasted.', '$victim was busted.', '$victim\'s bones are scraped clean by the desolate wind.', '$victim has died of dysentery.', '$victim fainted.', '$victim is out of usable Pokemon! $victim whited out!', '$victim is out of usable Pokemon! $victim blacked out!', '$victim whited out!', '$victim blacked out!', '$victim says goodbye to this cruel world.', '$victim got rekt.', '$victim was sawn in half by $victor.', '$victim died. I blame $victor.', '$victim was axe-murdered by $victor.', '$victim\'s melon was split by $victor.', '$victim was slice and diced by $victor.', '$victim was split from crotch to sternum by $victor.', '$victim\'s death put another notch in $victor\'s axe.', '$victim died impossibly!', '$victim died from $victor\'s mysterious tropical disease.', '$victim escaped infection by dying.', '$victim played hot-potato with a grenade.', '$victim was knifed by $victor.', '$victim fell on his sword.', '$victim ate a grenade.', '$victim practiced being $victor\'s clay pigeon.', '$victim is what\'s for dinner!', '$victim was terminated by $victor.', '$victim was shot before being thrown out of a plane.', '$victim was not invincible.', '$victim has encountered an error.', '$victim died and reincarnated as a goat.', '$victor threw $victim off a building.', '$victim is sleeping with the fishes.', '$victim got a premature burial.', '$victor replaced all of $victim\'s music with Nickelback.', '$victor spammed $victim\'s email.', '$victor made $victim a knuckle sandwich.', '$victor slapped $victim with pure nothing.', '$victor hit $victim with a small, interstellar spaceship.', '$victim was quickscoped by $victor.', '$victor put $victim in check-mate.', '$victor RSA-encrypted $victim and deleted the private key.', '$victor put $victim in the friendzone.', '$victor slaps $victim with a DMCA takedown request!', '$victim became a corpse blanket for $victor.', 'Death is when the monsters get you. Death comes for $victim.', 'Cowards die many times before their death. $victim never tasted death but once.' } local action = function(msg) local nicks = load_data('nicknames.json') local victim = msg.text:input() if msg.reply_to_message then if nicks[tostring(msg.reply_to_message.from.id)] then victim = nicks[tostring(msg.reply_to_message.from.id)] else victim = msg.reply_to_message.from.first_name end end local victor = msg.from.first_name if nicks[msg.from.id_str] then victor = nicks[msg.from.id_str] end if not victim then victim = victor victor = bot.first_name end local message = slaps[math.random(#slaps)] message = message:gsub('$victim', victim) message = message:gsub('$victor', victor) sendMessage(msg.chat.id, message) end return { action = action, triggers = triggers, doc = doc, command = command }
gpl-2.0
Ninjistix/darkstar
scripts/zones/Metalworks/npcs/Grohm.lua
5
2645
----------------------------------- -- Area: Metalworks -- NPC: Grohm -- Involved In Mission: Journey Abroad -- !pos -18 -11 -27 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) if (player:getCurrentMission(SANDORIA) == JOURNEY_TO_BASTOK) then if (player:getVar("notReceivePickaxe") == 1) then player:startEvent(425); elseif (player:getVar("MissionStatus") == 4) then player:startEvent(423); elseif (player:getVar("MissionStatus") == 5 and player:hasItem(599) == false) then player:startEvent(424); else player:startEvent(422); end elseif (player:getCurrentMission(SANDORIA) == JOURNEY_TO_BASTOK2) then if (player:getVar("MissionStatus") == 9) then player:startEvent(426); else player:startEvent(427); end elseif (player:getCurrentMission(WINDURST) == THE_THREE_KINGDOMS_BASTOK) then if (player:getVar("notReceivePickaxe") == 1) then player:startEvent(425,1); elseif (player:getVar("MissionStatus") == 4) then player:startEvent(423,1); elseif (player:getVar("MissionStatus") == 5 and player:hasItem(599) == false) then player:startEvent(424,1); else player:startEvent(422); end elseif (player:getCurrentMission(WINDURST) == THE_THREE_KINGDOMS_BASTOK2) then if (player:getVar("MissionStatus") == 9) then player:startEvent(426,1); else player:startEvent(427,1); end else player:startEvent(427);--422 end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 423 or csid == 425) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,605); -- Pickaxes player:setVar("notReceivePickaxe",1); else player:addItem(605,5); player:messageSpecial(ITEM_OBTAINED,605); -- Pickaxes player:setVar("MissionStatus",5); player:setVar("notReceivePickaxe",0); end elseif (csid == 426) then player:setVar("MissionStatus",10); end end;
gpl-3.0
blackman1380/antispam
libs/dateparser.lua
502
6212
local difftime, time, date = os.difftime, os.time, os.date local format = string.format local tremove, tinsert = table.remove, table.insert local pcall, pairs, ipairs, tostring, tonumber, type, setmetatable = pcall, pairs, ipairs, tostring, tonumber, type, setmetatable local dateparser={} --we shall use the host OS's time conversion facilities. Dealing with all those leap seconds by hand can be such a bore. local unix_timestamp do local now = time() local local_UTC_offset_sec = difftime(time(date("!*t", now)), time(date("*t", now))) unix_timestamp = function(t, offset_sec) local success, improper_time = pcall(time, t) if not success or not improper_time then return nil, "invalid date. os.time says: " .. (improper_time or "nothing") end return improper_time - local_UTC_offset_sec - offset_sec end end local formats = {} -- format names local format_func = setmetatable({}, {__mode='v'}) --format functions ---register a date format parsing function function dateparser.register_format(format_name, format_function) if type(format_name)~="string" or type(format_function)~='function' then return nil, "improper arguments, can't register format handler" end local found for i, f in ipairs(format_func) do --for ordering if f==format_function then found=true break end end if not found then tinsert(format_func, format_function) end formats[format_name] = format_function return true end ---register a date format parsing function function dateparser.unregister_format(format_name) if type(format_name)~="string" then return nil, "format name must be a string" end formats[format_name]=nil end ---return the function responsible for handling format_name date strings function dateparser.get_format_function(format_name) return formats[format_name] or nil, ("format %s not registered"):format(format_name) end ---try to parse date string --@param str date string --@param date_format optional date format name, if known --@return unix timestamp if str can be parsed; nil, error otherwise. function dateparser.parse(str, date_format) local success, res, err if date_format then if not formats[date_format] then return 'unknown date format: ' .. tostring(date_format) end success, res = pcall(formats[date_format], str) else for i, func in ipairs(format_func) do success, res = pcall(func, str) if success and res then return res end end end return success and res end dateparser.register_format('W3CDTF', function(rest) local year, day_of_year, month, day, week local hour, minute, second, second_fraction, offset_hours local alt_rest year, rest = rest:match("^(%d%d%d%d)%-?(.*)$") day_of_year, alt_rest = rest:match("^(%d%d%d)%-?(.*)$") if day_of_year then rest=alt_rest end month, rest = rest:match("^(%d%d)%-?(.*)$") day, rest = rest:match("^(%d%d)(.*)$") if #rest>0 then rest = rest:match("^T(.*)$") hour, rest = rest:match("^([0-2][0-9]):?(.*)$") minute, rest = rest:match("^([0-6][0-9]):?(.*)$") second, rest = rest:match("^([0-6][0-9])(.*)$") second_fraction, alt_rest = rest:match("^%.(%d+)(.*)$") if second_fraction then rest=alt_rest end if rest=="Z" then rest="" offset_hours=0 else local sign, offset_h, offset_m sign, offset_h, rest = rest:match("^([+-])(%d%d)%:?(.*)$") local offset_m, alt_rest = rest:match("^(%d%d)(.*)$") if offset_m then rest=alt_rest end offset_hours = tonumber(sign .. offset_h) + (tonumber(offset_m) or 0)/60 end if #rest>0 then return nil end end year = tonumber(year) local d = { year = year and (year > 100 and year or (year < 50 and (year + 2000) or (year + 1900))), month = tonumber(month) or 1, day = tonumber(day) or 1, hour = tonumber(hour) or 0, min = tonumber(minute) or 0, sec = tonumber(second) or 0, isdst = false } local t = unix_timestamp(d, (offset_hours or 0) * 3600) if second_fraction then return t + tonumber("0."..second_fraction) else return t end end) do local tz_table = { --taken from http://www.timeanddate.com/library/abbreviations/timezones/ A = 1, B = 2, C = 3, D = 4, E=5, F = 6, G = 7, H = 8, I = 9, K = 10, L = 11, M = 12, N = -1, O = -2, P = -3, Q = -4, R = -5, S = -6, T = -7, U = -8, V = -9, W = -10, X = -11, Y = -12, Z = 0, EST = -5, EDT = -4, CST = -6, CDT = -5, MST = -7, MDT = -6, PST = -8, PDT = -7, GMT = 0, UT = 0, UTC = 0 } local month_val = {Jan=1, Feb=2, Mar=3, Apr=4, May=5, Jun=6, Jul=7, Aug=8, Sep=9, Oct=10, Nov=11, Dec=12} dateparser.register_format('RFC2822', function(rest) local year, month, day, day_of_year, week_of_year, weekday local hour, minute, second, second_fraction, offset_hours local alt_rest weekday, alt_rest = rest:match("^(%w%w%w),%s+(.*)$") if weekday then rest=alt_rest end day, rest=rest:match("^(%d%d?)%s+(.*)$") month, rest=rest:match("^(%w%w%w)%s+(.*)$") month = month_val[month] year, rest = rest:match("^(%d%d%d?%d?)%s+(.*)$") hour, rest = rest:match("^(%d%d?):(.*)$") minute, rest = rest:match("^(%d%d?)(.*)$") second, alt_rest = rest:match("^:(%d%d)(.*)$") if second then rest = alt_rest end local tz, offset_sign, offset_h, offset_m tz, alt_rest = rest:match("^%s+(%u+)(.*)$") if tz then rest = alt_rest offset_hours = tz_table[tz] else offset_sign, offset_h, offset_m, rest = rest:match("^%s+([+-])(%d%d)(%d%d)%s*(.*)$") offset_hours = tonumber(offset_sign .. offset_h) + (tonumber(offset_m) or 0)/60 end if #rest>0 or not (year and day and month and hour and minute) then return nil end year = tonumber(year) local d = { year = year and ((year > 100) and year or (year < 50 and (year + 2000) or (year + 1900))), month = month, day = tonumber(day), hour= tonumber(hour) or 0, min = tonumber(minute) or 0, sec = tonumber(second) or 0, isdst = false } return unix_timestamp(d, offset_hours * 3600) end) end dateparser.register_format('RFC822', formats.RFC2822) --2822 supercedes 822, but is not a strict superset. For our intents and purposes though, it's perfectly good enough dateparser.register_format('RFC3339', formats.W3CDTF) --RFC3339 is a subset of W3CDTF return dateparser
gpl-2.0
amirb8/telepersian
libs/dateparser.lua
502
6212
local difftime, time, date = os.difftime, os.time, os.date local format = string.format local tremove, tinsert = table.remove, table.insert local pcall, pairs, ipairs, tostring, tonumber, type, setmetatable = pcall, pairs, ipairs, tostring, tonumber, type, setmetatable local dateparser={} --we shall use the host OS's time conversion facilities. Dealing with all those leap seconds by hand can be such a bore. local unix_timestamp do local now = time() local local_UTC_offset_sec = difftime(time(date("!*t", now)), time(date("*t", now))) unix_timestamp = function(t, offset_sec) local success, improper_time = pcall(time, t) if not success or not improper_time then return nil, "invalid date. os.time says: " .. (improper_time or "nothing") end return improper_time - local_UTC_offset_sec - offset_sec end end local formats = {} -- format names local format_func = setmetatable({}, {__mode='v'}) --format functions ---register a date format parsing function function dateparser.register_format(format_name, format_function) if type(format_name)~="string" or type(format_function)~='function' then return nil, "improper arguments, can't register format handler" end local found for i, f in ipairs(format_func) do --for ordering if f==format_function then found=true break end end if not found then tinsert(format_func, format_function) end formats[format_name] = format_function return true end ---register a date format parsing function function dateparser.unregister_format(format_name) if type(format_name)~="string" then return nil, "format name must be a string" end formats[format_name]=nil end ---return the function responsible for handling format_name date strings function dateparser.get_format_function(format_name) return formats[format_name] or nil, ("format %s not registered"):format(format_name) end ---try to parse date string --@param str date string --@param date_format optional date format name, if known --@return unix timestamp if str can be parsed; nil, error otherwise. function dateparser.parse(str, date_format) local success, res, err if date_format then if not formats[date_format] then return 'unknown date format: ' .. tostring(date_format) end success, res = pcall(formats[date_format], str) else for i, func in ipairs(format_func) do success, res = pcall(func, str) if success and res then return res end end end return success and res end dateparser.register_format('W3CDTF', function(rest) local year, day_of_year, month, day, week local hour, minute, second, second_fraction, offset_hours local alt_rest year, rest = rest:match("^(%d%d%d%d)%-?(.*)$") day_of_year, alt_rest = rest:match("^(%d%d%d)%-?(.*)$") if day_of_year then rest=alt_rest end month, rest = rest:match("^(%d%d)%-?(.*)$") day, rest = rest:match("^(%d%d)(.*)$") if #rest>0 then rest = rest:match("^T(.*)$") hour, rest = rest:match("^([0-2][0-9]):?(.*)$") minute, rest = rest:match("^([0-6][0-9]):?(.*)$") second, rest = rest:match("^([0-6][0-9])(.*)$") second_fraction, alt_rest = rest:match("^%.(%d+)(.*)$") if second_fraction then rest=alt_rest end if rest=="Z" then rest="" offset_hours=0 else local sign, offset_h, offset_m sign, offset_h, rest = rest:match("^([+-])(%d%d)%:?(.*)$") local offset_m, alt_rest = rest:match("^(%d%d)(.*)$") if offset_m then rest=alt_rest end offset_hours = tonumber(sign .. offset_h) + (tonumber(offset_m) or 0)/60 end if #rest>0 then return nil end end year = tonumber(year) local d = { year = year and (year > 100 and year or (year < 50 and (year + 2000) or (year + 1900))), month = tonumber(month) or 1, day = tonumber(day) or 1, hour = tonumber(hour) or 0, min = tonumber(minute) or 0, sec = tonumber(second) or 0, isdst = false } local t = unix_timestamp(d, (offset_hours or 0) * 3600) if second_fraction then return t + tonumber("0."..second_fraction) else return t end end) do local tz_table = { --taken from http://www.timeanddate.com/library/abbreviations/timezones/ A = 1, B = 2, C = 3, D = 4, E=5, F = 6, G = 7, H = 8, I = 9, K = 10, L = 11, M = 12, N = -1, O = -2, P = -3, Q = -4, R = -5, S = -6, T = -7, U = -8, V = -9, W = -10, X = -11, Y = -12, Z = 0, EST = -5, EDT = -4, CST = -6, CDT = -5, MST = -7, MDT = -6, PST = -8, PDT = -7, GMT = 0, UT = 0, UTC = 0 } local month_val = {Jan=1, Feb=2, Mar=3, Apr=4, May=5, Jun=6, Jul=7, Aug=8, Sep=9, Oct=10, Nov=11, Dec=12} dateparser.register_format('RFC2822', function(rest) local year, month, day, day_of_year, week_of_year, weekday local hour, minute, second, second_fraction, offset_hours local alt_rest weekday, alt_rest = rest:match("^(%w%w%w),%s+(.*)$") if weekday then rest=alt_rest end day, rest=rest:match("^(%d%d?)%s+(.*)$") month, rest=rest:match("^(%w%w%w)%s+(.*)$") month = month_val[month] year, rest = rest:match("^(%d%d%d?%d?)%s+(.*)$") hour, rest = rest:match("^(%d%d?):(.*)$") minute, rest = rest:match("^(%d%d?)(.*)$") second, alt_rest = rest:match("^:(%d%d)(.*)$") if second then rest = alt_rest end local tz, offset_sign, offset_h, offset_m tz, alt_rest = rest:match("^%s+(%u+)(.*)$") if tz then rest = alt_rest offset_hours = tz_table[tz] else offset_sign, offset_h, offset_m, rest = rest:match("^%s+([+-])(%d%d)(%d%d)%s*(.*)$") offset_hours = tonumber(offset_sign .. offset_h) + (tonumber(offset_m) or 0)/60 end if #rest>0 or not (year and day and month and hour and minute) then return nil end year = tonumber(year) local d = { year = year and ((year > 100) and year or (year < 50 and (year + 2000) or (year + 1900))), month = month, day = tonumber(day), hour= tonumber(hour) or 0, min = tonumber(minute) or 0, sec = tonumber(second) or 0, isdst = false } return unix_timestamp(d, offset_hours * 3600) end) end dateparser.register_format('RFC822', formats.RFC2822) --2822 supercedes 822, but is not a strict superset. For our intents and purposes though, it's perfectly good enough dateparser.register_format('RFC3339', formats.W3CDTF) --RFC3339 is a subset of W3CDTF return dateparser
gpl-2.0
ehrenbrav/FCEUX_Learning_Environment
output/luaScripts/SMB-AreaScrambler.lua
9
2561
--SMB area scrambler --Randomly changes the level contents. Doesn't garuantee a winnable level (nor does it guarantee it won't crash the game) --Written by XKeeper require("x_functions"); if not x_requires then -- Sanity check. If they require a newer version, let them know. timer = 1; while (true) do timer = timer + 1; for i = 0, 32 do gui.drawbox( 6, 28 + i, 250, 92 - i, "#000000"); end; gui.text( 10, 32, string.format("This Lua script requires the x_functions library.")); gui.text( 53, 42, string.format("It appears you do not have it.")); gui.text( 39, 58, "Please get the x_functions library at"); gui.text( 14, 69, "http://xkeeper.shacknet.nu/"); gui.text(114, 78, "emu/nes/lua/x_functions.lua"); warningboxcolor = string.format("%02X", math.floor(math.abs(30 - math.fmod(timer, 60)) / 30 * 0xFF)); gui.drawbox(7, 29, 249, 91, "#ff" .. warningboxcolor .. warningboxcolor); FCEU.frameadvance(); end; else x_requires(4); end; function areascrambler() end; function gameloop() joyin = joypad.read(1); if joyin['select'] then memory.writebyte(0x00e7, math.random(0, 0xFF)); memory.writebyte(0x00e8, math.random(0, 0xFF)); memory.writebyte(0x00e9, math.random(0, 0xFF)); memory.writebyte(0x00ea, math.random(0, 0xFF)); memory.writebyte(0x0750, math.random(0, 0xFF)); end; if joyin['up'] then memory.writebyte(0x009F, -5); memory.writebyte(0x07F8, 3); memory.writebyte(0x0722, 0xFF) end; screenpage = memory.readbyte(0x071a); screenxpos = memory.readbyte(0x071c); arealow = memory.readbyte(0x00e7); areahigh = memory.readbyte(0x00e8); enemylow = memory.readbyte(0x00e9); enemyhigh = memory.readbyte(0x00ea); unknown = memory.readbyte(0x0750); text( 6, 30, string.format("Position: %02X %02X", screenpage, screenxpos)); text( 19, 38, string.format("Area: %02X %02X", areahigh, arealow)); text( 13, 46, string.format("Enemy: %02X %02X", enemyhigh, enemylow)); text( 13, 54, string.format("?: %02X", unknown)); end; function areascramble() memory.writebyte(0x00e7, math.random(0, 0xFF)); memory.writebyte(0x00e8, math.random(0, 0xFF)); end; function enemyscramble() memory.writebyte(0x00e9, math.random(0, 0xFF)); memory.writebyte(0x00ea, math.random(0, 0xFF)); end; gui.register(gameloop); memory.register(0x00e8, areascramble); memory.register(0x00ea, enemyscramble); while (true) do memory.writebyte(0x079F, 2); FCEU.frameadvance(); end;
gpl-2.0
Ninjistix/darkstar
scripts/zones/Metalworks/npcs/Wise_Owl.lua
3
1550
----------------------------------- -- Area: Metalworks -- NPC: Wise Owl -- Type: Smithing Adv. Image Support -- !pos -106.336 2.000 26.117 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local guildMember = isGuildMember(player,8); local SkillLevel = player:getSkillLevel(SKILL_SMITHING); local Cost = getAdvImageSupportCost(player,SKILL_SMITHING); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_SMITHING_IMAGERY) == false) then player:startEvent(103,Cost,SkillLevel,0,207,player:getGil(),0,4095,0); else player:startEvent(103,Cost,SkillLevel,0,207,player:getGil(),28721,4095,0); end else player:startEvent(103); -- Standard Dialogue end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local Cost = getAdvImageSupportCost(player,SKILL_SMITHING); if (csid == 103 and option == 1) then player:delGil(Cost); player:messageSpecial(SMITHING_SUPPORT,0,2,0); player:addStatusEffect(EFFECT_SMITHING_IMAGERY,3,0,480); end end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Mount_Zhayolm/npcs/Waudeen.lua
5
2407
----------------------------------- -- Area: Mount_Zhayolm -- NPC: Waudeen -- Type: Assault -- !pos 673.882 -23.995 367.604 61 ----------------------------------- package.loaded["scripts/zones/Mount_Zhayolm/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/quests"); require("scripts/zones/Mount_Zhayolm/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local toauMission = player:getCurrentMission(TOAU); local beginnings = player:getQuestStatus(AHT_URHGAN,BEGINNINGS); -- IMMORTAL SENTRIES if (toauMission == IMMORTAL_SENTRIES) then if (player:hasKeyItem(SUPPLIES_PACKAGE)) then player:startEvent(4); elseif (player:getVar("AhtUrganStatus") == 1) then player:startEvent(5); end; -- BEGINNINGS elseif (beginnings == QUEST_ACCEPTED) then if (not player:hasKeyItem(BRAND_OF_THE_FLAMESERPENT)) then player:startEvent(10); -- brands you else player:startEvent(11); -- the way is neither smooth nor easy end; -- ASSAULT elseif (toauMission >= PRESIDENT_SALAHEEM) then local IPpoint = player:getCurrency("imperial_standing"); if (player:hasKeyItem(LEBROS_ASSAULT_ORDERS) and player:hasKeyItem(ASSAULT_ARMBAND) == false) then player:startEvent(209,50,IPpoint); else player:startEvent(6); -- player:delKeyItem(ASSAULT_ARMBAND); end; -- DEFAULT DIALOG else player:startEvent(3); end; end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) -- IMMORTAL SENTRIES if (csid == 4 and option == 1) then player:delKeyItem(SUPPLIES_PACKAGE); player:setVar("AhtUrganStatus",1); -- BEGINNINGS elseif (csid == 10) then player:addKeyItem(BRAND_OF_THE_FLAMESERPENT); player:messageSpecial(KEYITEM_OBTAINED,BRAND_OF_THE_FLAMESERPENT); -- ASSAULT elseif (csid == 209 and option == 1) then player:delCurrency("imperial_standing", 50); player:addKeyItem(ASSAULT_ARMBAND); player:messageSpecial(KEYITEM_OBTAINED,ASSAULT_ARMBAND); end; end;
gpl-3.0
premake/premake-4.x
tests/tools/test_gcc.lua
12
1818
-- -- tests/test_gcc.lua -- Automated test suite for the GCC toolset interface. -- Copyright (c) 2009-2011 Jason Perkins and the Premake project -- T.gcc = { } local suite = T.gcc local cfg function suite.setup() cfg = { } cfg.basedir = "." cfg.location = "." cfg.language = "C++" cfg.project = { name = "MyProject" } cfg.flags = { } cfg.objectsdir = "obj" cfg.platform = "Native" cfg.links = { } cfg.libdirs = { } cfg.linktarget = { fullpath="libMyProject.a" } end -- -- CPPFLAGS tests -- function suite.cppflags_OnWindows() cfg.system = "windows" local r = premake.gcc.getcppflags(cfg) test.isequal("-MMD -MP", table.concat(r, " ")) end function suite.cppflags_OnHaiku() cfg.system = "haiku" local r = premake.gcc.getcppflags(cfg) test.isequal("-MMD", table.concat(r, " ")) end -- -- CFLAGS tests -- function suite.cflags_SharedLib_Windows() cfg.kind = "SharedLib" cfg.system = "windows" local r = premake.gcc.getcflags(cfg) test.isequal('', table.concat(r,"|")) end function suite.cflags_OnFpFast() cfg.flags = { "FloatFast" } local r = premake.gcc.getcflags(cfg) test.isequal('-ffast-math', table.concat(r,"|")) end function suite.cflags_OnFpStrict() cfg.flags = { "FloatStrict" } local r = premake.gcc.getcflags(cfg) test.isequal('-ffloat-store', table.concat(r,"|")) end -- -- LDFLAGS tests -- function suite.ldflags_SharedLib_Windows() cfg.kind = "SharedLib" cfg.system = "windows" local r = premake.gcc.getldflags(cfg) test.isequal('-s|-shared|-Wl,--out-implib="libMyProject.a"', table.concat(r,"|")) end function suite.linkflags_OnFrameworks() cfg.links = { "Cocoa.framework" } local r = premake.gcc.getlinkflags(cfg) test.isequal('-framework Cocoa', table.concat(r,"|")) end
bsd-3-clause
Ninjistix/darkstar
scripts/zones/Port_Jeuno/npcs/Kochahy-Muwachahy.lua
5
1866
----------------------------------- -- Area: Port Jeuno -- NPC: Kochahy-Muwachahy -- !pos 40 0 6 246 ------------------------------------- package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/conquest"); require("scripts/zones/Port_Jeuno/TextIDs"); local guardnation = OTHER; -- SANDORIA, BASTOK, WINDURST, OTHER(Jeuno). local guardtype = 1; -- 1: city, 2: foreign, 3: outpost, 4: border function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; function onTrigger(player,npc) local Menu1 = getArg1(guardnation,player); local Menu3 = conquestRanking(); local Menu6 = getArg6(player); local Menu7 = player:getCP(); player:startEvent(32763,Menu1,0,Menu3,0,0,Menu6,Menu7,0); end; function onEventUpdate(player,csid,option) -- printf("onUpdateCSID: %u",csid); -- printf("onUpdateOPTION: %u",option); local inventory, size; if (player:getNation() == 0) then inventory = SandInv; size = #SandInv; elseif (player:getNation() == 1) then inventory = BastInv; size = #BastInv; else inventory = WindInv; size = #WindInv; end updateConquestGuard(player,csid,option,size,inventory); end; function onEventFinish(player,csid,option) -- printf("onFinishCSID: %u",csid); -- printf("onFinishOPTION: %u",option); local inventory, size; if (player:getNation() == 0) then inventory = SandInv; size = #SandInv; elseif (player:getNation() == 1) then inventory = BastInv; size = #BastInv; else inventory = WindInv; size = #WindInv; end finishConquestGuard(player,csid,option,size,inventory,guardnation); end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/mobskills/foxfire.lua
25
1186
--------------------------------------------- -- Foxfire -- -- Description: Damage varies with TP. Additional effect: "Stun." -- Type: Physical (Blunt) -- RDM, THF, PLD, BST, BRD, RNG, NIN, and COR fomors). -- --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) local job = mob:getMainJob(); if (job == JOBS.RDM or job == JOBS.THF or job == JOBS.PLD or job == JOBS.BST or job == JOBS.RNG or job == JOBS.BRD or job == JOBS.NIN or job == JOBS.COR) then return 0; end return 1; end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = 2.6; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,1,2,3); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded); local typeEffect = EFFECT_STUN; MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 6); target:delHP(dmg); return dmg; end;
gpl-3.0
Ninjistix/darkstar
scripts/commands/addmission.lua
10
1563
--------------------------------------------------------------------------------------------------- -- func: addmission <logID> <missionID> <player> -- desc: Adds a mission to the GM or target players log. --------------------------------------------------------------------------------------------------- require("scripts/globals/missions"); cmdprops = { permission = 1, parameters = "sss" }; function error(player, msg) player:PrintToPlayer(msg); player:PrintToPlayer("!addmission <logID> <missionID> {player}"); end; function onTrigger(player, logId, missionId, target) -- validate logId local logName; local logInfo = GetMissionLogInfo(logId); if (logInfo == nil) then error(player, "Invalid logID."); return; end logName = logInfo.full_name; logId = logInfo.mission_log; -- validate missionId if (missionId ~= nil) then missionId = tonumber(missionId) or _G[string.upper(missionId)]; end if (missionId == nil or missionId < 0) then error(player, "Invalid missionID."); return; end -- validate target local targ; if (target == nil) then targ = player; else targ = GetPlayerByName(target); if (targ == nil) then error(player, string.format("Player named '%s' not found!", target)); return; end end -- add mission targ:addMission(logId, missionId); player:PrintToPlayer(string.format("Added %s mission %i to %s.", logName, missionId, targ:getName())); end;
gpl-3.0
dinodeck/ninety_nine_days_of_dev
005_bitmap_text/map/map_world.lua
8
14367
function CreateWorldMap(state) local id = "world" local worldState = state.maps[id] local encountersWorld = { -- 1. yellow / plains { { oddment = 100, item = {} }, { oddment = 3, item = { background = "combat_bg_field.png", enemy = { "goblin_field", "goblin_field", "goblin_field", } } } }, -- 2.pink - pass { { oddment = 100, item = {} }, { oddment = 10, item = { background = "combat_bg_field.png", enemy = { "goblin_forest", "goblin_forest", "goblin_forest", } } } }, -- 3. blue / forest pass { { oddment = 100, item = {} }, { oddment = 3, item = { background = "combat_bg_field.png", enemy = { "goblin_field", "goblin_forest", "goblin_field", } } }, { oddment = 20, item = { background = "combat_bg_forest.png", enemy = { "goblin_forest", "goblin_field", "goblin_forest", } } } } } return { id = id, name = "World", can_save = true, version = "1.1", luaversion = "5.1", orientation = "orthogonal", width = 30, height = 30, tilewidth = 16, tileheight = 16, properties = {}, encounters = encountersWorld, on_wake = { }, actions = { to_town = { id = "ChangeMap", params = { "town", 1, 106 } }, to_cave = { id = "ChangeMap", params = { "cave", 12, 110 } }, }, trigger_types = { enter_town = { OnEnter = "to_town"}, enter_cave = { OnEnter = "to_cave"}, }, triggers = { { trigger = "enter_town", x = 7, y = 26 }, { trigger = "enter_cave", x = 23, y = 3 }, }, tilesets = { { name = "world_tileset", firstgid = 1, tilewidth = 16, tileheight = 16, spacing = 0, margin = 0, image = "world_tileset.png", imagewidth = 128, imageheight = 128, properties = {}, tiles = {} }, { name = "collision_graphic", firstgid = 65, tilewidth = 16, tileheight = 16, spacing = 0, margin = 0, image = "collision_graphic.png", imagewidth = 32, imageheight = 32, properties = {}, tiles = {} }, { name = "encounter_palette", firstgid = 69, tilewidth = 16, tileheight = 16, spacing = 0, margin = 0, image = "../../quests-9-solution/encounter_palette.png", imagewidth = 128, imageheight = 128, properties = {}, tiles = {} } }, layers = { { type = "tilelayer", name = "0-background", x = 0, y = 0, width = 30, height = 30, visible = true, opacity = 1, properties = {}, encoding = "lua", data = { 55, 55, 56, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 55, 56, 63, 63, 64, 55, 56, 55, 56, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 55, 56, 63, 64, 55, 56, 58, 63, 64, 63, 64, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 63, 64, 55, 56, 63, 64, 55, 56, 55, 56, 58, 58, 58, 58, 58, 58, 58, 58, 58, 58, 53, 58, 58, 58, 58, 58, 58, 47, 53, 58, 58, 58, 63, 64, 58, 58, 63, 55, 56, 64, 58, 58, 58, 58, 58, 58, 58, 58, 58, 54, 24, 52, 58, 58, 54, 52, 54, 8, 24, 52, 53, 58, 58, 58, 55, 56, 58, 63, 64, 58, 58, 58, 58, 53, 53, 53, 53, 53, 54, 25, 26, 27, 52, 54, 25, 34, 26, 26, 26, 26, 27, 52, 58, 58, 63, 64, 55, 56, 58, 58, 58, 58, 54, 24, 24, 24, 24, 25, 26, 34, 34, 34, 26, 26, 34, 34, 34, 34, 34, 34, 34, 27, 57, 58, 58, 58, 63, 64, 58, 58, 58, 59, 24, 24, 24, 24, 24, 33, 34, 34, 42, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 35, 57, 58, 58, 58, 58, 58, 58, 58, 58, 59, 24, 10, 20, 9, 24, 41, 42, 43, 24, 41, 34, 34, 43, 41, 34, 34, 34, 34, 34, 43, 58, 58, 58, 58, 58, 58, 58, 58, 58, 59, 24, 22, 19, 21, 24, 24, 24, 24, 24, 24, 41, 43, 24, 24, 41, 42, 42, 42, 43, 24, 52, 58, 58, 58, 58, 58, 58, 58, 58, 59, 24, 2, 23, 1, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 16, 24, 24, 24, 24, 24, 57, 58, 58, 58, 58, 58, 58, 58, 54, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 52, 58, 58, 58, 58, 58, 58, 59, 25, 26, 26, 26, 26, 27, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 49, 58, 58, 58, 58, 58, 58, 59, 33, 34, 34, 34, 34, 34, 26, 27, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 49, 58, 58, 58, 58, 58, 58, 58, 54, 34, 34, 34, 34, 34, 34, 34, 34, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 52, 58, 58, 58, 58, 58, 58, 54, 25, 34, 34, 34, 34, 34, 34, 34, 43, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 57, 58, 58, 58, 58, 59, 25, 34, 34, 34, 34, 34, 34, 34, 34, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 57, 58, 58, 58, 58, 59, 41, 42, 42, 42, 42, 42, 42, 42, 43, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 57, 58, 58, 58, 58, 58, 51, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 57, 58, 58, 58, 58, 58, 59, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 26, 26, 26, 27, 25, 26, 26, 26, 27, 24, 24, 24, 24, 57, 58, 58, 58, 58, 58, 59, 24, 24, 24, 24, 24, 24, 24, 24, 24, 33, 34, 34, 34, 34, 34, 34, 34, 34, 35, 24, 24, 24, 24, 52, 58, 58, 58, 58, 58, 59, 24, 24, 24, 24, 24, 24, 24, 24, 24, 33, 34, 34, 34, 34, 34, 34, 42, 42, 43, 24, 24, 24, 24, 10, 58, 58, 58, 58, 58, 59, 24, 24, 24, 24, 24, 24, 24, 24, 24, 33, 34, 34, 34, 34, 34, 34, 27, 24, 24, 24, 24, 24, 24, 22, 58, 58, 58, 58, 58, 54, 24, 24, 24, 24, 24, 24, 24, 24, 24, 33, 34, 34, 34, 34, 34, 34, 35, 24, 24, 24, 24, 24, 10, 4, 58, 58, 58, 58, 58, 51, 24, 24, 24, 10, 20, 9, 24, 24, 24, 41, 34, 34, 34, 34, 34, 34, 35, 24, 24, 24, 24, 10, 4, 19, 58, 55, 56, 58, 58, 59, 24, 24, 24, 22, 19, 21, 24, 24, 24, 24, 41, 42, 42, 43, 41, 42, 43, 24, 24, 24, 24, 22, 19, 19, 58, 63, 64, 58, 58, 59, 24, 48, 10, 4, 19, 21, 24, 24, 10, 20, 20, 20, 20, 20, 9, 24, 24, 24, 24, 24, 10, 4, 19, 19, 55, 56, 58, 58, 58, 58, 51, 24, 2, 23, 6, 3, 20, 20, 4, 19, 19, 19, 19, 19, 3, 20, 20, 20, 20, 20, 4, 19, 19, 19, 63, 55, 56, 58, 58, 58, 54, 10, 20, 20, 4, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 58, 63, 64, 58, 58, 54, 10, 4, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19 } }, { type = "tilelayer", name = "1-detail", x = 0, y = 0, width = 30, height = 30, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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 = "tilelayer", name = "2-collision", x = 0, y = 0, width = 30, height = 30, visible = true, opacity = 0.36, 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, 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, 0, 0, 0, 0, 0, 0, 0, 65, 65, 65, 65, 65, 65, 65, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 65, 65, 65, 65, 65, 65, 65, 65, 0, 65, 65, 65, 65, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 65, 0, 0, 0, 0, 0, 65, 68, 0, 65, 65, 65, 65, 65, 65, 0, 0, 65, 65, 65, 65, 65, 0, 0, 0, 0, 0, 0, 0, 0, 65, 65, 65, 65, 65, 65, 65, 0, 68, 0, 65, 65, 68, 0, 68, 0, 68, 0, 68, 65, 65, 65, 0, 0, 0, 0, 0, 0, 0, 65, 65, 66, 0, 66, 0, 68, 0, 68, 0, 68, 0, 68, 0, 68, 0, 0, 0, 68, 0, 68, 65, 65, 0, 0, 0, 0, 0, 0, 0, 65, 66, 0, 66, 0, 66, 0, 68, 0, 68, 0, 68, 0, 68, 0, 68, 0, 68, 0, 68, 0, 65, 65, 0, 0, 0, 0, 0, 0, 0, 65, 0, 66, 0, 66, 0, 68, 0, 68, 0, 68, 0, 68, 0, 68, 0, 0, 0, 68, 0, 68, 65, 65, 0, 0, 0, 0, 0, 0, 65, 65, 66, 0, 65, 0, 66, 0, 66, 0, 66, 0, 68, 0, 66, 0, 68, 0, 68, 68, 68, 66, 65, 65, 0, 0, 0, 0, 0, 0, 65, 65, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 0, 0, 66, 0, 66, 0, 65, 0, 0, 0, 0, 0, 0, 65, 65, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 65, 0, 0, 0, 0, 0, 0, 65, 68, 0, 68, 0, 68, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 65, 0, 0, 0, 0, 0, 0, 65, 0, 68, 0, 68, 0, 68, 0, 68, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 65, 65, 0, 0, 0, 0, 0, 65, 65, 68, 0, 68, 0, 68, 0, 68, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 65, 65, 0, 0, 0, 0, 65, 65, 68, 0, 68, 0, 68, 0, 68, 0, 68, 0, 67, 0, 67, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 65, 0, 0, 0, 0, 65, 68, 0, 68, 0, 68, 0, 68, 0, 68, 0, 67, 0, 67, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 65, 0, 0, 0, 0, 65, 0, 68, 0, 68, 0, 68, 0, 68, 0, 67, 0, 67, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 65, 0, 0, 0, 0, 65, 65, 0, 66, 0, 66, 0, 67, 0, 67, 0, 67, 0, 67, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 65, 0, 0, 0, 0, 0, 65, 66, 0, 66, 0, 66, 0, 66, 0, 67, 0, 68, 0, 68, 0, 68, 0, 68, 0, 68, 0, 66, 0, 66, 65, 0, 0, 0, 0, 0, 65, 0, 66, 0, 66, 0, 66, 0, 66, 0, 68, 0, 68, 0, 68, 0, 68, 0, 68, 0, 66, 0, 66, 0, 65, 0, 0, 0, 0, 0, 65, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 68, 0, 68, 0, 68, 0, 68, 0, 68, 0, 66, 0, 66, 65, 0, 0, 0, 0, 0, 65, 0, 66, 0, 66, 0, 66, 0, 66, 0, 68, 0, 68, 0, 68, 0, 68, 0, 66, 0, 66, 0, 66, 0, 65, 0, 0, 0, 0, 0, 65, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 68, 0, 68, 0, 68, 0, 68, 0, 66, 0, 66, 0, 66, 65, 0, 0, 0, 0, 0, 65, 0, 66, 0, 66, 0, 66, 0, 66, 0, 68, 0, 68, 0, 68, 0, 68, 0, 66, 0, 66, 0, 66, 65, 65, 0, 0, 0, 0, 0, 65, 66, 0, 66, 0, 65, 0, 66, 0, 66, 0, 68, 0, 68, 0, 68, 0, 68, 0, 66, 0, 66, 65, 65, 65, 0, 0, 0, 0, 0, 65, 0, 0, 0, 65, 65, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 66, 0, 65, 65, 65, 0, 0, 0, 0, 0, 65, 65, 0, 66, 0, 65, 65, 66, 0, 65, 65, 65, 65, 65, 65, 65, 0, 66, 0, 66, 0, 65, 65, 65, 65, 0, 0, 0, 0, 0, 65, 65, 66, 0, 66, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 0, 0, 0, 0, 65, 65, 66, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65 } } } } end
mit
dafei2015/hugular_cstolua
Client/tools/netProtocal/parseMsgEntity.lua
8
1380
require("helperFunction") io.output("../../Assets/Lua/net/netMsgHelper.lua") function genParseFunction(startLine) local structName = string.match(startLine, "(%S+)=") local nextLine = getNextValidLine() print("NetMsgHelper model name" , structName) local funStr = "" local parStr="" local sp="" while(not isEndStruct(nextLine)) do local valueName, valueType = string.match(nextLine, "(%S+)%s+(%S+)") -- local valueName, valueType ,z= string.match(nextLine, "(%S+)%s+(%S+)")--"(%S+)%s+(%S+)") local ueserType=string.match(valueType,"(%S%S_)") --print("userType="..ueserType) if ueserType ~= nil then parStr=parStr..sp..valueType funStr=funStr.."\tt[\""..valueName.."\"]="..valueType.."\n" else parStr=parStr..sp..valueName funStr=funStr.."\tt[\""..valueName.."\"]="..valueName.."\n" end sp="," nextLine = getNextValidLine() end io.write("function NetMsgHelper:make",structName, "(".. parStr..") \n") io.write("\tlocal t = {}\n") io.write(funStr) io.write("\treturn t\n") io.write("end\n\n") end io.input("protocal/protocal.txt") io.write("NetMsgHelper={}\n") local nextLine = getNextValidLine() while(nextLine ~= nil) do genParseFunction(nextLine) nextLine = getNextValidLine() end
mit
dinodeck/ninety_nine_days_of_dev
003_combat_numbers/code/PlanStrollState.lua
10
1628
PlanStrollState = { mName = "plan_stroll" } PlanStrollState.__index = PlanStrollState function PlanStrollState:Create(character, map) local this = { mCharacter = character, mMap = map, mEntity = character.mEntity, mController = character.mController, mFrameResetSpeed = 0.05, mFrameCount = 0, mCountDown = math.random(0, 3) } setmetatable(this, self) return this end function PlanStrollState:Enter() end function PlanStrollState:Exit() end function PlanStrollState:Update(dt) self.mCountDown = self.mCountDown - dt if self.mCountDown <= 0 then -- Choose a random direction and try to move that way. local choice = math.random(4) if choice == 1 then self.mController:Change("move", {x = -1, y = 0}) elseif choice == 2 then self.mController:Change("move", {x = 1, y = 0}) elseif choice == 3 then self.mController:Change("move", {x = 0, y = -1}) elseif choice == 4 then self.mController:Change("move", {x = 0, y = 1}) end end -- If we're in the wait state for a few frames, reset the frame to -- the starting frame. if self.mFrameCount ~= -1 then self.mFrameCount = self.mFrameCount + dt if self.mFrameCount >= self.mFrameResetSpeed then self.mFrameCount = -1 self.mEntity:SetFrame(self.mEntity.mStartFrame) self.mCharacter.mFacing = "down" end end end function PlanStrollState:Render(renderer) end
mit
dinodeck/ninety_nine_days_of_dev
007_map_cure/code/PlanStrollState.lua
10
1628
PlanStrollState = { mName = "plan_stroll" } PlanStrollState.__index = PlanStrollState function PlanStrollState:Create(character, map) local this = { mCharacter = character, mMap = map, mEntity = character.mEntity, mController = character.mController, mFrameResetSpeed = 0.05, mFrameCount = 0, mCountDown = math.random(0, 3) } setmetatable(this, self) return this end function PlanStrollState:Enter() end function PlanStrollState:Exit() end function PlanStrollState:Update(dt) self.mCountDown = self.mCountDown - dt if self.mCountDown <= 0 then -- Choose a random direction and try to move that way. local choice = math.random(4) if choice == 1 then self.mController:Change("move", {x = -1, y = 0}) elseif choice == 2 then self.mController:Change("move", {x = 1, y = 0}) elseif choice == 3 then self.mController:Change("move", {x = 0, y = -1}) elseif choice == 4 then self.mController:Change("move", {x = 0, y = 1}) end end -- If we're in the wait state for a few frames, reset the frame to -- the starting frame. if self.mFrameCount ~= -1 then self.mFrameCount = self.mFrameCount + dt if self.mFrameCount >= self.mFrameResetSpeed then self.mFrameCount = -1 self.mEntity:SetFrame(self.mEntity.mStartFrame) self.mCharacter.mFacing = "down" end end end function PlanStrollState:Render(renderer) end
mit
Ninjistix/darkstar
scripts/globals/items/dish_of_spaghetti_boscaiola.lua
3
1547
----------------------------------------- -- ID: 5192 -- Item: dish_of_spaghetti_boscaiola -- Food Effect: 30Min, All Races ----------------------------------------- -- Health % 18 -- Health Cap 120 -- Magic 35 -- Strength -5 -- Dexterity -2 -- Vitality 2 -- Mind 4 -- Store TP +6 -- Magic Regen While Healing 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- 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; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5192); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 18); target:addMod(MOD_FOOD_HP_CAP, 120); target:addMod(MOD_MP, 35); target:addMod(MOD_STR, -5); target:addMod(MOD_DEX, -2); target:addMod(MOD_VIT, 2); target:addMod(MOD_MND, 4); target:addMod(MOD_STORETP, 6); target:addMod(MOD_MPHEAL, 1); end; function onEffectLose(target, effect) target:delMod(MOD_FOOD_HPP, 18); target:delMod(MOD_FOOD_HP_CAP, 120); target:delMod(MOD_MP, 35); target:delMod(MOD_STR, -5); target:delMod(MOD_DEX, -2); target:delMod(MOD_VIT, 2); target:delMod(MOD_MND, 4); target:delMod(MOD_STORETP, 6); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Northern_San_dOria/npcs/Coullene.lua
5
1355
----------------------------------- -- Area: Northern San d'Oria -- NPC: Coullene -- Type: Involved in Quest (Flyers for Regine) -- @zone 231 -- !pos 146.420 0.000 127.601 -- ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getVar("tradeCoulene") == 0) then player:messageSpecial(COULLENE_DIALOG); player:setVar("FFR",player:getVar("FFR") - 1); player:setVar("tradeCoulene",1); player:messageSpecial(FLYER_ACCEPTED); player:tradeComplete(); elseif (player:getVar("tradeCoulene") ==1) then player:messageSpecial(FLYER_ALREADY); end end end; function onTrigger(player,npc) player:showText(npc,COULLENE_DIALOG); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Hall_of_the_Gods/Zone.lua
5
1337
----------------------------------- -- -- Zone: Hall_of_the_Gods (251) -- ----------------------------------- package.loaded["scripts/zones/Hall_of_the_Gods/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Hall_of_the_Gods/TextIDs"); ----------------------------------- function onInitialize(zone) end; function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(-0.011,-1.848,-176.133,192); elseif (player:getCurrentMission(ACP) == REMEMBER_ME_IN_YOUR_DREAMS and prevZone == 122) then cs = 5; end return cs; end; function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; function onRegionEnter(player,region) end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 5) then player:completeMission(ACP,REMEMBER_ME_IN_YOUR_DREAMS); player:addMission(ACP,BORN_OF_HER_NIGHTMARES); end end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/npc_util.lua
3
14265
--[[ Helper functions for common NPC tasks. npcUtil.pickNewPosition(npc, positionTable, allowCurrentPosition) npcUtil.giveItem(player, items) npcUtil.giveKeyItem(player, keyitems) npcUtil.completeQuest(player, area, quest, params) npcUtil.tradeHas(trade, items) npcUtil.genTmask(player,title) npcUtil.UpdateNPCSpawnPoint(id, minTime, maxTime, posTable, serverVar) npcUtil.fishingAnimation(npc, phaseDuration, func) --]] package.loaded["scripts/globals/settings"] = nil; require("scripts/globals/settings"); npcUtil = {}; -- Picks a new position for an NPC and excluding the current position. -- INPUT: npc = npcID, position = 2D table with coords: index, {x, y, z} -- RETURN: table index function npcUtil.pickNewPosition(npc, positionTable, allowCurrentPosition) local npc = GetNPCByID(npc); local positionIndex = 1; -- Default to position one in the table if it can't be found. local tableSize = 0; local newPosition = 0; allowCurrentPosition = allowCurrentPosition or false; for i, v in ipairs(positionTable) do -- Looking for the current position if not allowCurrentPosition then -- Finding by comparing the NPC's coords if (math.floor(v[1]) == math.floor(npc:getXPos()) and math.floor(v[2]) == math.floor(npc:getYPos()) and math.floor(v[3]) == math.floor(npc:getZPos())) then positionIndex = i; -- Found where the NPC is! end end tableSize = tableSize + 1; -- Counting the array size end if not allowCurrentPosition then -- Pick a new pos that isn't the current repeat newPosition = math.random(1, tableSize); until (newPosition ~= positionIndex) else newPosition = math.random(1, tableSize); end return {["x"] = positionTable[newPosition][1], ["y"] = positionTable[newPosition][2], ["z"] = positionTable[newPosition][3]}; end; --[[ ******************************************************************************* Give item(s) to player. If player has inventory space, give items, display message, and return true. If not, do not give items, display a message to indicate this, and return false. Examples of valid items parameter: 640 -- copper ore x1 { 640, 641 } -- copper ore x1, tin ore x1 { {640,2} } -- copper ore x2 { {640,2}, 641 } -- copper ore x2, tin ore x1 ******************************************************************************* --]] function npcUtil.giveItem(player, items) -- require zone TextIDs local TextIDs = "scripts/zones/" .. player:getZoneName() .. "/TextIDs"; package.loaded[TextIDs] = nil; require(TextIDs); -- create table of items, with key/val of itemId/itemQty local givenItems = {}; local itemId; local itemQty; if (type(items) == "number") then table.insert(givenItems, {items,1}); elseif (type(items) == "table") then for _, v in pairs(items) do if (type(v) == "number") then table.insert(givenItems, {v,1}); elseif (type(v) == "table" and #v == 2 and type(v[1]) == "number" and type(v[2]) == "number") then table.insert(givenItems, {v[1],v[2]}); else print(string.format("ERROR: invalid items parameter given to npcUtil.giveItem in zone %s.", player:getZoneName())); return false; end end end -- does player have enough inventory space? if (player:getFreeSlotsCount() < #givenItems) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, givenItems[1][1]); return false; end -- give items to player for _, v in pairs(givenItems) do player:addItem(v[1], v[2]); player:messageSpecial(ITEM_OBTAINED, v[1]); end return true; end --[[ ******************************************************************************* Give key item(s) to player. Message is displayed showing key items obtained. Examples of valid keyitems parameter: ZERUHN_REPORT {PALBOROUGH_MINES_LOGS} {BLUE_ACIDITY_TESTER, RED_ACIDITY_TESTER} ******************************************************************************* --]] function npcUtil.giveKeyItem(player, keyitems) -- require zone TextIDs local TextIDs = "scripts/zones/" .. player:getZoneName() .. "/TextIDs"; package.loaded[TextIDs] = nil; require(TextIDs); -- create table of keyitems local givenKeyItems = {}; if (type(keyitems) == "number") then givenKeyItems = {keyitems}; elseif (type(keyitems) == "table") then givenKeyItems = keyitems; else print(string.format("ERROR: invalid keyitems parameter given to npcUtil.giveKeyItem in zone %s.", player:getZoneName())); return false; end -- give key items to player, with message for _, v in pairs(givenKeyItems) do player:addKeyItem(v); player:messageSpecial(KEYITEM_OBTAINED,v); end return true; end --[[ ******************************************************************************* Complete a quest. If quest rewards items, and the player cannot carry them, return false. Otherwise, return true. Example of usage with params (all params are optional): npcUtil.completeQuest(player, SANDORIA, ROSEL_THE_ARMORER, { item = { {640,2}, 641 }, -- see npcUtil.giveItem for formats keyItem = ZERUHN_REPORT, -- see npcUtil.giveKeyItem for formats fame = 120, -- fame defaults to 30 if not set bayld = 500, gil = 200, xp = 1000, title = ENTRANCE_DENIED, }); ******************************************************************************* --]] function npcUtil.completeQuest(player, area, quest, params) params = params or {}; -- load text ids local TextIDs = "scripts/zones/" .. player:getZoneName() .. "/TextIDs"; package.loaded[TextIDs] = nil; require(TextIDs); -- item(s) plus message. return false if player lacks inventory space. if (params["item"] ~= nil) then if (not npcUtil.giveItem(player, params["item"])) then return false; end end -- key item(s), fame, gil, bayld, xp, and title if (params["keyItem"] ~= nil) then npcUtil.giveKeyItem(player, params["keyItem"]); end if (params["fame"] == nil) then params["fame"] = 30; end if (area["fame_area"] ~= nil and type(params["fame"]) == "number") then player:addFame(area, params["fame"]); end if (params["gil"] ~= nil and type(params["gil"]) == "number") then player:addGil(params["gil"] * GIL_RATE); player:messageSpecial(GIL_OBTAINED, params["gil"] * GIL_RATE); end if (params["bayld"] ~= nil and type(params["bayld"]) == "number") then player:addCurrency('bayld', params["bayld"] * BAYLD_RATE); player:messageSpecial(BAYLD_OBTAINED, params["bayld"] * BAYLD_RATE); end if (params["xp"] ~= nil and type(params["xp"]) == "number") then player:addExp(params["xp"] * EXP_RATE); end if (params["title"] ~= nil) then player:addTitle(params["title"]); end -- successfully complete the quest player:completeQuest(area,quest); return true end --[[ ******************************************************************************* check whether trade has all required items if yes, confirm all the items and return true if no, return false valid examples of items: 640 -- copper ore x1 { 640, 641 } -- copper ore x1, tin ore x1 { 640, 640 } -- copper ore x2 { {640,2} } -- copper ore x2 { {640,2}, 641 } -- copper ore x2, tin ore x1 { 640, {"gil", 200} } -- copper ore x1, gil x200 ******************************************************************************* --]] function npcUtil.tradeHas(trade, items, exact) if (type(exact) ~= "boolean") then exact = false; end -- create table of traded items, with key/val of itemId/itemQty local tradedItems = {}; local itemId; local itemQty; for i = 0, trade:getSlotCount()-1 do itemId = trade:getItemId(i); itemQty = trade:getItemQty(itemId); tradedItems[itemId] = itemQty; end -- create table of needed items, with key/val of itemId/itemQty local neededItems = {}; if (type(items) == "number") then neededItems[items] = 1; elseif (type(items) == "table") then local itemId; local itemQty; for _, v in pairs(items) do if (type(v) == "number") then itemId = v; itemQty = 1; elseif (type(v) == "table" and #v == 2 and type(v[1]) == "number" and type(v[2]) == "number") then itemId = v[1]; itemQty = v[2]; elseif (type(v) == "table" and #v == 2 and type(v[1]) == "string" and type(v[2]) == "number" and string.lower(v[1]) == "gil") then itemId = 65535; itemQty = v[2]; else print("ERROR: invalid value contained within items parameter given to npcUtil.tradeHas."); itemId = nil; end if (itemId ~= nil) then neededItems[itemId] = (neededItems[itemId] == nil) and itemQty or neededItems[itemId] + itemQty; end end else print("ERROR: invalid items parameter given to npcUtil.tradeHas."); return false; end -- determine whether all needed items have been traded. return false if not. for k, v in pairs(neededItems) do local tradedQty = (tradedItems[k] == nil) and 0 or tradedItems[k]; if (v > tradedQty) then return false; else tradedItems[k] = tradedQty - v; end end -- if an exact trade was requested, check if any excess items were traded. if so, return false. if (exact) then for k, v in pairs(tradedItems) do if (v > 0) then return false; end end end -- confirm items for k, v in pairs(neededItems) do trade:confirmItem(k,v) end return true; end --[[ ******************************************************************************* check whether trade has exactly required items if yes, confirm all the items and return true if no, return false valid examples of items: 640 -- copper ore x1 { 640, 641 } -- copper ore x1, tin ore x1 { 640, 640 } -- copper ore x2 { {640,2} } -- copper ore x2 { {640,2}, 641 } -- copper ore x2, tin ore x1 { 640, {"gil", 200} } -- copper ore x1, gil x200 ******************************************************************************* --]] function npcUtil.tradeHasExactly(trade, items) return npcUtil.tradeHas(trade, items, true); end function npcUtil.genTmask(player,title) local val1 = 0 for i = 1, #title do if (title[i] == 0 or player:hasTitle(title[i]) ~= true) then val1 = bit.bor(val1, bit.lshift(1, i)) end end return val1 end ----------------------------------- -- UpdateNPCSpawnPoint ---------------------------------- function npcUtil.UpdateNPCSpawnPoint(id, minTime, maxTime, posTable, serverVar) local npc = GetNPCByID(id); local respawnTime = math.random(minTime, maxTime); local newPosition = npcUtil.pickNewPosition(npc:getID(), posTable, true); serverVar = serverVar or nil; -- serverVar is optional if serverVar then if (GetServerVariable(serverVar) <= os.time(t)) then npc:hideNPC(1); -- hide so the NPC is not "moving" through the zone npc:setPos(newPosition.x, newPosition.y, newPosition.z); end end npc:timer(respawnTime * 1000, function(npc) npcUtil.UpdateNPCSpawnPoint(id, minTime, maxTime, posTable, serverVar); end) end; function npcUtil.fishingAnimation(npc, phaseDuration, func) func = func or function(npc) -- return true to not loop again return false end if func(npc) then return end npc:timer(phaseDuration * 1000, function(npc) local anims = { [ANIMATION_FISHING_NPC] = { duration = 5, nextAnim = { ANIMATION_FISHING_START } }, [ANIMATION_FISHING_START] = { duration = 10, nextAnim = { ANIMATION_FISHING_FISH } }, [ANIMATION_FISHING_FISH] = { duration = 10, nextAnim = { ANIMATION_FISHING_CAUGHT, ANIMATION_FISHING_ROD_BREAK, ANIMATION_FISHING_LINE_BREAK, } }, [ANIMATION_FISHING_ROD_BREAK] = { duration = 3, nextAnim = { ANIMATION_FISHING_NPC } }, [ANIMATION_FISHING_LINE_BREAK] = { duration = 3, nextAnim = { ANIMATION_FISHING_NPC } }, [ANIMATION_FISHING_CAUGHT] = { duration = 5, nextAnim = { ANIMATION_FISHING_NPC } }, [ANIMATION_FISHING_STOP] = { duration = 3, nextAnim = { ANIMATION_FISHING_NPC } }, } local anim = anims[npc:getAnimation()] local nextAnimationId = ANIMATION_FISHING_NPC local nextAnimationDuration = 10 local nextAnim = nil if anim then nextAnim = anim.nextAnim[math.random(1, #anim.nextAnim)] end if nextAnim then nextAnimationId = nextAnim if anims[nextAnimationId] then nextAnimationDuration = anims[nextAnimationId].duration end end npc:setAnimation(nextAnimationId) npcUtil.fishingAnimation(npc, nextAnimationDuration, func) end) end
gpl-3.0
scan-bot/scan-bot
plugins/isX.lua
605
2031
local https = require "ssl.https" local ltn12 = require "ltn12" local function request(imageUrl) -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local api_key = mashape.api_key if api_key:isempty() then return nil, 'Configure your Mashape API Key' end local api = "https://sphirelabs-advanced-porn-nudity-and-adult-content-detection.p.mashape.com/v1/get/index.php?" local parameters = "&url="..(URL.escape(imageUrl) or "") local url = api..parameters local respbody = {} local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "Accept: application/json" } print(url) local body, code, headers, status = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return "", code end local body = table.concat(respbody) return body, code end local function parseData(data) local jsonBody = json:decode(data) local response = "" print(data) if jsonBody["Error Occured"] ~= nil then response = response .. jsonBody["Error Occured"] elseif jsonBody["Is Porn"] == nil or jsonBody["Reason"] == nil then response = response .. "I don't know if that has adult content or not." else if jsonBody["Is Porn"] == "True" then response = response .. "Beware!\n" end response = response .. jsonBody["Reason"] end return jsonBody["Is Porn"], response end local function run(msg, matches) local data, code = request(matches[1]) if code ~= 200 then return "There was an error. "..code end local isPorn, result = parseData(data) return result end return { description = "Does this photo contain adult content?", usage = { "!isx [url]", "!isporn [url]" }, patterns = { "^!is[x|X] (.*)$", "^!is[p|P]orn (.*)$" }, run = run }
gpl-2.0
mohammad25253/persianguard12
plugins/isX.lua
605
2031
local https = require "ssl.https" local ltn12 = require "ltn12" local function request(imageUrl) -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local api_key = mashape.api_key if api_key:isempty() then return nil, 'Configure your Mashape API Key' end local api = "https://sphirelabs-advanced-porn-nudity-and-adult-content-detection.p.mashape.com/v1/get/index.php?" local parameters = "&url="..(URL.escape(imageUrl) or "") local url = api..parameters local respbody = {} local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "Accept: application/json" } print(url) local body, code, headers, status = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return "", code end local body = table.concat(respbody) return body, code end local function parseData(data) local jsonBody = json:decode(data) local response = "" print(data) if jsonBody["Error Occured"] ~= nil then response = response .. jsonBody["Error Occured"] elseif jsonBody["Is Porn"] == nil or jsonBody["Reason"] == nil then response = response .. "I don't know if that has adult content or not." else if jsonBody["Is Porn"] == "True" then response = response .. "Beware!\n" end response = response .. jsonBody["Reason"] end return jsonBody["Is Porn"], response end local function run(msg, matches) local data, code = request(matches[1]) if code ~= 200 then return "There was an error. "..code end local isPorn, result = parseData(data) return result end return { description = "Does this photo contain adult content?", usage = { "!isx [url]", "!isporn [url]" }, patterns = { "^!is[x|X] (.*)$", "^!is[p|P]orn (.*)$" }, run = run }
gpl-2.0
Ninjistix/darkstar
scripts/zones/Windurst_Waters/npcs/Jourille.lua
5
1249
----------------------------------- -- Area: Windurst Waters -- NPC: Jourille -- Only sells when Windurst controlls Ronfaure Region -- Confirmed shop stock, August 2013 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Windurst_Waters/TextIDs"); require("scripts/globals/conquest"); require("scripts/globals/shop"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local RegionOwner = GetRegionOwner(RONFAURE); if (RegionOwner ~= NATION_WINDURST) then player:showText(npc,JOURILLE_CLOSED_DIALOG); else player:showText(npc,JOURILLE_OPEN_DIALOG); local stock = { 639, 110, -- Chestnut 4389, 29, -- San d'Orian Carrot 610, 55, -- San d'Orian Flour 4431, 69, -- San d'Orian Grape } showShop(player,WINDURST,stock); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
PetarTilevRusev/EndlessWar
game/scripts/vscripts/gamemode.lua
1
10987
-- This is the primary barebones gamemode script and should be used to assist in initializing your game mode -- Set this to true if you want to see a complete debug output of all events/processes done by barebones -- You can also change the cvar 'barebones_spew' at any time to 1 or 0 for output/no output BAREBONES_DEBUG_SPEW = false if GameMode == nil then DebugPrint( '[BAREBONES] creating barebones game mode' ) _G.GameMode = class({}) end -- This library allow for easily delayed/timed actions require('libraries/timers') -- This library can be used for advancted physics/motion/collision of units. See PhysicsReadme.txt for more information. require('libraries/physics') -- This library can be used for advanced 3D projectile systems. require('libraries/projectiles') -- This library can be used for sending panorama notifications to the UIs of players/teams/everyone require('libraries/notifications') -- This library can be used for starting customized animations on units from lua require('libraries/animations') -- These internal libraries set up barebones's events and processes. Feel free to inspect them/change them if you need to. require('internal/gamemode') require('internal/events') -- settings.lua is where you can specify many different properties for your game mode and is one of the core barebones files. require('settings') -- events.lua is where you can specify the actions to be taken when any event occurs and is one of the core barebones files. require('events') require('base_spawner') require('spawner') -- Start the AI systems to control the guards behavior require('unitAI/human_guards_ai') require('unitAI/undead_guards_ai') require('units/human/human_upgrades') --[[ This function should be used to set up Async precache calls at the beginning of the gameplay. In this function, place all of your PrecacheItemByNameAsync and PrecacheUnitByNameAsync. These calls will be made after all players have loaded in, but before they have selected their heroes. PrecacheItemByNameAsync can also be used to precache dynamically-added datadriven abilities instead of items. PrecacheUnitByNameAsync will precache the precache{} block statement of the unit and all precache{} block statements for every Ability# defined on the unit. This function should only be called once. If you want to/need to precache more items/abilities/units at a later time, you can call the functions individually (for example if you want to precache units in a new wave of holdout). This function should generally only be used if the Precache() function in addon_game_mode.lua is not working. ]] function GameMode:PostLoadPrecache() DebugPrint("[BAREBONES] Performing Post-Load precache") --PrecacheItemByNameAsync("item_example_item", function(...) end) --PrecacheItemByNameAsync("example_ability", function(...) end) --PrecacheUnitByNameAsync("npc_dota_hero_viper", function(...) end) --PrecacheUnitByNameAsync("npc_dota_hero_enigma", function(...) end) end --[[ This function is called once and only once as soon as the first player (almost certain to be the server in local lobbies) loads in. It can be used to initialize state that isn't initializeable in InitGameMode() but needs to be done before everyone loads in. ]] function GameMode:OnFirstPlayerLoaded() DebugPrint("[BAREBONES] First Player has loaded") end --[[ This function is called once and only once after all players have loaded into the game, right as the hero selection time begins. It can be used to initialize non-hero player state or adjust the hero selection (i.e. force random etc) ]] function GameMode:OnAllPlayersLoaded() DebugPrint("[BAREBONES] All Players have loaded into the game") table.insert(humanSpawners, Entities:FindByName( nil, "human_mele_spawner_1"):GetAbsOrigin()) table.insert(humanSpawners, Entities:FindByName( nil, "human_range_spawner_1"):GetAbsOrigin()) table.insert(humanSpawners, Entities:FindByName( nil, "human_mele_spawner_2"):GetAbsOrigin()) table.insert(humanSpawners, Entities:FindByName( nil, "human_range_spawner_2"):GetAbsOrigin()) table.insert(humanSpawners, Entities:FindByName( nil, "human_mele_spawner_3"):GetAbsOrigin()) table.insert(humanSpawners, Entities:FindByName( nil, "human_range_spawner_3"):GetAbsOrigin()) table.insert(undeadSpawners, Entities:FindByName( nil, "undead_mele_spawner_1"):GetAbsOrigin()) table.insert(undeadSpawners, Entities:FindByName( nil, "undead_range_spawner_1"):GetAbsOrigin()) table.insert(undeadSpawners, Entities:FindByName( nil, "undead_mele_spawner_2"):GetAbsOrigin()) table.insert(undeadSpawners, Entities:FindByName( nil, "undead_range_spawner_2"):GetAbsOrigin()) table.insert(undeadSpawners, Entities:FindByName( nil, "undead_mele_spawner_3"):GetAbsOrigin()) table.insert(undeadSpawners, Entities:FindByName( nil, "undead_range_spawner_3"):GetAbsOrigin()) Base:CreateHumanBase() Base:CreateUndeadBase() -- Start the Guard AI systems for all races HumanGuardsAI:Start() UndeadGuardsAI:Start() end --[[ This function is called once and only once for every player when they spawn into the game for the first time. It is also called if the player's hero is replaced with a new hero for any reason. This function is useful for initializing heroes, such as adding levels, changing the starting gold, removing/adding abilities, adding physics, etc. The hero parameter is the hero entity that just spawned in ]] function GameMode:OnHeroInGame(hero) DebugPrint("[BAREBONES] Hero spawned in game for first time -- " .. hero:GetUnitName()) local team = hero:GetTeamNumber() if team == DOTA_TEAM_GOODGUYS then -- Save the hero into the humanTeam table if #humanTeam == 0 then table.insert(humanTeam, hero) else table.insert(#humanTeam + 1, hero) end -- Loop trought all the heroes and make them the owners of line barracks local counter = 1 for _, player in ipairs(humanTeam) do humanBuildings[counter]:SetControllableByPlayer(player:GetPlayerID(), true) humanBuildings[counter]:SetOwner(player) humanBuildings[counter + 1]:SetControllableByPlayer(player:GetPlayerID(), true) humanBuildings[counter + 1]:SetOwner(player) print("The player: "..humanBuildings[counter]:GetPlayerOwnerID().." owns: "..humanBuildings[counter]:GetUnitName()) print("The player: "..humanBuildings[counter + 1]:GetPlayerOwnerID().." owns: "..humanBuildings[counter + 1]:GetUnitName()) counter = counter + 2 end print("Player "..hero:GetPlayerID().." is added to "..team) end if team == DOTA_TEAM_BADGUYS then if #undeadTeam == 0 then table.insert(undeadTeam, hero) else table.insert(#undeadTeam + 1, hero) end print("Player "..hero:GetPlayerID().." is added to "..team) end if team == DOTA_TEAM_CUSTOM_1 then table.insert(nightElfTeam, player) print("Player "..hero:GetPlayerID().." is added to "..team) end if team == DOTA_TEAM_CUSTOM_2 then table.insert(orcTeam, player) print("Player "..hero:GetPlayerID().." is added to "..team) end -- This line for example will set the starting gold of every hero to 500 unreliable gold --hero:SetGold(500, false) -- These lines will create an item and add it to the player, effectively ensuring they start with the item --local item = CreateItem("item_example_item", hero, hero) --hero:AddItem(item) --[[ --These lines if uncommented will replace the W ability of any hero that loads into the game --with the "example_ability" ability local abil = hero:GetAbilityByIndex(1) hero:RemoveAbility(abil:GetAbilityName()) hero:AddAbility("example_ability")]] end --[[ This function is called once and only once when the game completely begins (about 0:00 on the clock). At this point, gold will begin to go up in ticks if configured, creeps will spawn, towers will become damageable etc. This function is useful for starting any game logic timers/thinkers, beginning the first round, etc. ]] function GameMode:OnGameInProgress() local repeat_interval = 30 -- Rerun this timer every *repeat_interval* game-time seconds local start_after = 30 -- Start this timer *start_after* game-time seconds later Timers:CreateTimer(start_after, function() Spawner:SpawnHumanWaves() Spawner:SpawnUndeadWaves() --Spawner:SpawnNightElfWaves() --Spawner:SpawnOrcWaves() return repeat_interval end) end -- This function initializes the game mode and is called before anyone loads into the game -- It can be used to pre-initialize any values/tables that will be needed later function GameMode:InitGameMode() GameMode = self DebugPrint('[BAREBONES] Starting to load Barebones gamemode...') -- Tables that will hold the players for every team humanTeam = {} undeadTeam = {} nightElfTeam = {} orcTeam = {} -- Tables that will hold the buildings for every team humanBuildings = {} humanBuildingAbilities = {} for row=1,6 do humanBuildingAbilities[row] = {} humanBuildingAbilities[row][1] = 0 humanBuildingAbilities[row][2] = 0 humanBuildingAbilities[row][3] = 0 humanBuildingAbilities[row][4] = 1 end humanUpgradeBuildings = {} humanMeleeGuards = {} humanRangedGuards = {} undeadBuildings = {} undeadBuildingAbilities = {} for row=1,6 do undeadBuildingAbilities[row] = {} undeadBuildingAbilities[row][1] = 0 undeadBuildingAbilities[row][2] = 0 undeadBuildingAbilities[row][3] = 0 undeadBuildingAbilities[row][4] = 1 end undeadUpgradeBuildings = {} undeadMeleeGuards = {} undeadRangedGuards = {} nightElfBuildings = {} orcBuildings = {} -- Tables thath will hold all the entities locations humanSpawners = {} undeadSpawners = {} nightElfSpawners = {} orcSpawners = {} -- Call the internal function to set up the rules/behaviors specified in constants.lua -- This also sets up event hooks for all event handlers in events.lua -- Check out internals/gamemode to see/modify the exact code GameMode:_InitGameMode() -- Commands can be registered for debugging purposes or as functions that can be called by the custom Scaleform UI Convars:RegisterCommand( "command_example", Dynamic_Wrap(GameMode, 'ExampleConsoleCommand'), "A console command example", FCVAR_CHEAT ) DebugPrint('[BAREBONES] Done loading Barebones gamemode!\n\n') end -- This is an example console command function GameMode:ExampleConsoleCommand() print( '******* Example Console Command ***************' ) local cmdPlayer = Convars:GetCommandClient() if cmdPlayer then local playerID = cmdPlayer:GetPlayerID() if playerID ~= nil and playerID ~= -1 then -- Do something here for the player who called this command PlayerResource:ReplaceHeroWith(playerID, "npc_dota_hero_viper", 1000, 1000) end end print( '*********************************************' ) end
mit
ccyphers/kong
kong/dao/db/postgres.lua
3
14466
local pgmoon = require "pgmoon-mashape" local Errors = require "kong.dao.errors" local utils = require "kong.tools.utils" local cjson = require "cjson" local get_phase = ngx.get_phase local timer_at = ngx.timer.at local tostring = tostring local ngx_log = ngx.log local concat = table.concat local ipairs = ipairs local pairs = pairs local match = string.match local type = type local find = string.find local uuid = utils.uuid local ceil = math.ceil local fmt = string.format local ERR = ngx.ERR local TTL_CLEANUP_INTERVAL = 60 -- 1 minute local function log(lvl, ...) return ngx_log(lvl, "[postgres] ", ...) end local _M = require("kong.dao.db").new_db("postgres") _M.dao_insert_values = { id = function() return uuid() end } _M.additional_tables = {"ttls"} function _M.new(kong_config) local self = _M.super.new() self.query_options = { host = kong_config.pg_host, port = kong_config.pg_port, user = kong_config.pg_user, password = kong_config.pg_password, database = kong_config.pg_database, ssl = kong_config.pg_ssl, ssl_verify = kong_config.pg_ssl_verify, cafile = kong_config.lua_ssl_trusted_certificate } return self end function _M:infos() return { desc = "database", name = self:clone_query_options().database } end local do_clean_ttl function _M:init_worker() local ok, err = timer_at(TTL_CLEANUP_INTERVAL, do_clean_ttl, self) if not ok then log(ERR, "could not create TTL timer: ", err) end return true end --- TTL utils -- @section ttl_utils local cached_columns_types = {} local function retrieve_primary_key_type(self, schema, table_name) local col_type = cached_columns_types[table_name] if not col_type then local query = fmt([[ SELECT data_type FROM information_schema.columns WHERE table_name = '%s' and column_name = '%s' LIMIT 1]], table_name, schema.primary_key[1]) local res, err = self:query(query) if not res then return nil, err elseif #res > 0 then col_type = res[1].data_type cached_columns_types[table_name] = col_type end end return col_type end local function ttl(self, tbl, table_name, schema, ttl) if not schema.primary_key or #schema.primary_key ~= 1 then return nil, "cannot set a TTL if the entity has no primary key, or has more than one primary key" end local primary_key_type, err = retrieve_primary_key_type(self, schema, table_name) if not primary_key_type then return nil, err end -- get current server time, in milliseconds, but with SECOND precision local query = [[ SELECT extract(epoch from now() at time zone 'utc')::bigint*1000 as timestamp; ]] local res, err = self:query(query) if not res then return nil, err end -- the expiration is always based on the current time local expire_at = res[1].timestamp + (ttl * 1000) local query = fmt([[ SELECT upsert_ttl('%s', %s, '%s', '%s', to_timestamp(%d/1000) at time zone 'UTC') ]], tbl[schema.primary_key[1]], primary_key_type == "uuid" and "'"..tbl[schema.primary_key[1]].."'" or "NULL", schema.primary_key[1], table_name, expire_at) local res, err = self:query(query) if not res then return nil, err end return true end local function clear_expired_ttl(self) local query = [[ SELECT * FROM ttls WHERE expire_at < CURRENT_TIMESTAMP(0) at time zone 'utc' ]] local res, err = self:query(query) if not res then return nil, err end for _, v in ipairs(res) do local delete_entity_query = fmt("DELETE FROM %s WHERE %s='%s'", v.table_name, v.primary_key_name, v.primary_key_value) local res, err = self:query(delete_entity_query) if not res then return nil, err end local delete_ttl_query = fmt([[ DELETE FROM ttls WHERE primary_key_value='%s' AND table_name='%s']], v.primary_key_value, v.table_name) res, err = self:query(delete_ttl_query) if not res then return nil, err end end return true end -- for tests _M.clear_expired_ttl = clear_expired_ttl do_clean_ttl = function(premature, self) if premature then return end local ok, err = clear_expired_ttl(self) if not ok then log(ERR, "could not cleanup TTLs: ", err) end ok, err = timer_at(TTL_CLEANUP_INTERVAL, do_clean_ttl, self) if not ok then log(ERR, "could not create TTL timer: ", err) end end --- Query building -- @section query_building -- @see pgmoon local function escape_identifier(ident) return '"' .. (tostring(ident):gsub('"', '""')) .. '"' end -- @see pgmoon local function escape_literal(val, field) local t_val = type(val) if t_val == "number" then return tostring(val) elseif t_val == "string" then return "'" .. tostring((val:gsub("'", "''"))) .. "'" elseif t_val == "boolean" then return val and "TRUE" or "FALSE" elseif t_val == "table" and field and (field.type == "table" or field.type == "array") then return escape_literal(cjson.encode(val)) end error("don't know how to escape value: " .. tostring(val)) end local function get_where(tbl) local where = {} for col, value in pairs(tbl) do where[#where+1] = fmt("%s = %s", escape_identifier(col), escape_literal(value)) end return concat(where, " AND ") end local function get_select_fields(schema) local fields = {} for k, v in pairs(schema.fields) do if v.type == "timestamp" then fields[#fields+1] = fmt("(extract(epoch from %s)*1000)::bigint as %s", k, k) else fields[#fields+1] = '"' .. k .. '"' end end return concat(fields, ", ") end local function select_query(self, select_clause, schema, table, where, offset, limit) local query local join_ttl = schema.primary_key and #schema.primary_key == 1 if join_ttl then local primary_key_type, err = retrieve_primary_key_type(self, schema, table) if not primary_key_type then return nil, err end query = fmt([[ SELECT %s FROM %s LEFT OUTER JOIN ttls ON (%s.%s = ttls.primary_%s_value) WHERE (ttls.primary_key_value IS NULL OR (ttls.table_name = '%s' AND expire_at > CURRENT_TIMESTAMP(0) at time zone 'utc')) ]], select_clause, table, table, schema.primary_key[1], primary_key_type == "uuid" and "uuid" or "key", table) else query = fmt("SELECT %s FROM %s", select_clause, table) end if where then query = query .. (join_ttl and " AND " or " WHERE ") .. where end if limit then query = query .. " LIMIT " .. limit end if offset and offset > 0 then query = query .. " OFFSET " .. offset end return query end --- Querying -- @section querying local function parse_error(err_str) local err if find(err_str, "Key .* already exists") then local col, value = match(err_str, "%((.+)%)=%((.+)%)") if col then err = Errors.unique {[col] = value} end elseif find(err_str, "violates foreign key constraint") then local col, value = match(err_str, "%((.+)%)=%((.+)%)") if col then err = Errors.foreign {[col] = value} end end return err or Errors.db(err_str) end local function deserialize_rows(rows, schema) for i, row in ipairs(rows) do for col, value in pairs(row) do if type(value) == "string" and schema.fields[col] and (schema.fields[col].type == "table" or schema.fields[col].type == "array") then rows[i][col] = cjson.decode(value) end end end end function _M:query(query, schema) local conn_opts = self:clone_query_options() local pg = pgmoon.new(conn_opts) local ok, err = pg:connect() if not ok then return nil, Errors.db(err) end local res, err = pg:query(query) if get_phase() ~= "init" then pg:keepalive() else pg:disconnect() end if not res then return nil, parse_error(err) elseif schema then deserialize_rows(res, schema) end return res end local function deserialize_timestamps(self, row, schema) local result = row for k, v in pairs(schema.fields) do if v.type == "timestamp" and result[k] then local query = fmt([[ SELECT (extract(epoch from timestamp '%s')*1000)::bigint as %s; ]], result[k], k) local res, err = self:query(query) if not res then return nil, err elseif #res > 0 then result[k] = res[1][k] end end end return result end local function serialize_timestamps(self, tbl, schema) local result = tbl for k, v in pairs(schema.fields) do if v.type == "timestamp" and result[k] then local query = fmt([[ SELECT to_timestamp(%d/1000) at time zone 'UTC' as %s; ]], result[k], k) local res, err = self:query(query) if not res then return nil, err elseif #res <= 1 then result[k] = res[1][k] end end end return result end function _M:insert(table_name, schema, model, _, options) options = options or {} local values, err = serialize_timestamps(self, model, schema) if err then return nil, err end local cols, args = {}, {} for col, value in pairs(values) do cols[#cols+1] = escape_identifier(col) args[#args+1] = escape_literal(value, schema.fields[col]) end local query = fmt("INSERT INTO %s(%s) VALUES(%s) RETURNING *", table_name, concat(cols, ", "), concat(args, ", ")) local res, err = self:query(query, schema) if not res then return nil, err elseif #res > 0 then res, err = deserialize_timestamps(self, res[1], schema) if err then return nil, err else -- Handle options if options.ttl then local ok, err = ttl(self, res, table_name, schema, options.ttl) if not ok then return nil, err end end return res end end end function _M:find(table_name, schema, primary_keys) local where = get_where(primary_keys) local query = select_query(self, get_select_fields(schema), schema, table_name, where) local rows, err = self:query(query, schema) if not rows then return nil, err elseif #rows <= 1 then return rows[1] else return nil, "bad rows result" end end function _M:find_all(table_name, tbl, schema) local where if tbl then where = get_where(tbl) end local query = select_query(self, get_select_fields(schema), schema, table_name, where) return self:query(query, schema) end function _M:find_page(table_name, tbl, page, page_size, schema) page = page or 1 local total_count, err = self:count(table_name, tbl, schema) if not total_count then return nil, err end local total_pages = ceil(total_count/page_size) local offset = page_size * (page - 1) local where if tbl then where = get_where(tbl) end local query = select_query(self, get_select_fields(schema), schema, table_name, where, offset, page_size) local rows, err = self:query(query, schema) if not rows then return nil, err end local next_page = page + 1 return rows, nil, (next_page <= total_pages and next_page or nil) end function _M:count(table_name, tbl, schema) local where if tbl then where = get_where(tbl) end local query = select_query(self, "COUNT(*)", schema, table_name, where) local res, err = self:query(query) if not res then return nil, err elseif #res <= 1 then return res[1].count else return nil, "bad rows result" end end function _M:update(table_name, schema, _, filter_keys, values, nils, full, _, options) options = options or {} local args = {} local values, err = serialize_timestamps(self, values, schema) if not values then return nil, err end for col, value in pairs(values) do args[#args+1] = fmt("%s = %s", escape_identifier(col), escape_literal(value, schema.fields[col])) end if full then for col in pairs(nils) do args[#args+1] = escape_identifier(col) .. " = NULL" end end local where = get_where(filter_keys) local query = fmt("UPDATE %s SET %s WHERE %s RETURNING *", table_name, concat(args, ", "), where) local res, err = self:query(query, schema) if not res then return nil, err elseif res.affected_rows == 1 then res, err = deserialize_timestamps(self, res[1], schema) if not res then return nil, err elseif options.ttl then local ok, err = ttl(self, res, table_name, schema, options.ttl) if not ok then return nil, err end end return res end end function _M:delete(table_name, schema, primary_keys) local where = get_where(primary_keys) local query = fmt("DELETE FROM %s WHERE %s RETURNING *", table_name, where) local res, err = self:query(query, schema) if not res then return nil, err elseif res.affected_rows == 1 then return deserialize_timestamps(self, res[1], schema) end end --- Migrations -- @section migrations function _M:queries(queries) if utils.strip(queries) ~= "" then local res, err = self:query(queries) if not res then return err end end end function _M:drop_table(table_name) local res, err = self:query("DROP TABLE "..table_name.." CASCADE") if not res then return nil, err end return true end function _M:truncate_table(table_name) local res, err = self:query("TRUNCATE "..table_name.." CASCADE") if not res then return nil, err end return true end function _M:current_migrations() -- check if schema_migrations table exists local rows, err = self:query "SELECT to_regclass('schema_migrations')" if not rows then return nil, err end if #rows > 0 and rows[1].to_regclass == "schema_migrations" then return self:query "SELECT * FROM schema_migrations" else return {} end end function _M:record_migration(id, name) local res, err = self:query{ [[ CREATE OR REPLACE FUNCTION upsert_schema_migrations(identifier text, migration_name varchar) RETURNS VOID AS $$ DECLARE BEGIN UPDATE schema_migrations SET migrations = array_append(migrations, migration_name) WHERE id = identifier; IF NOT FOUND THEN INSERT INTO schema_migrations(id, migrations) VALUES(identifier, ARRAY[migration_name]); END IF; END; $$ LANGUAGE 'plpgsql'; ]], fmt("SELECT upsert_schema_migrations('%s', %s)", id, escape_literal(name)) } if not res then return nil, err end return true end return _M
apache-2.0
Ninjistix/darkstar
scripts/zones/Norg/npcs/Heizo.lua
5
2877
----------------------------------- -- Area: Norg -- NPC: Heizo -- Starts and Ends Quest: Like Shining Leggings -- !pos -1 -5 25 252 ----------------------------------- package.loaded["scripts/zones/Norg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Norg/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) ShiningLeggings = player:getQuestStatus(OUTLANDS,LIKE_A_SHINING_LEGGINGS); Legging = trade:getItemQty(14117); if (Legging > 0 and Legging == trade:getItemCount()) then TurnedInVar = player:getVar("shiningLeggings_nb"); if (ShiningLeggings == QUEST_ACCEPTED and TurnedInVar + Legging >= 10) then -- complete quest player:startEvent(129); elseif (ShiningLeggings == QUEST_ACCEPTED and TurnedInVar <= 9) then -- turning in less than the amount needed to finish the quest TotalLeggings = Legging + TurnedInVar player:tradeComplete(); player:setVar("shiningLeggings_nb",TotalLeggings); player:startEvent(128,TotalLeggings); -- Update player on number of leggings turned in end else if (ShiningLeggings == QUEST_ACCEPTED) then player:startEvent(128,TotalLeggings); -- Update player on number of leggings turned in, but doesn't accept anything other than leggings else player:startEvent(126); -- Give standard conversation if items are traded but no quest is accepted end end end; function onTrigger(player,npc) ShiningLeggings = player:getQuestStatus(OUTLANDS,LIKE_A_SHINING_LEGGINGS); if (ShiningLeggings == QUEST_AVAILABLE and player:getFameLevel(NORG) >= 3) then player:startEvent(127); -- Start Like Shining Leggings elseif (ShiningLeggings == QUEST_ACCEPTED) then player:startEvent(128,player:getVar("shiningSubligar_nb")); -- Update player on number of Leggings turned in else player:startEvent(126); -- Standard Conversation end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 127) then player:addQuest(OUTLANDS,LIKE_A_SHINING_LEGGINGS); elseif (csid == 129) then player:tradeComplete(); player:addItem(4958); -- Scroll of Dokumori: Ichi player:messageSpecial(ITEM_OBTAINED, 4958); -- Scroll of Dokumori: Ichi player:addFame(NORG,100); player:addTitle(LOOKS_GOOD_IN_LEGGINGS); player:setVar("shiningLeggings_nb",0); player:completeQuest(OUTLANDS,LIKE_A_SHINING_LEGGINGS); end end;
gpl-3.0
s-d-a/DCS-ExportScripts
Scripts/DCS-ExportScript/ExportsModules/SA342M.lua
1
44848
-- SA342M ExportScript.FoundDCSModule = true ExportScript.Version.SA342M = "1.2.1" ExportScript.ConfigEveryFrameArguments = { --[[ every frames arguments based of "mainpanel_init.lua" Example (http://www.lua.org/manual/5.1/manual.html#pdf-string.format) [DeviceID] = "Format" [4] = "%.4f", <- floating-point number with 4 digits after point [19] = "%0.1f", <- floating-point number with 1 digit after point [129] = "%1d", <- decimal number [5] = "%.f", <- floating point number rounded to a decimal number ]] -- Gyro Panel [200] = "%.4f", -- Gyro_Needle_State {-1,1} Gyro Panel SYNC [201] = "%.f", -- Gyro_voyant_test Lamp {0,1} [202] = "%.f", -- Gyro_voyant_trim Lamp {0,1} [203] = "%.f", -- Gyro_voyant_bpp Lamp {0,1} -- Autopilot Panel [37] = "%.4f", -- T_Needle_State {-1,1} Pitch correction Indicator [38] = "%.4f", -- R_Needle_State {-1,1} Roll correction Indicator [39] = "%.4f", -- L_Needle_State {-1,1} Yaw correction Indicator --[196] = "%.4f", -- RWR_light {0,1} -- RWR background light --[] = "%.4f", -- PE_fondbright {0,1} ??? --[353] = "%.4f", -- NADIR_fondbright {0,1} ??? -- Flare Dispenser Lamps [233] = "%.f", -- Voyant_FD_On {0,1} Power On [231] = "%.f", -- Voyant_FD_G {0,1} select Left [232] = "%.f", -- Voyant_FD_D {0,1} select Right [227] = "%.f", -- Voyant_FD_LEU {0,1} Status LEU [223] = "%.f", -- Voyant_FD_G_vide1 {0,1} Status Left G [224] = "%.f", -- Voyant_FD_G_vide2 {0,1} Status Left VIDE [225] = "%.f", -- Voyant_FD_D_vide1 {0,1} Status Right G [226] = "%.f", -- Voyant_FD_D_vide2 {0,1} Status Right VIDE -- ADF Radio [158] = "%0.1f", -- ADF_nav1_centaine {0,1} X00.0 khz {0,1,2,3,4,5,6,7,8,9,0}{0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0} [159] = "%0.1f", -- ADF_nav1_dizaine {0,1} 0X0.0 khz {0,1,2,3,4,5,6,7,8,9,0}{0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0} [160] = "%0.1f", -- ADF_nav1_unite {0,1} 00X.0 khz {0,1,2,3,4,5,6,7,8,9,0}{0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0} [161] = "%0.1f", -- ADF_nav1_dec {0,1} 000.X khz {0,1,2,3,4,5,6,7,8,9,0}{0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0} [162] = "%0.1f", -- ADF_nav2_centaine {0,1} X00.0 khz {0,1,2,3,4,5,6,7,8,9,0}{0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0} [163] = "%0.1f", -- ADF_nav2_dizaine {0,1} 0X0.0 khz {0,1,2,3,4,5,6,7,8,9,0}{0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0} [164] = "%0.1f", -- ADF_nav2_unite {0,1} 00X.0 khz {0,1,2,3,4,5,6,7,8,9,0}{0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0} [165] = "%0.1f", -- ADF_nav2_dec {0,1} 000.X khz {0,1,2,3,4,5,6,7,8,9,0}{0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0} -- ADF Gauge [113] = "%.4f", -- ADF_Fond Compass rose {0,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250,260,270,280,290,300,310,320,330,340,350,360}{0.0,0.028,0.055,0.084,0.111,0.138,0.166,0.194,0.222,0.249,0.2775,0.305,0.332,0.36,0.388,0.415,0.4434,0.47,0.498,0.526,0.555,0.583,0.611,0.638,0.6665,0.694,0.722,0.75,0.776,0.805,0.833,0.861,0.8885,0.917,0.944,0.972,1.0} --[102] = "%.4f", -- ADF_Aiguille_large Heading Needle large {-360.0,0.0,360.0}{-1.0,0.0,1.0} [103] = "%.4f", -- ADF_Aiguille_fine Heading Needle fine {-360.0,0.0,360.0}{-1.0,0.0,1.0} [107] = "%.1f", -- ADF_FlagCAP {0,1} [109] = "%.1f", -- ADF_FlagBut {0,1} [108] = "%.1f", -- ADF_FlagCompteur PX Flag {0,1} [110] = "%0.1f", -- ADF_compteur_Cent {0,1} X00 {0,1,2,3,4,5,6,7,8,9,0}{0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0} [111] = "%0.1f", -- ADF_compteur_Dix {0,1} 0X0 {0,1,2,3,4,5,6,7,8,9,0}{0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0} [112] = "%0.1f", -- ADF_compteur_Unit {0,1} 00X {0,1,2,3,4,5,6,7,8,9,0}{0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0} -- CLOCK [41] = "%.3f", -- CLOCK_HOUR {0,1,2,3,4,5,6,7,8,9,10,11,12}{0,0.081,0.162,0.245,0.33,0.415,0.501,0.587,0.672,0.756,0.838,0.919,1} [42] = "%.3f", -- CLOCK_SECOND {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60}{0,0.017,0.033,0.049,0.065,0.08,0.098,0.115,0.131,0.147,0.163,0.18,0.195,0.213,0.23,0.246,0.262,0.279,0.296,0.313,0.33,0.346,0.363,0.38,0.397,0.415,0.431,0.449,0.466,0.483,0.501,0.518,0.535,0.552,0.569,0.586,0.604,0.621,0.638,0.655,0.672,0.688,0.705,0.722,0.739,0.755,0.771,0.788,0.804,0.821,0.838,0.853,0.87,0.885,0.902,0.919,0.934,0.95,0.967,0.984,1} [43] = "%.3f", -- CLOCK_MINUTE {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60}{0,0.017,0.033,0.049,0.065,0.08,0.098,0.115,0.131,0.147,0.163,0.18,0.195,0.213,0.23,0.246,0.262,0.279,0.296,0.313,0.33,0.346,0.363,0.38,0.397,0.415,0.431,0.449,0.466,0.483,0.501,0.518,0.535,0.552,0.569,0.586,0.604,0.621,0.638,0.655,0.672,0.688,0.705,0.722,0.739,0.755,0.771,0.788,0.804,0.821,0.838,0.853,0.87,0.885,0.902,0.919,0.934,0.95,0.967,0.984,1} [44] = "%.3f", -- CLOCK_MINI {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30}{0,0.032,0.065,0.098,0.131,0.164,0.198,0.231,0.264,0.297,0.331,0.364,0.397,0.43,0.464,0.497,0.523,0.551,0.576,0.605,0.63,0.659,0.684,0.714,0.758,0.796,0.838,0.879,0.92,0.958,1} [210] = "%.4f", -- Clock_ExtCouronne -- Wipers --[547] = "%.4f", -- EGPilote {-1,1} --[546] = "%.4f", -- EGCopilote {-1,1} -- LIGHTS --[40] = "%.4f", -- Lum_Plafond {0,1} Main Panel Lights --[142] = "%.4f", -- PBOIntensity {0,1} Main Panel Background lights --[144] = "%.4f", -- PUPIntensity {0,1} Lower Panel Background lights -- Baro altimetre [87] = "%.4f", -- Baro_Altimeter_thousands Needle {0.0,1.0} [573] = "%.4f", -- Baro_Altimeter_hundred Needle {0.0,1.0} [88] = "%0.1f", -- Baro_Altimeter_press_unite 000X {0,1,2,3,4,5,6,7,8,9,0}{0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0} [90] = "%0.1f", -- Baro_Altimeter_press_dix 00X0 {0,1,2,3,4,5,6,7,8,9,0}{0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0} [92] = "%0.1f", -- Baro_Altimeter_press_cent 0X00 {0,1,2,3,4,5,6,7,8,9,0}{0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0} [95] = "%0.1f", -- Baro_Altimeter_press_mille X000 {0,1,2,3,4,5,6,7,8,9,0}{0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0} -- radar altimetre [94] = "%.4f", -- Radar_Altimeter {0,5,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,200,250,300,350,400,450,500,550,600,650,700,750,800,850}{0,0.019,0.035,0.072,0.109,0.147,0.18,0.214,0.247,0.283,0.316,0.345,0.376,0.407,0.438,0.469,0.501,0.564,0.606,0.648,0.676,0.706,0.732,0.756,0.775,0.794,0.811,0.829,0.843,0.858,0.87} [93] = "%.4f", -- DangerRALT_index {0,5,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,200,250,300,350,400,450,500,550,600,650,700,750,800,850}{0.0,0.0175,0.0338,0.0715,0.109,0.147,0.182,0.215,0.247,0.282,0.315,0.3445,0.377,0.407,0.439,0.47,0.5005,0.5628,0.6052,0.646,0.675,0.7058,0.7315,0.755,0.7747,0.793,0.8097,0.8272,0.8425,0.8575,0.8693} --[97] = "%.f", -- RAltlamp {0,1} [98] = "%.f", -- RAlt_flag_Panne OFF Flag{0,1} [99] = "%.1f", -- RAlt_flag_MA A (Test) Flag{0,1} [91] = "%.1f", -- RAlt_knob_MA Power/Test Knop{0,1} -- TORQUE [16] = "%.3f", -- Torque {0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100,105,110}{0.085,0.13,0.172,0.214,0.253,0.289,0.326,0.362,0.395,0.43,0.466,0.501,0.537,0.573,0.607,0.639,0.676,0.71,0.746,0.785,0.826,0.865,0.908} [55] = "%.3f", -- Torque_Bug {0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100,105,110}{0.084,0.128,0.171,0.2134,0.252,0.2889,0.325,0.361,0.396,0.431,0.467,0.501,0.535,0.571,0.605,0.639,0.674,0.71,0.745,0.785,0.825,0.865,0.91} [17] = "%.f", -- VOYANT_TORQUE Lamp {0,1} -- Gyro_Compas [26] = "%.3f", -- Gyro_Compas {0,30,60,90,120,150,180,210,240,270,300,330,360}{0,0.083,0.167,0.251,0.334,0.418,0.5,0.583,0.667,0.751,0.832,0.917,1} -- Stby HA ADI [214] = "%.4f", -- StbyHA_Roll {-180,-90,-60,-30,-20,-10,0,10,20,30,60,90,180}{-1,-0.502,-0.335,-0.166,-0.11,-0.052,0,0.055,0.113,0.171,0.334,0.502,1} [213] = "%.4f", -- StbyHA_Pitch {-180,-150,-120,-90,-60,-50,-40,-30,-20,-15,-10,-5,0,5,10,15,20,30,40,50,60,90,120,150,180}{-1,-0.833,-0.667,-0.5,-0.333,-0.278,-0.223,-0.167,-0.111,-0.084,-0.057,-0.003,0,0.028,0.056,0.083,0.111,0.167,0.223,0.278,0.333,0.5,0.667,0.833,1} [211] = "%.1f", -- StdbyHA_Flag Fault Flag {0,1} [212] = "%.4f", -- Stdby_HA_W W Sympol {0,1} [217] = "%.4f", -- Stdby_HA_Curseur Knob Needle {0,1} -- QComb Fuel Indicator [137] = "%.3f", -- QComb {0,50,100,150,200,250,300,350,400,500}{0.093,0.243,0.354,0.428,0.521,0.621,0.692,0.771,0.834,0.932} -- Horizon Artificiel Principal [27] = "%.4f", -- Pitch_HA {-180,-170,-160,-150,-140,-130,-120,-110,-100,-90,-80,-70,-60,-50,-40,-30,-20,-10,0,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180}{-1,-0.946,-0.898,-0.838,-0.78,-0.723,-0.667,-0.61,-0.556,-0.501,-0.446,-0.393,-0.334,-0.277,-0.223,-0.166,-0.104,-0.054,0,0.054,0.102,0.161,0.22,0.277,0.333,0.389,0.443,0.498,0.553,0.607,0.666,0.722,0.776,0.834,0.896,0.946,1} [28] = "%.4f", -- Roll_HA {-180,-90,-60,-30,-20,-10,0,10,20,30,60,90,180}{-1,-0.498,-0.331,-0.162,-0.111,-0.053,0,0.058,0.112,0.168,0.331,0.498,1} [20] = "%.4f", -- Bille_HA Slip Ball {-1,1} [18] = "%.1f", -- flag_GS_HA GS Flag {0,1} [19] = "%.1f", -- flag_HS_HA Fault Flag {0,1} [29] = "%.1f", -- flag_Lock_HA Lock Flag {0,1} [117] = "%.4f", -- Curseur_HA Knob Needle {0,1} [120] = "%.4f", -- W_HA W Sympol {-1,1} [118] = "%.4f", -- VerBar_HA Vertical Bar {-1,1} [119] = "%.4f", -- HorBar_HA Horizon Bar {-1,1} -- variometre [24] = "%.4f", -- Variometre {-800,-700,-600,-500,-400,-300,-200,-100,-50,0,50,100,200,300,400,500,600,700,800}{-0.481,-0.436,-0.391,-0.338,-0.28,-0.218,-0.153,-0.075,-0.035,0.0,0.035,0.071,0.139,0.202,0.264,0.32,0.372,0.418,0.463} -- IAS [51] = "%.4f", -- IAS {0,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250,260,270,280,290,300,310,320,330,340,350,360,370}{0,0.1,0.133,0.172,0.207,0.243,0.277,0.316,0.35,0.38,0.41,0.439,0.465,0.491,0.517,0.541,0.565,0.587,0.611,0.63,0.651,0.671,0.692,0.712,0.731,0.75,0.77,0.791,0.809,0.829,0.849,0.867,0.886} -- RPM [135] = "%.4f", -- Turbine_RPM large Needle {0,5000,10000,15000,20000,25000,29000,35000,40000,43500,45000,50000}{0.095,0.181,0.263,0.346,0.424,0.505,0.572,0.665,0.748,0.802,0.828,0.909} [52] = "%.4f", -- Rotor_RPM small Needle {0,50,100,150,200,250,262,316.29,361.05,387,400,450}{0.096,0.191,0.283,0.374,0.461,0.549,0.57,0.665,0.748,0.802,0.811,0.904} -- Voltmetre [14] = "%.3f", -- Voltmetre {0,5,10,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35}{0.045,0.074,0.103,0.133,0.163,0.192,0.221,0.25,0.281,0.31,0.339,0.368,0.399,0.429,0.458,0.488,0.518,0.547,0.576,0.605,0.635,0.664,0.695,0.724} -- TQuatre Engine temperature Indicator [15] = "%.3f", -- TQuatre Engine Temp {0,100,200,300,400,500,600,700,800}{0.1575,0.228,0.3,0.3845,0.473,0.577,0.676,0.772,0.8625} -- TempExt outside temperature [25] = "%.3f", -- TempExt {-40,-35,-30,-25,-20,-15,-10,-5,0,5,10,15,20,25,30,35,40,45,50,55,60,65,70}{-0.758,-0.691,-0.625,-0.558,-0.492,-0.425,-0.359,-0.292,-0.224,-0.158,-0.09,-0.024,0.043,0.11,0.177,0.244,0.31,0.379,0.445,0.512,0.579,0.644,0.712} -- TempThm Oil Temperature Indicator [151] = "%.3f", -- TempThm Oil Temp {-20,-10,0,10,20,30,40,50,60,70,80,85,90,100}{0.046,0.102,0.157,0.213,0.268,0.323,0.38,0.435,0.492,0.547,0.603,0.63,0.659,0.715} -- Fuel Tank Indicator [152] = "%.3f", -- Gauge_RSupp {-1,0,0.25,0.5,0.75,1}{0,0.202,0.426,0.63,0.801,1} -- VHF AM Radio [133] = "%.1f", -- AM_Radio_freq_cent {0,1} X00.000 {0,1,2,3,4,5,6,7,8,9,0}{0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0} [134] = "%.1f", -- AM_Radio_freq_dix {0,1} 0X0.000 {0,1,2,3,4,5,6,7,8,9,0}{0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0} [136] = "%.1f", -- AM_Radio_freq_unite {0,1} 00X.000 {0,1,2,3,4,5,6,7,8,9,0}{0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0} [138] = "%.1f", -- AM_Radio_freq_dixieme {0,1} 000.X00 {0,1,2,3,4,5,6,7,8,9,0}{0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0} [139] = "%.2f", -- AM_Radio_freq_centieme {0,1} 000.0XX {00,25,50,75,00}{0.0,0.25,0.50,0.75,1.0} -- Lamps -- Voyant_DEM [300] = "%.f", -- Voyant_DEM Start lamp{0,1} -- Voyant_RLT [301] = "%.f", -- Voyant_RLT Idle lamp {0,1} -- Voyant_BLOC [302] = "%.f", -- Voyant_BLOC Blocked Engine lamp {0,1} -- RSUPP Fueltank [320] = "%.f", -- Voyant_RSupp Fueltank lamp {0,1} -- RCONV Convoy Fueltank [321] = "%.f", -- Voyant_RConv Convoy Fueltank lamüp {0,1} -- Voyant_FILTAS Sandfilter lamp [322] = "%.f", -- Voyant_FILTAS sandfilter lamp {0,1} -- Voyant_Alarme Master Alarme lamp [303] = "%.f", -- Voyant_Alarme Master Alarme lamp {0,1} -- AM_RADIO [141] = "%.f", -- AM_Radio_lamp {0,1} -- Tableau Alarme Lamps [1] = "%.f", -- TA_Pitot {0,1} [2] = "%.f", -- TA_Hmot {0,1} [3] = "%.f", -- TA_Hbtp {0,1} [4] = "%.f", -- TA_Hral {0,1} [5] = "%.f", -- TA_Gene {0,1} [6] = "%.f", -- TA_Alter {0,1} [7] = "%.f", -- TA_Bat {0,1} [8] = "%.f", -- TA_PA {0,1} [9] = "%.f", -- TA_Nav {0,1} [10] = "%.f", -- TA_Comb {0,1} [11] = "%.f", -- TA_Bphy {0,1} [12] = "%.f", -- TA_Lim {0,1} [13] = "%.f", -- TA_Filt {0,1} -- Intercomp Lamps [455] = "%.f", -- Intercomp VHF Light [456] = "%.f", -- Intercomp FM1 Light [457] = "%.f", -- Intercomp UHF Light -- SA342M HOT3 Weapon Panel Lamps [183] = "%.f", -- HOT3 WP Lamps BON [184] = "%.f", -- HOT3 WP Lamps MAUVAIS [185] = "%.f", -- HOT3 WP Lamps ALIMENTATION [186] = "%.f", -- HOT3 WP Lamps MISSILE PRET [187] = "%.f", -- HOT3 WP Lamps TIR AUTOR. [188] = "%.f", -- HOT3 WP Lamps DEFAUT [189] = "%.f", -- HOT3 WP Lamps TEST I [190] = "%.f", -- HOT3 WP Lamps JOUR [191] = "%.f", -- HOT3 WP Lamps LUMINOSITE [192] = "%.f", -- HOT3 WP Lamps TEST II [193] = "%.f" -- HOT3 WP Lamps NUIT } ExportScript.ConfigArguments = { --[[ arguments for export in low tick interval based on "clickabledata.lua" ]] -- WEAPONS PANEL 1 [354] = "%1d", -- WP1 - Off/On/Stsnfby {-1.0,0.0,1.0} [357] = "%.4f", -- WP1 - Brightness (Axis) {0.0, 1.0} in 0.1 Steps -- WEAPONS PANEL 2 [372] = "%1d", -- WP2 - Ma Left [373] = "%1d", -- WP2 - Ma Left Cover [374] = "%1d", -- WP2 - Ma Right [375] = "%1d", -- WP2 - Ma Right Cover [376] = "%1d", -- WP2 - Seq Ripple selection -- PILOTSIGHT [171] = "%1d", -- PILOTSIGHT - Pilot Sight -- PILOT STICK --[50] = "%1d", -- PILOT STICK - Magnetic Brake --[53] = "%1d", -- PILOT STICK - Wiper once --[209] = "%1d", -- PILOT STICK - Autopilot Button --[293] = "%1d", -- PILOT STICK - Slave --[294] = "%1d", -- PILOT STICK - Auto-Hover -- WSO LEFT SIDE STICK [255] = "%1d", -- PE WSO STICK - Lasing Button Cover [256] = "%1d", -- PE WSO STICK - Lasing Button [257] = "%1d", -- PE WSO STICK - Missile Launch Cover [258] = "%1d", -- PE WSO STICK - Missile Launch Button [259] = "%1d", -- PE WSO STICK - Inversed Symbology Toggle [260] = "%1d", -- PE WSO STICK - Inversed Image Toggle [264] = "%.1f", -- PE WSO STICK - Image Focus {-1.0,1.0} [262] = "%.1f", -- PE WSO STICK - Gain {-1.0,1.0} [263] = "%.1f", -- PE WSO STICK - Image Brightness {-1.0,1.0} [219] = "%.1f", -- PE WSO STICK - Symbology Brightness {-1.0,1.0} -- GYRO [197] = "%1d", -- GYRO - Test Cover [198] = "%1d", -- GYRO - Test Switch On/Off [199] = "%1d", -- GYRO - Left/Center/Right [153] = "%.2f", -- GYRO - CM/A/GM/D/GD {0.0,0.25,0.50,0.75,1.0} -- CLOCK [45] = "%.4f", -- CLOCK - Winder (Axis) {0.0, 1.0} in 0.1 Steps [46] = "%1d", -- CLOCK - Start/Stop [47] = "%1d", -- CLOCK - Reset -- SA342M HOT3 only -- PH SA342M HOT3 [180] = "%.2f", -- PH - Test II/Test I/Off/Day/Night {0.0,0.25,0.50,0.75,1.0} [181] = "%.3f", -- PH - Station Select 0/1/0/2/0/3/0/4/0 {0.0,0.125,0.250,0,375,0.500,0.625,0.750,0.875,1.0} [182] = "%.4f", -- PH - Brightness (Axis) {0.0, 1.0} in 0.1 Steps -- PE SA342L/M/Mistral BCV (BOITIER DE COMMANDE VIDEO – video command box) [362] = "%1d", -- PE BCV - Centering [364] = "%1d", -- PE BCV - VDO/VTH [365] = "%.1f", -- PE BCV - Zoom {-1.0,1.0} [366] = "%.1f", -- PE BCV - CTH A/V/M {0.0,0.5,1.0} [367] = "%1d", -- PE BCV - Power [370] = "%.2f", -- PE BCV - Mode A/C/V/PIL/ASS {0.0,0.25,0.50,0.75,1.0} -- NADIR [330] = "%.4f", -- NADIR - Off/Brightness (Axis) {0.0, 1.0} in 0.1 Steps [331] = "%.2f", -- NADIR - Mode Off/Stby/Ground/Sea/Air Speed Sensor/Ground Test {0.0,0.2,0.4,0.6,0.8,1.0} [332] = "%.2f", -- NADIR - Parameter Wind/Magnetic Heading/Ground Speed/Calculated Time/Current Position/Waypoint {0.0,0.2,0.4,0.6,0.8,1.0} [333] = "%1d", -- NADIR - ENT [334] = "%1d", -- NADIR - DES [335] = "%1d", -- NADIR - AUX [336] = "%1d", -- NADIR - IC [337] = "%1d", -- NADIR - DOWN [351] = "%1d", -- NADIR - 0 [338] = "%1d", -- NADIR - 1 [339] = "%1d", -- NADIR - 2 [340] = "%1d", -- NADIR - 3 [342] = "%1d", -- NADIR - 4 [343] = "%1d", -- NADIR - 5 [344] = "%1d", -- NADIR - 6 [346] = "%1d", -- NADIR - 7 [347] = "%1d", -- NADIR - 8 [348] = "%1d", -- NADIR - 9 [341] = "%1d", -- NADIR - POL [345] = "%1d", -- NADIR - GEO [349] = "%1d", -- NADIR - POS [350] = "%1d", -- NADIR - GEL [352] = "%1d", -- NADIR - EFF -- AM_RADIO [128] = "%.2f", -- AM RADIO - Selector {0.0,0.33,0.66,0.99} [129] = "%.4f", -- AM RADIO - Freq decimals (Axis) {0.0, 1.0} in 0.1 Steps [130] = "%1d", -- AM RADIO - 25/50kHz Selector [131] = "%.4f", -- AM RADIO - Freq dial (Axis) {0.0, 1.0} in 0.1 Steps -- FM_RADIO [272] = "%.2f", -- FM RADIO - Main Selector {0.0,0.25,0.50,0.75,1.0} [273] = "%.3f", -- FM RADIO - Chanel Selector {0.0,0.143,0.286,0.429,0.572,0.715,0.858,1.0} [274] = "%1d", -- FM RADIO - 7 [275] = "%1d", -- FM RADIO - 8 [276] = "%1d", -- FM RADIO - 9 [277] = "%1d", -- FM RADIO - 0 [278] = "%1d", -- FM RADIO - X [279] = "%1d", -- FM RADIO - 4 [280] = "%1d", -- FM RADIO - 5 [281] = "%1d", -- FM RADIO - 6 [282] = "%1d", -- FM RADIO - RC [283] = "%1d", -- FM RADIO - UP [284] = "%1d", -- FM RADIO - 1 [285] = "%1d", -- FM RADIO - 2 [286] = "%1d", -- FM RADIO - 3 [287] = "%1d", -- FM RADIO - VAL [288] = "%1d", -- FM RADIO - DOWN -- TV [124] = "%1d", -- TV - On/Off [125] = "%.4f", -- TV - Contrast (Axis) {0.0, 1.0} in 0.1 Steps [123] = "%.4f", -- TV - Brightness (Axis) {0.0, 1.0} in 0.1 Steps --[126] = "%.4f", -- TV - Cover (Axis) {0.0, 1.0} in 0.1 Steps -- RWR [148] = "%1d", -- RWR - Off/On/Croc {-1.0,0.0,1.0} [149] = "%1d", -- RWR - Marker [150] = "%1d", -- RWR - Page [121] = "%.4f", -- RWR - Audio (Axis) {0.0, 1.0} in 0.1 Steps [122] = "%.4f", -- RWR - Brightness (Axis) {0.0, 1.0} in 0.1 Steps -- ADI [115] = "%.4f", -- ADI - Unlock (Axis) {0.0, 1.0} in 0.1 Steps [116] = "%1d", -- ADI - Unlock -- Stby ADI [215] = "%.4f", -- STDBY ADI - Unlock (Axis) {0.0, 1.0} in 0.1 Steps [216] = "%1d", -- STDBY ADI - Unlock -- ArtVisVhfDop (Source selector for main artificial horizon vertical bar) [218] = "%.2f", -- ADI - Source Off/Camera target point/ADF ermitter/NADIR Waypoint {0.0,0.33,0.66,0.99} -- INTERCOM [452] = "%1d", -- INTERCOM - VHF AM Radio [68] = "%.4f", -- INTERCOM - VHF AM Radio Volume (Axis) {0.0, 1.0} in 0.1 Steps [453] = "%1d", -- INTERCOM - FM Radio [69] = "%.4f", -- INTERCOM - FM Radio Volume (Axis) {0.0, 1.0} in 0.1 Steps [454] = "%1d", -- INTERCOM - UHF Radio [70] = "%.4f", -- INTERCOM - UHF Radio Volume (Axis) {0.0, 1.0} in 0.1 Steps -- TORQUE [58] = "%1d", -- TORQUE Bug/Test [54] = "%.4f", -- TORQUE Bug/Test (Axis) {0.0, 1.0} in 0.1 Steps -- LIGHTS [22] = "%.4f", -- LIGHTS - Main Dashboard Lighting (Axis) {0.0, 1.0} in 0.1 Steps [21] = "%.4f", -- LIGHTS - Console Lighting (Axis) {0.0, 1.0} in 0.1 Steps [145] = "%.4f", -- LIGHTS - UV Lighting (Axis) {0.0, 1.0} in 0.1 Steps [23] = "%1d", -- LIGHTS - NORM/BNL [147] = "%.4f", -- LIGHTS - Roof Lamp Knob (Axis) {0.0, 1.0} in 0.1 Steps [154] = "%1d", -- LIGHTS - Red Lens On/Off -- ELECTRIC [264] = "%1d", -- ELECTRIC - Battery [265] = "%1d", -- ELECTRIC - Alternator [268] = "%1d", -- ELECTRIC - Generator [62] = "%1d", -- ELECTRIC - Voltmeter Test [170] = "%1d", -- ELECTRIC - Pitot [271] = "%1d", -- ELECTRIC - Fuel Pump [267] = "%1d", -- ELECTRIC - Additionnal Fuel Tank [56] = "%1d", -- ELECTRIC - Starter Start/Stop/Air {-1.0,0.0,1.0} [57] = "%1d", -- ELECTRIC - Test [48] = "%1d", -- ELECTRIC - Copilot Wiper {-1.0,0.0,1.0} [49] = "%1d", -- ELECTRIC - Pilot Wiper {-1.0,0.0,1.0} [61] = "%1d", -- ELECTRIC - Left from Pitot [59] = "%1d", -- ELECTRIC - HYD Test [66] = "%1d", -- ELECTRIC - Alter Rearm [67] = "%1d", -- ELECTRIC - Gene Rearm [63] = "%1d", -- ELECTRIC - Convoy Tank On/Off [64] = "%1d", -- ELECTRIC - Sand Filter On/Off -- NAVLIGHTS [146] = "%1d", -- NAVLIGHTS - Navigation Lights CLI/OFF/FIX {-1.0,0.0,1.0} [228] = "%1d", -- NAVLIGHTS - Anticollision Light NOR/OFF/ATT {-1.0,0.0,1.0} [105] = "%1d", -- NAVLIGHTS - Landing Light Off/Vario/On {-1.0,0.0,1.0} [106] = "%1d", -- NAVLIGHTS - Landing Light Extend/Retract [382] = "%1d", -- NAVLIGHTS - Panels Lighting On/Off [30] = "%.4f", -- NAVLIGHTS - AntiCollision Light Intensity (Axis) {0.0, 1.0} in 0.1 Steps [229] = "%1d", -- NAVLIGHTS - Formation Lights On/Off [230] = "%.4f", -- NAVLIGHTS - Formation Lights Intensity (Axis) {0.0, 1.0} in 0.1 Steps -- FLARE DISPENSER [220] = "%1d", -- FLARE DISPENSER - G/G+D/D {-1.0,0.0,1.0} [221] = "%1d", -- FLARE DISPENSER - Mode [222] = "%1d", -- FLARE DISPENSER - Off/Speed {-1.0,0.0,1.0} [194] = "%1d", -- FLARE DISPENSER - Fire Button Cover [195] = "%1d", -- FLARE DISPENSER - Fire Button -- AUTOPILOT [31] = "%1d", -- AUTOPILOT - Autopilot On/Off [32] = "%1d", -- AUTOPILOT - Pitch On/Off [33] = "%1d", -- AUTOPILOT - Roll On/Off [34] = "%1d", -- AUTOPILOT - Yaw On/Off [35] = "%1d", -- AUTOPILOT - Mode Speed/OFF/Altitude {-1.0,0.0,1.0} [60] = "%1d", -- AUTOPILOT - Trim On/Off [65] = "%1d", -- AUTOPILOT - Magnetic Brake On/Off -- WEAPONS [269] = "%1d", -- WEAPONS - Master arm On/Off -- ROTORS [556] = "%.4f", -- ROTORS - Rotor Brake (Axis) {0.0, 1.0} in 0.055 Steps -- RADIOALTIMETER [96] = "%.4f", -- RADIOALTIMETER - Radar Alt Bug (Axis) {0.0, 1.0} in 0.1 Steps [100] = "%1d", -- RADIOALTIMETER - Radar Alt On/Off - Test [91] = "%.4f", -- RADIOALTIMETER - Radar Alt On/Off - Test (Axis) {0.0, 1.0} in 0.1 Steps -- BAROALTIMETER [89] = "%.4f", -- BAROALTIMETER - Baro pressure QFE knob (Axis) {0.0, 1.0} in 0.1 Steps -- FUEL SYSTEM [557] = "%.4f", -- FUEL SYSTEM - Fuel Flow Lever (Axis) {0.0, 1.0} in 0.2 Steps -- ADF RADIO [166] = "%1d", -- ADF RADIO - Select [167] = "%1d", -- ADF RADIO - Tone [178] = "%.2f", -- ADF RADIO - Mode {0.0,0.33,0.66,0.99} [179] = "%.4f", -- ADF RADIO - Gain (Axis) {0.0, 1.0} in 0.2 Steps [168] = "%.4f", -- ADF RADIO - Nav1 Hundred (Axis) {0.0, 1.0} in 0.2 Steps [169] = "%.4f", -- ADF RADIO - Nav1 Ten (Axis) {0.0, 1.0} in 0.2 Steps [173] = "%.4f", -- ADF RADIO - Nav1 Unit (Axis) {0.0, 1.0} in 0.2 Steps [174] = "%.4f", -- ADF RADIO - Nav2 Hundred (Axis) {0.0, 1.0} in 0.2 Steps [175] = "%.4f", -- ADF RADIO - Nav2 Ten (Axis) {0.0, 1.0} in 0.2 Steps [176] = "%.4f", -- ADF RADIO - Nav2 Unit (Axis) {0.0, 1.0} in 0.2 Steps -- UHF RADIO [383] = "%.3f", -- UHF RADIO - MODE 0/FF/NA/SV/DL/G/EN {0.0,0.167,0.334,0.501,0.668,0.835,1.0} [384] = "%1d", -- UHF RADIO - DRW [385] = "%1d", -- UHF RADIO - VLD [386] = "%.4f", -- UHF RADIO - PAGE (Axis) {0.0, 1.0} in 0.2 Steps [387] = "%1d", -- UHF RADIO - CONF [388] = "%1d", -- UHF RADIO - 1 [389] = "%1d", -- UHF RADIO - 2 [390] = "%1d", -- UHF RADIO - 3 [391] = "%1d", -- UHF RADIO - 4 [392] = "%1d", -- UHF RADIO - 5 [393] = "%1d", -- UHF RADIO - 6 [394] = "%1d", -- UHF RADIO - 7 [395] = "%1d", -- UHF RADIO - 8 [396] = "%1d", -- UHF RADIO - 9 [397] = "%1d" -- UHF RADIO - 0 } ----------------------------- -- HIGH IMPORTANCE EXPORTS -- -- done every export event -- ----------------------------- -- Pointed to by ProcessIkarusDCSHighImportance function ExportScript.ProcessIkarusDCSConfigHighImportance(mainPanelDevice) --[[ every frame export to Ikarus Example from A-10C Get Radio Frequencies get data from device local lUHFRadio = GetDevice(54) ExportScript.Tools.SendData("ExportID", "Format") ExportScript.Tools.SendData(2000, string.format("%7.3f", lUHFRadio:get_frequency()/1000000)) -- <- special function for get frequency data ExportScript.Tools.SendData(2000, ExportScript.Tools.RoundFreqeuncy((UHF_RADIO:get_frequency()/1000000))) -- ExportScript.Tools.RoundFreqeuncy(frequency (MHz|KHz), format ("7.3"), PrefixZeros (false), LeastValue (0.025)) ]] --[97] = "%.f", -- RAltlamp {0,1} ExportScript.Tools.SendData(97, (mainPanelDevice:get_argument_value(97) > 0.009 and 1 or 0)) --[102] = "%.4f", -- ADF_Aiguille_large Heading Needle large {-360.0,0.0,360.0}{-1.0,0.0,1.0} local ADF_Aiguille_large = mainPanelDevice:get_argument_value(102) if ADF_Aiguille_large ~= 0 then ADF_Aiguille_large = ADF_Aiguille_large + 0.5 if ADF_Aiguille_large > 1 then ADF_Aiguille_large = ADF_Aiguille_large - 1.0 end end ExportScript.Tools.SendData(102, string.format("%.4f", ADF_Aiguille_large)) end function ExportScript.ProcessDACConfigHighImportance(mainPanelDevice) --[[ every frame export to DAC Example from A-10C Get Radio Frequencies get data from device local UHF_RADIO = GetDevice(54) ExportScript.Tools.SendDataDAC("ExportID", "Format") ExportScript.Tools.SendDataDAC("ExportID", "Format", HardwareConfigID) ExportScript.Tools.SendDataDAC("2000", string.format("%7.3f", UHF_RADIO:get_frequency()/1000000)) ExportScript.Tools.SendDataDAC("2000", ExportScript.Tools.RoundFreqeuncy((UHF_RADIO:get_frequency()/1000000))) -- ExportScript.Tools.RoundFreqeuncy(frequency (MHz|KHz), format ("7.3"), PrefixZeros (false), LeastValue (0.025)) ]] end ----------------------------------------------------- -- LOW IMPORTANCE EXPORTS -- -- done every gExportLowTickInterval export events -- ----------------------------------------------------- -- Pointed to by ExportScript.ProcessIkarusDCSConfigLowImportance function ExportScript.ProcessIkarusDCSConfigLowImportance(mainPanelDevice) --[[ export in low tick interval to Ikarus Example from A-10C Get Radio Frequencies get data from device local lUHFRadio = GetDevice(54) ExportScript.Tools.SendData("ExportID", "Format") ExportScript.Tools.SendData(2000, string.format("%7.3f", lUHFRadio:get_frequency()/1000000)) -- <- special function for get frequency data ExportScript.Tools.SendData(2000, ExportScript.Tools.RoundFreqeuncy((UHF_RADIO:get_frequency()/1000000))) -- ExportScript.Tools.RoundFreqeuncy(frequency (MHz|KHz), format ("7.3"), PrefixZeros (false), LeastValue (0.025)) ]] -- UHF Radio --------------------------------------------------- local lUHFRadio = GetDevice(31) if lUHFRadio:is_on() then --ExportScript.Tools.SendData(2000, string.format("%.3f", lUHFRadio:get_frequency()/1000000)) --ExportScript.Tools.WriteToLog('UHF_Freq: '..ExportScript.Tools.dump(list_indication(5))) local lUHFRadioFreq = ExportScript.Tools.getListIndicatorValue(5) if lUHFRadioFreq ~= nil and lUHFRadioFreq.UHF_Freq ~= nil then ExportScript.Tools.SendData(2000, string.format("%s", lUHFRadioFreq.UHF_Freq)) end else ExportScript.Tools.SendData(2000, " ") end -- AM Radio --------------------------------------------------- local lAMRadio = GetDevice(5) if lAMRadio:is_on() then --ExportScript.Tools.SendData(2001, string.format("%.3f", lAMRadio:get_frequency()/1000000)) ExportScript.Tools.SendData(2001, ExportScript.Tools.RoundFreqeuncy(lAMRadio:get_frequency()/1000000)) end -- FM Radio PR4G --------------------------------------------------- local lFMRadio = GetDevice(28) if lFMRadio:is_on() then --ExportScript.Tools.SendData(2002, string.format("%.3f", lFMRadio:get_frequency()/1000000)) --ExportScript.Tools.WriteToLog('FM_Freq: '..ExportScript.Tools.dump(list_indication(4))) local lFMRadioFreq = ExportScript.Tools.getListIndicatorValue(4) if lFMRadioFreq ~= nil and lFMRadioFreq.FM_Freq ~= nil then ExportScript.Tools.SendData(2002, string.format("%s", lFMRadioFreq.FM_Freq)) end else ExportScript.Tools.SendData(2002, " ") end -- [273] = "%.3f", -- FM RADIO - Chanel Selector {0.0,0.143,0.286,0.429,0.572,0.715,0.858,1.0} -- laut clickabledata.lua -- [273] = "%.1f", -- FM RADIO - Chanel Selector {0.0,0.2,0.3,0.5,0.6,0.8,0.9,1.1} -- gerundet local lFM_RADIO_PRESET = {[0.0]="1",[0.2]="2",[0.3]="3",[0.5]="4",[0.6]="5",[0.8]="6",[0.9]="0",[1.1]="R"} ExportScript.Tools.SendData(2003, lFM_RADIO_PRESET[ExportScript.Tools.round(mainPanelDevice:get_argument_value(273), 1, "ceil")]) -- Weapon Panel --------------------------------------------------- if mainPanelDevice:get_argument_value(354) >= 0.0 then -- Weapon panel is On local lWeaponPanelDisplays = ExportScript.Tools.getListIndicatorValue(8) if lWeaponPanelDisplays ~= nil then if lWeaponPanelDisplays.LEFT_screen ~= nil then ExportScript.Tools.SendData(2004, string.format("%s", lWeaponPanelDisplays.LEFT_screen)) end if lWeaponPanelDisplays.RIGHT_screen ~= nil then ExportScript.Tools.SendData(2005, string.format("%s", lWeaponPanelDisplays.RIGHT_screen)) end end else ExportScript.Tools.SendData(2004, "-") ExportScript.Tools.SendData(2005, "-") end end function ExportScript.ProcessDACConfigLowImportance(mainPanelDevice) --[[ export in low tick interval to DAC Example from A-10C Get Radio Frequencies get data from device local UHF_RADIO = GetDevice(54) ExportScript.Tools.SendDataDAC("ExportID", "Format") ExportScript.Tools.SendDataDAC("ExportID", "Format", HardwareConfigID) ExportScript.Tools.SendDataDAC("2000", string.format("%7.3f", UHF_RADIO:get_frequency()/1000000)) ExportScript.Tools.SendDataDAC("2000", ExportScript.Tools.RoundFreqeuncy((UHF_RADIO:get_frequency()/1000000))) -- ExportScript.Tools.RoundFreqeuncy(frequency (MHz|KHz), format ("7.3"), PrefixZeros (false), LeastValue (0.025)) ]] -- UHF Radio --------------------------------------------------- local lUHFRadio = GetDevice(31) if lUHFRadio:is_on() then --ExportScript.Tools.SendDataDAC("2000", string.format("%.3f", lUHFRadio:get_frequency()/1000000)) --ExportScript.Tools.WriteToLog('UHF_Freq: '..ExportScript.Tools.dump(list_indication(5))) local lUHFRadioFreq = ExportScript.Tools.getListIndicatorValue(5) if lUHFRadioFreq ~= nil and lUHFRadioFreq.UHF_Freq ~= nil then ExportScript.Tools.SendDataDAC("2000", string.format("%s", lUHFRadioFreq.UHF_Freq)) end else ExportScript.Tools.SendDataDAC("2000", "-") end -- AM Radio --------------------------------------------------- local lAMRadio = GetDevice(5) if lAMRadio:is_on() then --ExportScript.Tools.SendDataDAC("2001", string.format("%.3f", lAMRadio:get_frequency()/1000000)) ExportScript.Tools.SendDataDAC("2001", ExportScript.Tools.RoundFreqeuncy(lAMRadio:get_frequency()/1000000)) end -- FM Radio PR4G --------------------------------------------------- local lFMRadio = GetDevice(28) if lFMRadio:is_on() then --ExportScript.Tools.SendDataDAC(2002, string.format("%.3f", lFMRadio:get_frequency()/1000000)) --ExportScript.Tools.WriteToLog('FM_Freq: '..ExportScript.Tools.dump(list_indication(4))) local lFMRadioFreq = ExportScript.Tools.getListIndicatorValue(4) if lFMRadioFreq ~= nil and lFMRadioFreq.FM_Freq ~= nil then ExportScript.Tools.SendDataDAC("2002", string.format("%s", lFMRadioFreq.FM_Freq)) end else ExportScript.Tools.SendDataDAC("2002", "-") end -- [273] = "%.3f", -- FM RADIO - Chanel Selector {0.0,0.143,0.286,0.429,0.572,0.715,0.858,1.0} -- laut clickabledata.lua -- [273] = "%.1f", -- FM RADIO - Chanel Selector {0.0,0.2,0.3,0.5,0.6,0.8,0.9,1.1} -- gerundet local lFM_RADIO_PRESET = {[0.0]="1",[0.2]="2",[0.3]="3",[0.5]="4",[0.6]="5",[0.8]="6",[0.9]="0",[1.1]="R"} ExportScript.Tools.SendDataDAC("2003", lFM_RADIO_PRESET[ExportScript.Tools.round(mainPanelDevice:get_argument_value(273), 1, "ceil")]) -- Weapon Panel --------------------------------------------------- if mainPanelDevice:get_argument_value(354) >= 0.0 then -- Weapon panel is On local lWeaponPanelDisplays = ExportScript.Tools.getListIndicatorValue(8) if lWeaponPanelDisplays ~= nil then if lWeaponPanelDisplays.LEFT_screen ~= nil then ExportScript.Tools.SendDataDAC("2004", string.format("%s", lWeaponPanelDisplays.LEFT_screen)) end if lWeaponPanelDisplays.RIGHT_screen ~= nil then ExportScript.Tools.SendDataDAC("2005", string.format("%s", lWeaponPanelDisplays.RIGHT_screen)) end end else ExportScript.Tools.SendDataDAC("2004", "-") ExportScript.Tools.SendDataDAC("2005", "-") end -- generic Radio display and frequency rotarys ------------------------------------------------- -- genericRadioConf ExportScript.genericRadioConf = {} ExportScript.genericRadioConf['maxRadios'] = 3 -- numbers of aviables/supported radios ExportScript.genericRadioConf[1] = {} -- first radio ExportScript.genericRadioConf[1]['Name'] = "UHF Radio" -- name of radio ExportScript.genericRadioConf[1]['DeviceID'] = 31 -- DeviceID for GetDevice from device.lua ExportScript.genericRadioConf[1]['setFrequency'] = true -- change frequency active ExportScript.genericRadioConf[1]['FrequencyMultiplicator'] = 1000000 -- Multiplicator from Hz to MHz ExportScript.genericRadioConf[1]['FrequencyFormat'] = "%7.3f" -- frequency view format LUA style ExportScript.genericRadioConf[1]['FrequencyStep'] = 25 -- minimal step for frequency change ExportScript.genericRadioConf[1]['minFrequency'] = 225.000 -- lowest frequency ExportScript.genericRadioConf[1]['maxFrequency'] = 399.975 -- highest frequency ExportScript.genericRadioConf[1]['Power'] = {} -- power button active ExportScript.genericRadioConf[1]['Power']['ButtonID'] = 3001 -- power button id from cklickable.lua ExportScript.genericRadioConf[1]['Power']['ValueOn'] = 0.167 -- power on value from cklickable.lua ExportScript.genericRadioConf[1]['Power']['ValueOff'] = 0.0 -- power off value from cklickable.lua --ExportScript.genericRadioConf[1]['Volume'] = {} -- volume knob active --ExportScript.genericRadioConf[1]['Volume']['ButtonID'] = 3011 -- volume button id from cklickable.lua --ExportScript.genericRadioConf[1]['Preset'] = {} -- preset knob active --ExportScript.genericRadioConf[1]['Preset']['ArgumentID'] = 161 -- ManualPreset argument id from cklickable.lua --ExportScript.genericRadioConf[1]['Preset']['ButtonID'] = 3001 -- preset button id from cklickable.lua -- Preset based on switchlogic on clickabledata.lua --ExportScript.genericRadioConf[1]['Preset']['List'] = {[0.0]="01",[0.05]="02",[0.10]="03",[0.15]="04",[0.20]="05",[0.25]="06",[0.30]="07",[0.35]="08",[0.40]="09",[0.45]="10",[0.50]="11",[0.55]="12",[0.60]="13",[0.65]="14",[0.70]="15",[0.75]="16",[0.80]="17",[0.85]="18",[0.90]="19",[0.95]="20",[1.00]="01"} --ExportScript.genericRadioConf[1]['Preset']['Step'] = 0.05 -- minimal step for preset change --ExportScript.genericRadioConf[1]['Squelch'] = {} -- squelch switch active --ExportScript.genericRadioConf[1]['Squelch']['ArgumentID'] = 170 -- ManualPreset argument id from cklickable.lua --ExportScript.genericRadioConf[1]['Squelch']['ButtonID'] = 3010 -- squelch button id from cklickable.lua --ExportScript.genericRadioConf[1]['Squelch']['ValueOn'] = 0.0 -- squelch on value from cklickable.lua --ExportScript.genericRadioConf[1]['Squelch']['ValueOff'] = 1.0 -- squelch off value from cklickable.lua -- Load Button = VLD Button ExportScript.genericRadioConf[1]['Load'] = {} -- load button preset ExportScript.genericRadioConf[1]['Load']['ButtonID'] = 3003 -- load button id from cklickable.lua --ExportScript.genericRadioConf[1]['ManualPreset'] = {} -- switch manual or preset active --ExportScript.genericRadioConf[1]['ManualPreset']['ArgumentID'] = 167 -- ManualPreset argument id from cklickable.lua --ExportScript.genericRadioConf[1]['ManualPreset']['ButtonID'] = 3007 -- ManualPreset button id from cklickable.lua --ExportScript.genericRadioConf[1]['ManualPreset']['ValueManual'] = 0.0-- ManualPreset Manual value from cklickable.lua --ExportScript.genericRadioConf[1]['ManualPreset']['ValuePreset'] = 0.1-- ManualPreset Preset value from cklickable.lua ExportScript.genericRadioConf[2] = {} -- secound radio ExportScript.genericRadioConf[2]['Name'] = "AM Radio" -- name of radio ExportScript.genericRadioConf[2]['DeviceID'] = 5 -- DeviceID for GetDevice from device.lua ExportScript.genericRadioConf[2]['setFrequency'] = true -- change frequency active ExportScript.genericRadioConf[2]['FrequencyMultiplicator'] = 1000000 -- Multiplicator from Hz to MHz ExportScript.genericRadioConf[2]['FrequencyFormat'] = "%7.3f" -- frequency view format LUA style ExportScript.genericRadioConf[2]['FrequencyStep'] = 25 -- minimal step for frequency change ExportScript.genericRadioConf[2]['minFrequency'] = 118.000 -- lowest frequency ExportScript.genericRadioConf[2]['maxFrequency'] = 143.975 -- highest frequency ExportScript.genericRadioConf[2]['Power'] = {} -- power button active ExportScript.genericRadioConf[2]['Power']['ButtonID'] = 3001 -- power button id from cklickable.lua ExportScript.genericRadioConf[2]['Power']['ValueOn'] = 0.33 -- power on value from cklickable.lua ExportScript.genericRadioConf[2]['Power']['ValueOff'] = 0.0 -- power off value from cklickable.lua --ExportScript.genericRadioConf[2]['Volume'] = {} -- volume knob active --ExportScript.genericRadioConf[2]['Volume']['ButtonID'] = 3005 -- volume button id from cklickable.lua --ExportScript.genericRadioConf[2]['Preset'] = {} -- preset knob active --ExportScript.genericRadioConf[2]['Preset']['ArgumentID'] = 137 -- ManualPreset argument id from cklickable.lua --ExportScript.genericRadioConf[2]['Preset']['ButtonID'] = 3001 -- preset button id from cklickable.lua -- Preset based on switchlogic on clickabledata.lua --ExportScript.genericRadioConf[2]['Preset']['List'] = {[0.0]="01",[0.01]="02",[0.02]="03",[0.03]="04",[0.04]="05",[0.05]="06",[0.06]="07",[0.07]="08",[0.08]="09",[0.09]="10",[0.10]="11",[0.11]="12",[0.12]="13",[0.13]="14",[0.14]="15",[0.15]="16",[0.16]="17",[0.17]="18",[0.18]="19",[0.19]="20",[0.20]="01"} --ExportScript.genericRadioConf[2]['Preset']['Step'] = 0.01 -- minimal step for preset change --ExportScript.genericRadioConf[2]['Squelch'] = {} -- squelch switch active --ExportScript.genericRadioConf[2]['Squelch']['ArgumentID'] = 134 -- ManualPreset argument id from cklickable.lua --ExportScript.genericRadioConf[2]['Squelch']['ButtonID'] = 3008 -- squelch button id from cklickable.lua --ExportScript.genericRadioConf[2]['Squelch']['ValueOn'] = 0.0 -- squelch on value from cklickable.lua --ExportScript.genericRadioConf[2]['Squelch']['ValueOff'] = 1.0 -- squelch off value from cklickable.lua --ExportScript.genericRadioConf[2]['Load'] = {} -- load button preset --ExportScript.genericRadioConf[2]['Load']['ButtonID'] = 3006 -- load button id from cklickable.lua --ExportScript.genericRadioConf[2]['ManualPreset'] = {} -- switch manual or preset active --ExportScript.genericRadioConf[2]['ManualPreset']['ArgumentID'] = 135 -- ManualPreset argument id from cklickable.lua --ExportScript.genericRadioConf[2]['ManualPreset']['ButtonID'] = 3004 -- ManualPreset button id from cklickable.lua --ExportScript.genericRadioConf[2]['ManualPreset']['ValueManual'] = 0.2-- ManualPreset Manual value from cklickable.lua --ExportScript.genericRadioConf[2]['ManualPreset']['ValuePreset'] = 0.3-- ManualPreset Preset value from cklickable.lua ExportScript.genericRadioConf[3] = {} -- secound radio ExportScript.genericRadioConf[3]['Name'] = "FM Radio" -- name of radio ExportScript.genericRadioConf[3]['DeviceID'] = 28 -- DeviceID for GetDevice from device.lua ExportScript.genericRadioConf[3]['setFrequency'] = true -- change frequency active ExportScript.genericRadioConf[3]['FrequencyMultiplicator'] = 1000000 -- Multiplicator from Hz to MHz ExportScript.genericRadioConf[3]['FrequencyFormat'] = "%7.3f" -- frequency view format LUA style ExportScript.genericRadioConf[3]['FrequencyStep'] = 25 -- minimal step for frequency change ExportScript.genericRadioConf[3]['minFrequency'] = 30.000 -- lowest frequency ExportScript.genericRadioConf[3]['maxFrequency'] = 87.975 -- highest frequency ExportScript.genericRadioConf[3]['Power'] = {} -- power button active ExportScript.genericRadioConf[3]['Power']['ButtonID'] = 3001 -- power button id from cklickable.lua ExportScript.genericRadioConf[3]['Power']['ValueOn'] = 0.25 -- power on value from cklickable.lua ExportScript.genericRadioConf[3]['Power']['ValueOff'] = 0.0 -- power off value from cklickable.lua --ExportScript.genericRadioConf[3]['Volume'] = {} -- volume knob active --ExportScript.genericRadioConf[3]['Volume']['ButtonID'] = 3005 -- volume button id from cklickable.lua ExportScript.genericRadioConf[3]['Preset'] = {} -- preset knob active ExportScript.genericRadioConf[3]['Preset']['ArgumentID'] = 273 -- ManualPreset argument id from cklickable.lua ExportScript.genericRadioConf[3]['Preset']['ButtonID'] = 3002 -- preset button id from cklickable.lua --ExportScript.genericRadioConf[3]['Preset']['ButtonID2'] = 3002 -- preset button id from cklickable.lua -- Preset based on switchlogic on clickabledata.lua -- [273] = "%.3f", -- FM RADIO - Chanel Selector {0.0,0.143,0.286,0.429,0.572,0.715,0.858,1.0} -- laut clickabledata.lua ExportScript.genericRadioConf[3]['Preset']['List'] = {[0.0]="1",[0.143]="2",[0.286]="3",[0.429]="4",[0.572]="5",[0.715]="6",[0.858]="0",[1.0]="-"} ExportScript.genericRadioConf[3]['Preset']['Step'] = 0.143 -- minimal step for preset change --ExportScript.genericRadioConf[3]['Preset']['Step2'] = -0.01 -- minimal step for preset change --ExportScript.genericRadioConf[3]['Squelch'] = {} -- squelch switch active --ExportScript.genericRadioConf[3]['Squelch']['ArgumentID'] = 148 -- ManualPreset argument id from cklickable.lua --ExportScript.genericRadioConf[3]['Squelch']['ButtonID'] = 3008 -- squelch button id from cklickable.lua --ExportScript.genericRadioConf[3]['Squelch']['ValueOn'] = 0.0 -- squelch on value from cklickable.lua --ExportScript.genericRadioConf[3]['Squelch']['ValueOff'] = -1.0 -- squelch off value from cklickable.lua --ExportScript.genericRadioConf[3]['Load'] = {} -- load button preset --ExportScript.genericRadioConf[3]['Load']['ButtonID'] = 3004 -- load button id from cklickable.lua --ExportScript.genericRadioConf[3]['ManualPreset'] = {} -- switch manual or preset active --ExportScript.genericRadioConf[3]['ManualPreset']['ArgumentID'] = 149 -- ManualPreset argument id from cklickable.lua --ExportScript.genericRadioConf[3]['ManualPreset']['ButtonID'] = 3004 -- ManualPreset button id from cklickable.lua --ExportScript.genericRadioConf[3]['ManualPreset']['ValueManual'] = 0.2-- ManualPreset Manual value from cklickable.lua --ExportScript.genericRadioConf[3]['ManualPreset']['ValuePreset'] = 0.3-- ManualPreset Preset value from cklickable.lua ExportScript.genericRadio(nil, nil) --===================================================================================== --[[ ExportScript.Tools.WriteToLog('list_cockpit_params(): '..ExportScript.Tools.dump(list_cockpit_params())) ExportScript.Tools.WriteToLog('CMSP: '..ExportScript.Tools.dump(list_indication(7))) -- list_indication get tehe value of cockpit displays local ltmp1 = 0 for ltmp2 = 0, 20, 1 do ltmp1 = list_indication(ltmp2) ExportScript.Tools.WriteToLog(ltmp2..': '..ExportScript.Tools.dump(ltmp1)) end ]] --[[ -- getmetatable get function name from devices local ltmp1 = 0 for ltmp2 = 1, 70, 1 do ltmp1 = GetDevice(ltmp2) ExportScript.Tools.WriteToLog(ltmp2..': '..ExportScript.Tools.dump(ltmp1)) ExportScript.Tools.WriteToLog(ltmp2..' (metatable): '..ExportScript.Tools.dump(getmetatable(ltmp1))) end ]] end ----------------------------- -- Custom functions -- -----------------------------
lgpl-3.0
Ninjistix/darkstar
scripts/zones/Kazham-Jeuno_Airship/npcs/Joosef.lua
5
2002
----------------------------------- -- Area: Kazham-Jeuno Airship -- NPC: Joosef -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham-Jeuno_Airship/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Kazham-Jeuno_Airship/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local vHour = VanadielHour(); local vMin = VanadielMinute(); while vHour >= 1 do vHour = vHour - 6; end local message = WILL_REACH_KAZHAM; if (vHour == -5) then if (vMin >= 48) then vHour = 3; message = WILL_REACH_JEUNO; else vHour = 0; end elseif (vHour == -4) then vHour = 2; message = WILL_REACH_JEUNO; elseif (vHour == -3) then vHour = 1; message = WILL_REACH_JEUNO; elseif (vHour == -2) then if (vMin <= 49) then vHour = 0; message = WILL_REACH_JEUNO; else vHour = 3; end elseif (vHour == -1) then vHour = 2; elseif (vHour == 0) then vHour = 1; end local vMinutes = 0; if (message == WILL_REACH_JEUNO) then vMinutes = (vHour * 60) + 49 - vMin; else -- WILL_REACH_KAZHAM vMinutes = (vHour * 60) + 48 - vMin; end if (vMinutes <= 30) then if ( message == WILL_REACH_KAZHAM) then message = IN_KAZHAM_MOMENTARILY; else -- WILL_REACH_JEUNO message = IN_JEUNO_MOMENTARILY; end elseif (vMinutes < 60) then vHour = 0; end player:messageSpecial( message, math.floor((2.4 * vMinutes) / 60), math.floor( vMinutes / 60 + 0.5)); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
chappers/refresh-love
_book/images/main.lua
2
1205
function love.load() Tileset = love.graphics.newImage('countryside.png') TileW, TileH = 32,32 local tilesetW, tilesetH = Tileset:getWidth(), Tileset:getHeight() local quadInfo = { {'.', 0, 0}, -- grass {'#', 32, 0}, -- box {'*', 0, 32}, -- flowers {'^',32, 32} -- boxtop } Quads = {} for _, info in ipairs(quadInfo) do -- info[1] = char, info[2] = x, info[3] = y Quads[info[1]] = love.graphics.newQuad(info[2], info[3], TileW, TileH, tilesetW, tilesetH) end local tileString = [[ ... .#*. ... ]] TileTable = {} local width = #(tileString:match("[^\n]+")) for x=1,width,1 do TileTable[x] = {} end -- initilaise correct dim local rowIndex, columnIndex = 1,1 for row in tileString:gmatch("[^\n]+") do columnIndex = 1 for chr in row:gmatch(".") do TileTable[rowIndex][columnIndex] = chr columnIndex = columnIndex + 1 end rowIndex = rowIndex+1 end end function love.draw() for rowIndex, row in ipairs(TileTable) do for colIndex, chr in ipairs(row) do local x,y = 250+(colIndex-1)*TileW, 250+(rowIndex-1)*TileH love.graphics.draw(Tileset, Quads[chr], x,y) end end end
mit
chappers/refresh-love
images/main.lua
2
1205
function love.load() Tileset = love.graphics.newImage('countryside.png') TileW, TileH = 32,32 local tilesetW, tilesetH = Tileset:getWidth(), Tileset:getHeight() local quadInfo = { {'.', 0, 0}, -- grass {'#', 32, 0}, -- box {'*', 0, 32}, -- flowers {'^',32, 32} -- boxtop } Quads = {} for _, info in ipairs(quadInfo) do -- info[1] = char, info[2] = x, info[3] = y Quads[info[1]] = love.graphics.newQuad(info[2], info[3], TileW, TileH, tilesetW, tilesetH) end local tileString = [[ ... .#*. ... ]] TileTable = {} local width = #(tileString:match("[^\n]+")) for x=1,width,1 do TileTable[x] = {} end -- initilaise correct dim local rowIndex, columnIndex = 1,1 for row in tileString:gmatch("[^\n]+") do columnIndex = 1 for chr in row:gmatch(".") do TileTable[rowIndex][columnIndex] = chr columnIndex = columnIndex + 1 end rowIndex = rowIndex+1 end end function love.draw() for rowIndex, row in ipairs(TileTable) do for colIndex, chr in ipairs(row) do local x,y = 250+(colIndex-1)*TileW, 250+(rowIndex-1)*TileH love.graphics.draw(Tileset, Quads[chr], x,y) end end end
mit
codedash64/Urho3D
Source/ThirdParty/LuaJIT/src/jit/dis_x86.lua
41
32726
---------------------------------------------------------------------------- -- LuaJIT x86/x64 disassembler module. -- -- Copyright (C) 2005-2016 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- This is a helper module used by the LuaJIT machine code dumper module. -- -- Sending small code snippets to an external disassembler and mixing the -- output with our own stuff was too fragile. So I had to bite the bullet -- and write yet another x86 disassembler. Oh well ... -- -- The output format is very similar to what ndisasm generates. But it has -- been developed independently by looking at the opcode tables from the -- Intel and AMD manuals. The supported instruction set is quite extensive -- and reflects what a current generation Intel or AMD CPU implements in -- 32 bit and 64 bit mode. Yes, this includes MMX, SSE, SSE2, SSE3, SSSE3, -- SSE4.1, SSE4.2, SSE4a, AVX, AVX2 and even privileged and hypervisor -- (VMX/SVM) instructions. -- -- Notes: -- * The (useless) a16 prefix, 3DNow and pre-586 opcodes are unsupported. -- * No attempt at optimization has been made -- it's fast enough for my needs. ------------------------------------------------------------------------------ local type = type local sub, byte, format = string.sub, string.byte, string.format local match, gmatch, gsub = string.match, string.gmatch, string.gsub local lower, rep = string.lower, string.rep local bit = require("bit") local tohex = bit.tohex -- Map for 1st opcode byte in 32 bit mode. Ugly? Well ... read on. local map_opc1_32 = { --0x [0]="addBmr","addVmr","addBrm","addVrm","addBai","addVai","push es","pop es", "orBmr","orVmr","orBrm","orVrm","orBai","orVai","push cs","opc2*", --1x "adcBmr","adcVmr","adcBrm","adcVrm","adcBai","adcVai","push ss","pop ss", "sbbBmr","sbbVmr","sbbBrm","sbbVrm","sbbBai","sbbVai","push ds","pop ds", --2x "andBmr","andVmr","andBrm","andVrm","andBai","andVai","es:seg","daa", "subBmr","subVmr","subBrm","subVrm","subBai","subVai","cs:seg","das", --3x "xorBmr","xorVmr","xorBrm","xorVrm","xorBai","xorVai","ss:seg","aaa", "cmpBmr","cmpVmr","cmpBrm","cmpVrm","cmpBai","cmpVai","ds:seg","aas", --4x "incVR","incVR","incVR","incVR","incVR","incVR","incVR","incVR", "decVR","decVR","decVR","decVR","decVR","decVR","decVR","decVR", --5x "pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR", "popUR","popUR","popUR","popUR","popUR","popUR","popUR","popUR", --6x "sz*pushaw,pusha","sz*popaw,popa","boundVrm","arplWmr", "fs:seg","gs:seg","o16:","a16", "pushUi","imulVrmi","pushBs","imulVrms", "insb","insVS","outsb","outsVS", --7x "joBj","jnoBj","jbBj","jnbBj","jzBj","jnzBj","jbeBj","jaBj", "jsBj","jnsBj","jpeBj","jpoBj","jlBj","jgeBj","jleBj","jgBj", --8x "arith!Bmi","arith!Vmi","arith!Bmi","arith!Vms", "testBmr","testVmr","xchgBrm","xchgVrm", "movBmr","movVmr","movBrm","movVrm", "movVmg","leaVrm","movWgm","popUm", --9x "nop*xchgVaR|pause|xchgWaR|repne nop","xchgVaR","xchgVaR","xchgVaR", "xchgVaR","xchgVaR","xchgVaR","xchgVaR", "sz*cbw,cwde,cdqe","sz*cwd,cdq,cqo","call farViw","wait", "sz*pushfw,pushf","sz*popfw,popf","sahf","lahf", --Ax "movBao","movVao","movBoa","movVoa", "movsb","movsVS","cmpsb","cmpsVS", "testBai","testVai","stosb","stosVS", "lodsb","lodsVS","scasb","scasVS", --Bx "movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi", "movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI", --Cx "shift!Bmu","shift!Vmu","retBw","ret","vex*3$lesVrm","vex*2$ldsVrm","movBmi","movVmi", "enterBwu","leave","retfBw","retf","int3","intBu","into","iretVS", --Dx "shift!Bm1","shift!Vm1","shift!Bmc","shift!Vmc","aamBu","aadBu","salc","xlatb", "fp*0","fp*1","fp*2","fp*3","fp*4","fp*5","fp*6","fp*7", --Ex "loopneBj","loopeBj","loopBj","sz*jcxzBj,jecxzBj,jrcxzBj", "inBau","inVau","outBua","outVua", "callVj","jmpVj","jmp farViw","jmpBj","inBad","inVad","outBda","outVda", --Fx "lock:","int1","repne:rep","rep:","hlt","cmc","testb!Bm","testv!Vm", "clc","stc","cli","sti","cld","std","incb!Bm","incd!Vm", } assert(#map_opc1_32 == 255) -- Map for 1st opcode byte in 64 bit mode (overrides only). local map_opc1_64 = setmetatable({ [0x06]=false, [0x07]=false, [0x0e]=false, [0x16]=false, [0x17]=false, [0x1e]=false, [0x1f]=false, [0x27]=false, [0x2f]=false, [0x37]=false, [0x3f]=false, [0x60]=false, [0x61]=false, [0x62]=false, [0x63]="movsxdVrDmt", [0x67]="a32:", [0x40]="rex*", [0x41]="rex*b", [0x42]="rex*x", [0x43]="rex*xb", [0x44]="rex*r", [0x45]="rex*rb", [0x46]="rex*rx", [0x47]="rex*rxb", [0x48]="rex*w", [0x49]="rex*wb", [0x4a]="rex*wx", [0x4b]="rex*wxb", [0x4c]="rex*wr", [0x4d]="rex*wrb", [0x4e]="rex*wrx", [0x4f]="rex*wrxb", [0x82]=false, [0x9a]=false, [0xc4]="vex*3", [0xc5]="vex*2", [0xce]=false, [0xd4]=false, [0xd5]=false, [0xd6]=false, [0xea]=false, }, { __index = map_opc1_32 }) -- Map for 2nd opcode byte (0F xx). True CISC hell. Hey, I told you. -- Prefix dependent MMX/SSE opcodes: (none)|rep|o16|repne, -|F3|66|F2 local map_opc2 = { --0x [0]="sldt!Dmp","sgdt!Ump","larVrm","lslVrm",nil,"syscall","clts","sysret", "invd","wbinvd",nil,"ud1",nil,"$prefetch!Bm","femms","3dnowMrmu", --1x "movupsXrm|movssXrvm|movupdXrm|movsdXrvm", "movupsXmr|movssXmvr|movupdXmr|movsdXmvr", "movhlpsXrm$movlpsXrm|movsldupXrm|movlpdXrm|movddupXrm", "movlpsXmr||movlpdXmr", "unpcklpsXrvm||unpcklpdXrvm", "unpckhpsXrvm||unpckhpdXrvm", "movlhpsXrm$movhpsXrm|movshdupXrm|movhpdXrm", "movhpsXmr||movhpdXmr", "$prefetcht!Bm","hintnopVm","hintnopVm","hintnopVm", "hintnopVm","hintnopVm","hintnopVm","hintnopVm", --2x "movUmx$","movUmy$","movUxm$","movUym$","movUmz$",nil,"movUzm$",nil, "movapsXrm||movapdXrm", "movapsXmr||movapdXmr", "cvtpi2psXrMm|cvtsi2ssXrvVmt|cvtpi2pdXrMm|cvtsi2sdXrvVmt", "movntpsXmr|movntssXmr|movntpdXmr|movntsdXmr", "cvttps2piMrXm|cvttss2siVrXm|cvttpd2piMrXm|cvttsd2siVrXm", "cvtps2piMrXm|cvtss2siVrXm|cvtpd2piMrXm|cvtsd2siVrXm", "ucomissXrm||ucomisdXrm", "comissXrm||comisdXrm", --3x "wrmsr","rdtsc","rdmsr","rdpmc","sysenter","sysexit",nil,"getsec", "opc3*38",nil,"opc3*3a",nil,nil,nil,nil,nil, --4x "cmovoVrm","cmovnoVrm","cmovbVrm","cmovnbVrm", "cmovzVrm","cmovnzVrm","cmovbeVrm","cmovaVrm", "cmovsVrm","cmovnsVrm","cmovpeVrm","cmovpoVrm", "cmovlVrm","cmovgeVrm","cmovleVrm","cmovgVrm", --5x "movmskpsVrXm$||movmskpdVrXm$","sqrtpsXrm|sqrtssXrm|sqrtpdXrm|sqrtsdXrm", "rsqrtpsXrm|rsqrtssXrvm","rcppsXrm|rcpssXrvm", "andpsXrvm||andpdXrvm","andnpsXrvm||andnpdXrvm", "orpsXrvm||orpdXrvm","xorpsXrvm||xorpdXrvm", "addpsXrvm|addssXrvm|addpdXrvm|addsdXrvm","mulpsXrvm|mulssXrvm|mulpdXrvm|mulsdXrvm", "cvtps2pdXrm|cvtss2sdXrvm|cvtpd2psXrm|cvtsd2ssXrvm", "cvtdq2psXrm|cvttps2dqXrm|cvtps2dqXrm", "subpsXrvm|subssXrvm|subpdXrvm|subsdXrvm","minpsXrvm|minssXrvm|minpdXrvm|minsdXrvm", "divpsXrvm|divssXrvm|divpdXrvm|divsdXrvm","maxpsXrvm|maxssXrvm|maxpdXrvm|maxsdXrvm", --6x "punpcklbwPrvm","punpcklwdPrvm","punpckldqPrvm","packsswbPrvm", "pcmpgtbPrvm","pcmpgtwPrvm","pcmpgtdPrvm","packuswbPrvm", "punpckhbwPrvm","punpckhwdPrvm","punpckhdqPrvm","packssdwPrvm", "||punpcklqdqXrvm","||punpckhqdqXrvm", "movPrVSm","movqMrm|movdquXrm|movdqaXrm", --7x "pshufwMrmu|pshufhwXrmu|pshufdXrmu|pshuflwXrmu","pshiftw!Pvmu", "pshiftd!Pvmu","pshiftq!Mvmu||pshiftdq!Xvmu", "pcmpeqbPrvm","pcmpeqwPrvm","pcmpeqdPrvm","emms*|", "vmreadUmr||extrqXmuu$|insertqXrmuu$","vmwriteUrm||extrqXrm$|insertqXrm$", nil,nil, "||haddpdXrvm|haddpsXrvm","||hsubpdXrvm|hsubpsXrvm", "movVSmMr|movqXrm|movVSmXr","movqMmr|movdquXmr|movdqaXmr", --8x "joVj","jnoVj","jbVj","jnbVj","jzVj","jnzVj","jbeVj","jaVj", "jsVj","jnsVj","jpeVj","jpoVj","jlVj","jgeVj","jleVj","jgVj", --9x "setoBm","setnoBm","setbBm","setnbBm","setzBm","setnzBm","setbeBm","setaBm", "setsBm","setnsBm","setpeBm","setpoBm","setlBm","setgeBm","setleBm","setgBm", --Ax "push fs","pop fs","cpuid","btVmr","shldVmru","shldVmrc",nil,nil, "push gs","pop gs","rsm","btsVmr","shrdVmru","shrdVmrc","fxsave!Dmp","imulVrm", --Bx "cmpxchgBmr","cmpxchgVmr","$lssVrm","btrVmr", "$lfsVrm","$lgsVrm","movzxVrBmt","movzxVrWmt", "|popcntVrm","ud2Dp","bt!Vmu","btcVmr", "bsfVrm","bsrVrm|lzcntVrm|bsrWrm","movsxVrBmt","movsxVrWmt", --Cx "xaddBmr","xaddVmr", "cmppsXrvmu|cmpssXrvmu|cmppdXrvmu|cmpsdXrvmu","$movntiVmr|", "pinsrwPrvWmu","pextrwDrPmu", "shufpsXrvmu||shufpdXrvmu","$cmpxchg!Qmp", "bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR", --Dx "||addsubpdXrvm|addsubpsXrvm","psrlwPrvm","psrldPrvm","psrlqPrvm", "paddqPrvm","pmullwPrvm", "|movq2dqXrMm|movqXmr|movdq2qMrXm$","pmovmskbVrMm||pmovmskbVrXm", "psubusbPrvm","psubuswPrvm","pminubPrvm","pandPrvm", "paddusbPrvm","padduswPrvm","pmaxubPrvm","pandnPrvm", --Ex "pavgbPrvm","psrawPrvm","psradPrvm","pavgwPrvm", "pmulhuwPrvm","pmulhwPrvm", "|cvtdq2pdXrm|cvttpd2dqXrm|cvtpd2dqXrm","$movntqMmr||$movntdqXmr", "psubsbPrvm","psubswPrvm","pminswPrvm","porPrvm", "paddsbPrvm","paddswPrvm","pmaxswPrvm","pxorPrvm", --Fx "|||lddquXrm","psllwPrvm","pslldPrvm","psllqPrvm", "pmuludqPrvm","pmaddwdPrvm","psadbwPrvm","maskmovqMrm||maskmovdquXrm$", "psubbPrvm","psubwPrvm","psubdPrvm","psubqPrvm", "paddbPrvm","paddwPrvm","padddPrvm","ud", } assert(map_opc2[255] == "ud") -- Map for three-byte opcodes. Can't wait for their next invention. local map_opc3 = { ["38"] = { -- [66] 0f 38 xx --0x [0]="pshufbPrvm","phaddwPrvm","phadddPrvm","phaddswPrvm", "pmaddubswPrvm","phsubwPrvm","phsubdPrvm","phsubswPrvm", "psignbPrvm","psignwPrvm","psigndPrvm","pmulhrswPrvm", "||permilpsXrvm","||permilpdXrvm",nil,nil, --1x "||pblendvbXrma",nil,nil,nil, "||blendvpsXrma","||blendvpdXrma","||permpsXrvm","||ptestXrm", "||broadcastssXrm","||broadcastsdXrm","||broadcastf128XrlXm",nil, "pabsbPrm","pabswPrm","pabsdPrm",nil, --2x "||pmovsxbwXrm","||pmovsxbdXrm","||pmovsxbqXrm","||pmovsxwdXrm", "||pmovsxwqXrm","||pmovsxdqXrm",nil,nil, "||pmuldqXrvm","||pcmpeqqXrvm","||$movntdqaXrm","||packusdwXrvm", "||maskmovpsXrvm","||maskmovpdXrvm","||maskmovpsXmvr","||maskmovpdXmvr", --3x "||pmovzxbwXrm","||pmovzxbdXrm","||pmovzxbqXrm","||pmovzxwdXrm", "||pmovzxwqXrm","||pmovzxdqXrm","||permdXrvm","||pcmpgtqXrvm", "||pminsbXrvm","||pminsdXrvm","||pminuwXrvm","||pminudXrvm", "||pmaxsbXrvm","||pmaxsdXrvm","||pmaxuwXrvm","||pmaxudXrvm", --4x "||pmulddXrvm","||phminposuwXrm",nil,nil, nil,"||psrlvVSXrvm","||psravdXrvm","||psllvVSXrvm", --5x [0x58] = "||pbroadcastdXrlXm",[0x59] = "||pbroadcastqXrlXm", [0x5a] = "||broadcasti128XrlXm", --7x [0x78] = "||pbroadcastbXrlXm",[0x79] = "||pbroadcastwXrlXm", --8x [0x8c] = "||pmaskmovXrvVSm", [0x8e] = "||pmaskmovVSmXvr", --Dx [0xdc] = "||aesencXrvm", [0xdd] = "||aesenclastXrvm", [0xde] = "||aesdecXrvm", [0xdf] = "||aesdeclastXrvm", --Fx [0xf0] = "|||crc32TrBmt",[0xf1] = "|||crc32TrVmt", }, ["3a"] = { -- [66] 0f 3a xx --0x [0x00]="||permqXrmu","||permpdXrmu","||pblenddXrvmu",nil, "||permilpsXrmu","||permilpdXrmu","||perm2f128Xrvmu",nil, "||roundpsXrmu","||roundpdXrmu","||roundssXrvmu","||roundsdXrvmu", "||blendpsXrvmu","||blendpdXrvmu","||pblendwXrvmu","palignrPrvmu", --1x nil,nil,nil,nil, "||pextrbVmXru","||pextrwVmXru","||pextrVmSXru","||extractpsVmXru", "||insertf128XrvlXmu","||extractf128XlXmYru",nil,nil, nil,nil,nil,nil, --2x "||pinsrbXrvVmu","||insertpsXrvmu","||pinsrXrvVmuS",nil, --3x [0x38] = "||inserti128Xrvmu",[0x39] = "||extracti128XlXmYru", --4x [0x40] = "||dppsXrvmu", [0x41] = "||dppdXrvmu", [0x42] = "||mpsadbwXrvmu", [0x44] = "||pclmulqdqXrvmu", [0x46] = "||perm2i128Xrvmu", [0x4a] = "||blendvpsXrvmb",[0x4b] = "||blendvpdXrvmb", [0x4c] = "||pblendvbXrvmb", --6x [0x60] = "||pcmpestrmXrmu",[0x61] = "||pcmpestriXrmu", [0x62] = "||pcmpistrmXrmu",[0x63] = "||pcmpistriXrmu", [0xdf] = "||aeskeygenassistXrmu", }, } -- Map for VMX/SVM opcodes 0F 01 C0-FF (sgdt group with register operands). local map_opcvm = { [0xc1]="vmcall",[0xc2]="vmlaunch",[0xc3]="vmresume",[0xc4]="vmxoff", [0xc8]="monitor",[0xc9]="mwait", [0xd8]="vmrun",[0xd9]="vmmcall",[0xda]="vmload",[0xdb]="vmsave", [0xdc]="stgi",[0xdd]="clgi",[0xde]="skinit",[0xdf]="invlpga", [0xf8]="swapgs",[0xf9]="rdtscp", } -- Map for FP opcodes. And you thought stack machines are simple? local map_opcfp = { -- D8-DF 00-BF: opcodes with a memory operand. -- D8 [0]="faddFm","fmulFm","fcomFm","fcompFm","fsubFm","fsubrFm","fdivFm","fdivrFm", "fldFm",nil,"fstFm","fstpFm","fldenvVm","fldcwWm","fnstenvVm","fnstcwWm", -- DA "fiaddDm","fimulDm","ficomDm","ficompDm", "fisubDm","fisubrDm","fidivDm","fidivrDm", -- DB "fildDm","fisttpDm","fistDm","fistpDm",nil,"fld twordFmp",nil,"fstp twordFmp", -- DC "faddGm","fmulGm","fcomGm","fcompGm","fsubGm","fsubrGm","fdivGm","fdivrGm", -- DD "fldGm","fisttpQm","fstGm","fstpGm","frstorDmp",nil,"fnsaveDmp","fnstswWm", -- DE "fiaddWm","fimulWm","ficomWm","ficompWm", "fisubWm","fisubrWm","fidivWm","fidivrWm", -- DF "fildWm","fisttpWm","fistWm","fistpWm", "fbld twordFmp","fildQm","fbstp twordFmp","fistpQm", -- xx C0-FF: opcodes with a pseudo-register operand. -- D8 "faddFf","fmulFf","fcomFf","fcompFf","fsubFf","fsubrFf","fdivFf","fdivrFf", -- D9 "fldFf","fxchFf",{"fnop"},nil, {"fchs","fabs",nil,nil,"ftst","fxam"}, {"fld1","fldl2t","fldl2e","fldpi","fldlg2","fldln2","fldz"}, {"f2xm1","fyl2x","fptan","fpatan","fxtract","fprem1","fdecstp","fincstp"}, {"fprem","fyl2xp1","fsqrt","fsincos","frndint","fscale","fsin","fcos"}, -- DA "fcmovbFf","fcmoveFf","fcmovbeFf","fcmovuFf",nil,{nil,"fucompp"},nil,nil, -- DB "fcmovnbFf","fcmovneFf","fcmovnbeFf","fcmovnuFf", {nil,nil,"fnclex","fninit"},"fucomiFf","fcomiFf",nil, -- DC "fadd toFf","fmul toFf",nil,nil, "fsub toFf","fsubr toFf","fdivr toFf","fdiv toFf", -- DD "ffreeFf",nil,"fstFf","fstpFf","fucomFf","fucompFf",nil,nil, -- DE "faddpFf","fmulpFf",nil,{nil,"fcompp"}, "fsubrpFf","fsubpFf","fdivrpFf","fdivpFf", -- DF nil,nil,nil,nil,{"fnstsw ax"},"fucomipFf","fcomipFf",nil, } assert(map_opcfp[126] == "fcomipFf") -- Map for opcode groups. The subkey is sp from the ModRM byte. local map_opcgroup = { arith = { "add", "or", "adc", "sbb", "and", "sub", "xor", "cmp" }, shift = { "rol", "ror", "rcl", "rcr", "shl", "shr", "sal", "sar" }, testb = { "testBmi", "testBmi", "not", "neg", "mul", "imul", "div", "idiv" }, testv = { "testVmi", "testVmi", "not", "neg", "mul", "imul", "div", "idiv" }, incb = { "inc", "dec" }, incd = { "inc", "dec", "callUmp", "$call farDmp", "jmpUmp", "$jmp farDmp", "pushUm" }, sldt = { "sldt", "str", "lldt", "ltr", "verr", "verw" }, sgdt = { "vm*$sgdt", "vm*$sidt", "$lgdt", "vm*$lidt", "smsw", nil, "lmsw", "vm*$invlpg" }, bt = { nil, nil, nil, nil, "bt", "bts", "btr", "btc" }, cmpxchg = { nil, "sz*,cmpxchg8bQmp,cmpxchg16bXmp", nil, nil, nil, nil, "vmptrld|vmxon|vmclear", "vmptrst" }, pshiftw = { nil, nil, "psrlw", nil, "psraw", nil, "psllw" }, pshiftd = { nil, nil, "psrld", nil, "psrad", nil, "pslld" }, pshiftq = { nil, nil, "psrlq", nil, nil, nil, "psllq" }, pshiftdq = { nil, nil, "psrlq", "psrldq", nil, nil, "psllq", "pslldq" }, fxsave = { "$fxsave", "$fxrstor", "$ldmxcsr", "$stmxcsr", nil, "lfenceDp$", "mfenceDp$", "sfenceDp$clflush" }, prefetch = { "prefetch", "prefetchw" }, prefetcht = { "prefetchnta", "prefetcht0", "prefetcht1", "prefetcht2" }, } ------------------------------------------------------------------------------ -- Maps for register names. local map_regs = { B = { "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" }, B64 = { "al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" }, W = { "ax", "cx", "dx", "bx", "sp", "bp", "si", "di", "r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w" }, D = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d" }, Q = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" }, M = { "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7", "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7" }, -- No x64 ext! X = { "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15" }, Y = { "ymm0", "ymm1", "ymm2", "ymm3", "ymm4", "ymm5", "ymm6", "ymm7", "ymm8", "ymm9", "ymm10", "ymm11", "ymm12", "ymm13", "ymm14", "ymm15" }, } local map_segregs = { "es", "cs", "ss", "ds", "fs", "gs", "segr6", "segr7" } -- Maps for size names. local map_sz2n = { B = 1, W = 2, D = 4, Q = 8, M = 8, X = 16, Y = 32, } local map_sz2prefix = { B = "byte", W = "word", D = "dword", Q = "qword", M = "qword", X = "xword", Y = "yword", F = "dword", G = "qword", -- No need for sizes/register names for these two. } ------------------------------------------------------------------------------ -- Output a nicely formatted line with an opcode and operands. local function putop(ctx, text, operands) local code, pos, hex = ctx.code, ctx.pos, "" local hmax = ctx.hexdump if hmax > 0 then for i=ctx.start,pos-1 do hex = hex..format("%02X", byte(code, i, i)) end if #hex > hmax then hex = sub(hex, 1, hmax)..". " else hex = hex..rep(" ", hmax-#hex+2) end end if operands then text = text.." "..operands end if ctx.o16 then text = "o16 "..text; ctx.o16 = false end if ctx.a32 then text = "a32 "..text; ctx.a32 = false end if ctx.rep then text = ctx.rep.." "..text; ctx.rep = false end if ctx.rex then local t = (ctx.rexw and "w" or "")..(ctx.rexr and "r" or "").. (ctx.rexx and "x" or "")..(ctx.rexb and "b" or "").. (ctx.vexl and "l" or "") if ctx.vexv and ctx.vexv ~= 0 then t = t.."v"..ctx.vexv end if t ~= "" then text = ctx.rex.."."..t.." "..text elseif ctx.rex == "vex" then text = "v"..text end ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false ctx.rex = false; ctx.vexl = false; ctx.vexv = false end if ctx.seg then local text2, n = gsub(text, "%[", "["..ctx.seg..":") if n == 0 then text = ctx.seg.." "..text else text = text2 end ctx.seg = false end if ctx.lock then text = "lock "..text; ctx.lock = false end local imm = ctx.imm if imm then local sym = ctx.symtab[imm] if sym then text = text.."\t->"..sym end end ctx.out(format("%08x %s%s\n", ctx.addr+ctx.start, hex, text)) ctx.mrm = false ctx.vexv = false ctx.start = pos ctx.imm = nil end -- Clear all prefix flags. local function clearprefixes(ctx) ctx.o16 = false; ctx.seg = false; ctx.lock = false; ctx.rep = false ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false ctx.rex = false; ctx.a32 = false; ctx.vexl = false end -- Fallback for incomplete opcodes at the end. local function incomplete(ctx) ctx.pos = ctx.stop+1 clearprefixes(ctx) return putop(ctx, "(incomplete)") end -- Fallback for unknown opcodes. local function unknown(ctx) clearprefixes(ctx) return putop(ctx, "(unknown)") end -- Return an immediate of the specified size. local function getimm(ctx, pos, n) if pos+n-1 > ctx.stop then return incomplete(ctx) end local code = ctx.code if n == 1 then local b1 = byte(code, pos, pos) return b1 elseif n == 2 then local b1, b2 = byte(code, pos, pos+1) return b1+b2*256 else local b1, b2, b3, b4 = byte(code, pos, pos+3) local imm = b1+b2*256+b3*65536+b4*16777216 ctx.imm = imm return imm end end -- Process pattern string and generate the operands. local function putpat(ctx, name, pat) local operands, regs, sz, mode, sp, rm, sc, rx, sdisp local code, pos, stop, vexl = ctx.code, ctx.pos, ctx.stop, ctx.vexl -- Chars used: 1DFGIMPQRSTUVWXYabcdfgijlmoprstuvwxyz for p in gmatch(pat, ".") do local x = nil if p == "V" or p == "U" then if ctx.rexw then sz = "Q"; ctx.rexw = false elseif ctx.o16 then sz = "W"; ctx.o16 = false elseif p == "U" and ctx.x64 then sz = "Q" else sz = "D" end regs = map_regs[sz] elseif p == "T" then if ctx.rexw then sz = "Q"; ctx.rexw = false else sz = "D" end regs = map_regs[sz] elseif p == "B" then sz = "B" regs = ctx.rex and map_regs.B64 or map_regs.B elseif match(p, "[WDQMXYFG]") then sz = p if sz == "X" and vexl then sz = "Y"; ctx.vexl = false end regs = map_regs[sz] elseif p == "P" then sz = ctx.o16 and "X" or "M"; ctx.o16 = false if sz == "X" and vexl then sz = "Y"; ctx.vexl = false end regs = map_regs[sz] elseif p == "S" then name = name..lower(sz) elseif p == "s" then local imm = getimm(ctx, pos, 1); if not imm then return end x = imm <= 127 and format("+0x%02x", imm) or format("-0x%02x", 256-imm) pos = pos+1 elseif p == "u" then local imm = getimm(ctx, pos, 1); if not imm then return end x = format("0x%02x", imm) pos = pos+1 elseif p == "b" then local imm = getimm(ctx, pos, 1); if not imm then return end x = regs[imm/16+1] pos = pos+1 elseif p == "w" then local imm = getimm(ctx, pos, 2); if not imm then return end x = format("0x%x", imm) pos = pos+2 elseif p == "o" then -- [offset] if ctx.x64 then local imm1 = getimm(ctx, pos, 4); if not imm1 then return end local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end x = format("[0x%08x%08x]", imm2, imm1) pos = pos+8 else local imm = getimm(ctx, pos, 4); if not imm then return end x = format("[0x%08x]", imm) pos = pos+4 end elseif p == "i" or p == "I" then local n = map_sz2n[sz] if n == 8 and ctx.x64 and p == "I" then local imm1 = getimm(ctx, pos, 4); if not imm1 then return end local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end x = format("0x%08x%08x", imm2, imm1) else if n == 8 then n = 4 end local imm = getimm(ctx, pos, n); if not imm then return end if sz == "Q" and (imm < 0 or imm > 0x7fffffff) then imm = (0xffffffff+1)-imm x = format(imm > 65535 and "-0x%08x" or "-0x%x", imm) else x = format(imm > 65535 and "0x%08x" or "0x%x", imm) end end pos = pos+n elseif p == "j" then local n = map_sz2n[sz] if n == 8 then n = 4 end local imm = getimm(ctx, pos, n); if not imm then return end if sz == "B" and imm > 127 then imm = imm-256 elseif imm > 2147483647 then imm = imm-4294967296 end pos = pos+n imm = imm + pos + ctx.addr if imm > 4294967295 and not ctx.x64 then imm = imm-4294967296 end ctx.imm = imm if sz == "W" then x = format("word 0x%04x", imm%65536) elseif ctx.x64 then local lo = imm % 0x1000000 x = format("0x%02x%06x", (imm-lo) / 0x1000000, lo) else x = "0x"..tohex(imm) end elseif p == "R" then local r = byte(code, pos-1, pos-1)%8 if ctx.rexb then r = r + 8; ctx.rexb = false end x = regs[r+1] elseif p == "a" then x = regs[1] elseif p == "c" then x = "cl" elseif p == "d" then x = "dx" elseif p == "1" then x = "1" else if not mode then mode = ctx.mrm if not mode then if pos > stop then return incomplete(ctx) end mode = byte(code, pos, pos) pos = pos+1 end rm = mode%8; mode = (mode-rm)/8 sp = mode%8; mode = (mode-sp)/8 sdisp = "" if mode < 3 then if rm == 4 then if pos > stop then return incomplete(ctx) end sc = byte(code, pos, pos) pos = pos+1 rm = sc%8; sc = (sc-rm)/8 rx = sc%8; sc = (sc-rx)/8 if ctx.rexx then rx = rx + 8; ctx.rexx = false end if rx == 4 then rx = nil end end if mode > 0 or rm == 5 then local dsz = mode if dsz ~= 1 then dsz = 4 end local disp = getimm(ctx, pos, dsz); if not disp then return end if mode == 0 then rm = nil end if rm or rx or (not sc and ctx.x64 and not ctx.a32) then if dsz == 1 and disp > 127 then sdisp = format("-0x%x", 256-disp) elseif disp >= 0 and disp <= 0x7fffffff then sdisp = format("+0x%x", disp) else sdisp = format("-0x%x", (0xffffffff+1)-disp) end else sdisp = format(ctx.x64 and not ctx.a32 and not (disp >= 0 and disp <= 0x7fffffff) and "0xffffffff%08x" or "0x%08x", disp) end pos = pos+dsz end end if rm and ctx.rexb then rm = rm + 8; ctx.rexb = false end if ctx.rexr then sp = sp + 8; ctx.rexr = false end end if p == "m" then if mode == 3 then x = regs[rm+1] else local aregs = ctx.a32 and map_regs.D or ctx.aregs local srm, srx = "", "" if rm then srm = aregs[rm+1] elseif not sc and ctx.x64 and not ctx.a32 then srm = "rip" end ctx.a32 = false if rx then if rm then srm = srm.."+" end srx = aregs[rx+1] if sc > 0 then srx = srx.."*"..(2^sc) end end x = format("[%s%s%s]", srm, srx, sdisp) end if mode < 3 and (not match(pat, "[aRrgp]") or match(pat, "t")) then -- Yuck. x = map_sz2prefix[sz].." "..x end elseif p == "r" then x = regs[sp+1] elseif p == "g" then x = map_segregs[sp+1] elseif p == "p" then -- Suppress prefix. elseif p == "f" then x = "st"..rm elseif p == "x" then if sp == 0 and ctx.lock and not ctx.x64 then x = "CR8"; ctx.lock = false else x = "CR"..sp end elseif p == "v" then if ctx.vexv then x = regs[ctx.vexv+1]; ctx.vexv = false end elseif p == "y" then x = "DR"..sp elseif p == "z" then x = "TR"..sp elseif p == "l" then vexl = false elseif p == "t" then else error("bad pattern `"..pat.."'") end end if x then operands = operands and operands..", "..x or x end end ctx.pos = pos return putop(ctx, name, operands) end -- Forward declaration. local map_act -- Fetch and cache MRM byte. local function getmrm(ctx) local mrm = ctx.mrm if not mrm then local pos = ctx.pos if pos > ctx.stop then return nil end mrm = byte(ctx.code, pos, pos) ctx.pos = pos+1 ctx.mrm = mrm end return mrm end -- Dispatch to handler depending on pattern. local function dispatch(ctx, opat, patgrp) if not opat then return unknown(ctx) end if match(opat, "%|") then -- MMX/SSE variants depending on prefix. local p if ctx.rep then p = ctx.rep=="rep" and "%|([^%|]*)" or "%|[^%|]*%|[^%|]*%|([^%|]*)" ctx.rep = false elseif ctx.o16 then p = "%|[^%|]*%|([^%|]*)"; ctx.o16 = false else p = "^[^%|]*" end opat = match(opat, p) if not opat then return unknown(ctx) end -- ctx.rep = false; ctx.o16 = false --XXX fails for 66 f2 0f 38 f1 06 crc32 eax,WORD PTR [esi] --XXX remove in branches? end if match(opat, "%$") then -- reg$mem variants. local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end opat = match(opat, mrm >= 192 and "^[^%$]*" or "%$(.*)") if opat == "" then return unknown(ctx) end end if opat == "" then return unknown(ctx) end local name, pat = match(opat, "^([a-z0-9 ]*)(.*)") if pat == "" and patgrp then pat = patgrp end return map_act[sub(pat, 1, 1)](ctx, name, pat) end -- Get a pattern from an opcode map and dispatch to handler. local function dispatchmap(ctx, opcmap) local pos = ctx.pos local opat = opcmap[byte(ctx.code, pos, pos)] pos = pos + 1 ctx.pos = pos return dispatch(ctx, opat) end -- Map for action codes. The key is the first char after the name. map_act = { -- Simple opcodes without operands. [""] = function(ctx, name, pat) return putop(ctx, name) end, -- Operand size chars fall right through. B = putpat, W = putpat, D = putpat, Q = putpat, V = putpat, U = putpat, T = putpat, M = putpat, X = putpat, P = putpat, F = putpat, G = putpat, Y = putpat, -- Collect prefixes. [":"] = function(ctx, name, pat) ctx[pat == ":" and name or sub(pat, 2)] = name if ctx.pos - ctx.start > 5 then return unknown(ctx) end -- Limit #prefixes. end, -- Chain to special handler specified by name. ["*"] = function(ctx, name, pat) return map_act[name](ctx, name, sub(pat, 2)) end, -- Use named subtable for opcode group. ["!"] = function(ctx, name, pat) local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end return dispatch(ctx, map_opcgroup[name][((mrm-(mrm%8))/8)%8+1], sub(pat, 2)) end, -- o16,o32[,o64] variants. sz = function(ctx, name, pat) if ctx.o16 then ctx.o16 = false else pat = match(pat, ",(.*)") if ctx.rexw then local p = match(pat, ",(.*)") if p then pat = p; ctx.rexw = false end end end pat = match(pat, "^[^,]*") return dispatch(ctx, pat) end, -- Two-byte opcode dispatch. opc2 = function(ctx, name, pat) return dispatchmap(ctx, map_opc2) end, -- Three-byte opcode dispatch. opc3 = function(ctx, name, pat) return dispatchmap(ctx, map_opc3[pat]) end, -- VMX/SVM dispatch. vm = function(ctx, name, pat) return dispatch(ctx, map_opcvm[ctx.mrm]) end, -- Floating point opcode dispatch. fp = function(ctx, name, pat) local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end local rm = mrm%8 local idx = pat*8 + ((mrm-rm)/8)%8 if mrm >= 192 then idx = idx + 64 end local opat = map_opcfp[idx] if type(opat) == "table" then opat = opat[rm+1] end return dispatch(ctx, opat) end, -- REX prefix. rex = function(ctx, name, pat) if ctx.rex then return unknown(ctx) end -- Only 1 REX or VEX prefix allowed. for p in gmatch(pat, ".") do ctx["rex"..p] = true end ctx.rex = "rex" end, -- VEX prefix. vex = function(ctx, name, pat) if ctx.rex then return unknown(ctx) end -- Only 1 REX or VEX prefix allowed. ctx.rex = "vex" local pos = ctx.pos if ctx.mrm then ctx.mrm = nil pos = pos-1 end local b = byte(ctx.code, pos, pos) if not b then return incomplete(ctx) end pos = pos+1 if b < 128 then ctx.rexr = true end local m = 1 if pat == "3" then m = b%32; b = (b-m)/32 local nb = b%2; b = (b-nb)/2 if nb == 0 then ctx.rexb = true end local nx = b%2; b = (b-nx)/2 if nx == 0 then ctx.rexx = true end b = byte(ctx.code, pos, pos) if not b then return incomplete(ctx) end pos = pos+1 if b >= 128 then ctx.rexw = true end end ctx.pos = pos local map if m == 1 then map = map_opc2 elseif m == 2 then map = map_opc3["38"] elseif m == 3 then map = map_opc3["3a"] else return unknown(ctx) end local p = b%4; b = (b-p)/4 if p == 1 then ctx.o16 = "o16" elseif p == 2 then ctx.rep = "rep" elseif p == 3 then ctx.rep = "repne" end local l = b%2; b = (b-l)/2 if l ~= 0 then ctx.vexl = true end ctx.vexv = (-1-b)%16 return dispatchmap(ctx, map) end, -- Special case for nop with REX prefix. nop = function(ctx, name, pat) return dispatch(ctx, ctx.rex and pat or "nop") end, -- Special case for 0F 77. emms = function(ctx, name, pat) if ctx.rex ~= "vex" then return putop(ctx, "emms") elseif ctx.vexl then ctx.vexl = false return putop(ctx, "zeroall") else return putop(ctx, "zeroupper") end end, } ------------------------------------------------------------------------------ -- Disassemble a block of code. local function disass_block(ctx, ofs, len) if not ofs then ofs = 0 end local stop = len and ofs+len or #ctx.code ofs = ofs + 1 ctx.start = ofs ctx.pos = ofs ctx.stop = stop ctx.imm = nil ctx.mrm = false clearprefixes(ctx) while ctx.pos <= stop do dispatchmap(ctx, ctx.map1) end if ctx.pos ~= ctx.start then incomplete(ctx) end end -- Extended API: create a disassembler context. Then call ctx:disass(ofs, len). local function create(code, addr, out) local ctx = {} ctx.code = code ctx.addr = (addr or 0) - 1 ctx.out = out or io.write ctx.symtab = {} ctx.disass = disass_block ctx.hexdump = 16 ctx.x64 = false ctx.map1 = map_opc1_32 ctx.aregs = map_regs.D return ctx end local function create64(code, addr, out) local ctx = create(code, addr, out) ctx.x64 = true ctx.map1 = map_opc1_64 ctx.aregs = map_regs.Q return ctx end -- Simple API: disassemble code (a string) at address and output via out. local function disass(code, addr, out) create(code, addr, out):disass() end local function disass64(code, addr, out) create64(code, addr, out):disass() end -- Return register name for RID. local function regname(r) if r < 8 then return map_regs.D[r+1] end return map_regs.X[r-7] end local function regname64(r) if r < 16 then return map_regs.Q[r+1] end return map_regs.X[r-15] end -- Public module functions. return { create = create, create64 = create64, disass = disass, disass64 = disass64, regname = regname, regname64 = regname64 }
mit
Ninjistix/darkstar
scripts/globals/items/bunch_of_pamamas.lua
3
1046
----------------------------------------- -- ID: 4468 -- Item: Bunch of Pamamas -- Food Effect: 30Min, All Races ----------------------------------------- -- Strength -3 -- Intelligence 1 -- Additional Effect with Opo-Opo Crown -- HP 50 -- MP 50 -- CHR 14 -- Additional Effect with Kinkobo or -- Primate Staff -- DELAY -90 -- ACC 10 -- Additional Effect with Primate Staff +1 -- DELAY -80 -- ACC 12 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- 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; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4468); end; function onEffectGain(target, effect) target:addMod(MOD_STR, -3); target:addMod(MOD_INT, 1); end; function onEffectLose(target, effect) target:delMod(MOD_STR, -3); target:delMod(MOD_INT, 1); end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Quicksand_Caves/npcs/Treasure_Coffer.lua
5
4149
----------------------------------- -- Area: Quicksand Caves -- NPC: Treasure Coffer -- @zone 208 -- !pos 615 -6 -681 ----------------------------------- package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/Quicksand_Caves/TextIDs"); local TreasureType = "Coffer"; local TreasureLvL = 53; local TreasureMinLvL = 43; function onTrade(player,npc,trade) -- trade:hasItemQty(1054,1); -- Treasure Key -- trade:hasItemQty(1115,1); -- Skeleton Key -- trade:hasItemQty(1023,1); -- Living Key -- trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if ((trade:hasItemQty(1054,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then -- IMPORTANT ITEM: AF Keyitems, AF Items, & Map ----------- local mJob = player:getMainJob(); local zone = player:getZoneID(); if (player:hasKeyItem(MAP_OF_THE_QUICKSAND_CAVES) == false) then questItemNeeded = 3; end local listAF = getAFbyZone(zone); for nb = 1,#listAF,3 do if (player:getQuestStatus(JEUNO,listAF[nb + 1]) ~= QUEST_AVAILABLE and mJob == listAF[nb] and player:hasItem(listAF[nb + 2]) == false) then questItemNeeded = 2; break end end -------------------------------------- local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if (pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if (success ~= -2) then player:tradeComplete(); if (math.random() <= success) then -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); if (questItemNeeded == 3) then player:addKeyItem(MAP_OF_THE_QUICKSAND_CAVES); player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_THE_QUICKSAND_CAVES); -- Map of the Quicksand Caves (KI) elseif (questItemNeeded == 2) then for nb = 1,#listAF,3 do if (mJob == listAF[nb]) then player:addItem(listAF[nb + 2]); player:messageSpecial(ITEM_OBTAINED,listAF[nb + 2]); break end end else player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = cofferLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if (loot[1]=="gil") then player:addGil(loot[2]); player:messageSpecial(GIL_OBTAINED,loot[2]); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end end UpdateTreasureSpawnPoint(npc:getID()); else player:messageSpecial(CHEST_MIMIC); spawnMimic(zone,npc,player); UpdateTreasureSpawnPoint(npc:getID(), true); end end end end; function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1054); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Konschtat_Highlands/npcs/qm1.lua
4
1045
----------------------------------- -- 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"); ----------------------------------- function onTrade(player,npc,trade) end; 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; function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/mobskills/vitriolic_spray.lua
33
1046
--------------------------------------------- -- Vitriolic Spray -- Family: Wamouracampa -- Description: Expels a caustic stream at targets in a fan-shaped area of effect. Additional effect: Burn -- Type: Magical -- Utsusemi/Blink absorb: Wipes shadow -- Range: Cone -- Notes: Burn is 10-30/tic --------------------------------------------- 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_BURN; local power = math.random(10,30); MobStatusEffectMove(mob, target, typeEffect, power, 3, 60); local dmgmod = 1; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*2.7,ELE_FIRE,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_FIRE,MOBPARAM_WIPE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Mount_Zhayolm/npcs/Bapokk.lua
5
1146
----------------------------------- -- Area: Mount Zhayolm -- NPC: Bapokk -- Handles access to Alzadaal Ruins -- !pos -20 -6 276 61 ----------------------------------- package.loaded["scripts/zones/Mount_Zhayolm/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mount_Zhayolm/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) if (trade:getItemCount() == 1 and trade:hasItemQty(2185,1)) then -- Silver player:tradeComplete(); player:setPos(-20,-6,0,192); -- using the pos method until the problem below is fixed -- player:startEvent(163); -- << this CS goes black at the end, never fades in return 1; end end; function onTrigger(player,npc) -- Ruins -> Zhayolm if (player:getZPos() > -280) then player:startEvent(164); -- Zhayolm -> Ruins else player:startEvent(162); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
dafei2015/hugular_cstolua
Client/tools/luaTools/lua/jit/dis_x86.lua
74
29330
---------------------------------------------------------------------------- -- LuaJIT x86/x64 disassembler module. -- -- Copyright (C) 2005-2014 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- This is a helper module used by the LuaJIT machine code dumper module. -- -- Sending small code snippets to an external disassembler and mixing the -- output with our own stuff was too fragile. So I had to bite the bullet -- and write yet another x86 disassembler. Oh well ... -- -- The output format is very similar to what ndisasm generates. But it has -- been developed independently by looking at the opcode tables from the -- Intel and AMD manuals. The supported instruction set is quite extensive -- and reflects what a current generation Intel or AMD CPU implements in -- 32 bit and 64 bit mode. Yes, this includes MMX, SSE, SSE2, SSE3, SSSE3, -- SSE4.1, SSE4.2, SSE4a and even privileged and hypervisor (VMX/SVM) -- instructions. -- -- Notes: -- * The (useless) a16 prefix, 3DNow and pre-586 opcodes are unsupported. -- * No attempt at optimization has been made -- it's fast enough for my needs. -- * The public API may change when more architectures are added. ------------------------------------------------------------------------------ local type = type local sub, byte, format = string.sub, string.byte, string.format local match, gmatch, gsub = string.match, string.gmatch, string.gsub local lower, rep = string.lower, string.rep -- Map for 1st opcode byte in 32 bit mode. Ugly? Well ... read on. local map_opc1_32 = { --0x [0]="addBmr","addVmr","addBrm","addVrm","addBai","addVai","push es","pop es", "orBmr","orVmr","orBrm","orVrm","orBai","orVai","push cs","opc2*", --1x "adcBmr","adcVmr","adcBrm","adcVrm","adcBai","adcVai","push ss","pop ss", "sbbBmr","sbbVmr","sbbBrm","sbbVrm","sbbBai","sbbVai","push ds","pop ds", --2x "andBmr","andVmr","andBrm","andVrm","andBai","andVai","es:seg","daa", "subBmr","subVmr","subBrm","subVrm","subBai","subVai","cs:seg","das", --3x "xorBmr","xorVmr","xorBrm","xorVrm","xorBai","xorVai","ss:seg","aaa", "cmpBmr","cmpVmr","cmpBrm","cmpVrm","cmpBai","cmpVai","ds:seg","aas", --4x "incVR","incVR","incVR","incVR","incVR","incVR","incVR","incVR", "decVR","decVR","decVR","decVR","decVR","decVR","decVR","decVR", --5x "pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR", "popUR","popUR","popUR","popUR","popUR","popUR","popUR","popUR", --6x "sz*pushaw,pusha","sz*popaw,popa","boundVrm","arplWmr", "fs:seg","gs:seg","o16:","a16", "pushUi","imulVrmi","pushBs","imulVrms", "insb","insVS","outsb","outsVS", --7x "joBj","jnoBj","jbBj","jnbBj","jzBj","jnzBj","jbeBj","jaBj", "jsBj","jnsBj","jpeBj","jpoBj","jlBj","jgeBj","jleBj","jgBj", --8x "arith!Bmi","arith!Vmi","arith!Bmi","arith!Vms", "testBmr","testVmr","xchgBrm","xchgVrm", "movBmr","movVmr","movBrm","movVrm", "movVmg","leaVrm","movWgm","popUm", --9x "nop*xchgVaR|pause|xchgWaR|repne nop","xchgVaR","xchgVaR","xchgVaR", "xchgVaR","xchgVaR","xchgVaR","xchgVaR", "sz*cbw,cwde,cdqe","sz*cwd,cdq,cqo","call farViw","wait", "sz*pushfw,pushf","sz*popfw,popf","sahf","lahf", --Ax "movBao","movVao","movBoa","movVoa", "movsb","movsVS","cmpsb","cmpsVS", "testBai","testVai","stosb","stosVS", "lodsb","lodsVS","scasb","scasVS", --Bx "movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi", "movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI", --Cx "shift!Bmu","shift!Vmu","retBw","ret","$lesVrm","$ldsVrm","movBmi","movVmi", "enterBwu","leave","retfBw","retf","int3","intBu","into","iretVS", --Dx "shift!Bm1","shift!Vm1","shift!Bmc","shift!Vmc","aamBu","aadBu","salc","xlatb", "fp*0","fp*1","fp*2","fp*3","fp*4","fp*5","fp*6","fp*7", --Ex "loopneBj","loopeBj","loopBj","sz*jcxzBj,jecxzBj,jrcxzBj", "inBau","inVau","outBua","outVua", "callVj","jmpVj","jmp farViw","jmpBj","inBad","inVad","outBda","outVda", --Fx "lock:","int1","repne:rep","rep:","hlt","cmc","testb!Bm","testv!Vm", "clc","stc","cli","sti","cld","std","incb!Bm","incd!Vm", } assert(#map_opc1_32 == 255) -- Map for 1st opcode byte in 64 bit mode (overrides only). local map_opc1_64 = setmetatable({ [0x06]=false, [0x07]=false, [0x0e]=false, [0x16]=false, [0x17]=false, [0x1e]=false, [0x1f]=false, [0x27]=false, [0x2f]=false, [0x37]=false, [0x3f]=false, [0x60]=false, [0x61]=false, [0x62]=false, [0x63]="movsxdVrDmt", [0x67]="a32:", [0x40]="rex*", [0x41]="rex*b", [0x42]="rex*x", [0x43]="rex*xb", [0x44]="rex*r", [0x45]="rex*rb", [0x46]="rex*rx", [0x47]="rex*rxb", [0x48]="rex*w", [0x49]="rex*wb", [0x4a]="rex*wx", [0x4b]="rex*wxb", [0x4c]="rex*wr", [0x4d]="rex*wrb", [0x4e]="rex*wrx", [0x4f]="rex*wrxb", [0x82]=false, [0x9a]=false, [0xc4]=false, [0xc5]=false, [0xce]=false, [0xd4]=false, [0xd5]=false, [0xd6]=false, [0xea]=false, }, { __index = map_opc1_32 }) -- Map for 2nd opcode byte (0F xx). True CISC hell. Hey, I told you. -- Prefix dependent MMX/SSE opcodes: (none)|rep|o16|repne, -|F3|66|F2 local map_opc2 = { --0x [0]="sldt!Dmp","sgdt!Ump","larVrm","lslVrm",nil,"syscall","clts","sysret", "invd","wbinvd",nil,"ud1",nil,"$prefetch!Bm","femms","3dnowMrmu", --1x "movupsXrm|movssXrm|movupdXrm|movsdXrm", "movupsXmr|movssXmr|movupdXmr|movsdXmr", "movhlpsXrm$movlpsXrm|movsldupXrm|movlpdXrm|movddupXrm", "movlpsXmr||movlpdXmr", "unpcklpsXrm||unpcklpdXrm", "unpckhpsXrm||unpckhpdXrm", "movlhpsXrm$movhpsXrm|movshdupXrm|movhpdXrm", "movhpsXmr||movhpdXmr", "$prefetcht!Bm","hintnopVm","hintnopVm","hintnopVm", "hintnopVm","hintnopVm","hintnopVm","hintnopVm", --2x "movUmx$","movUmy$","movUxm$","movUym$","movUmz$",nil,"movUzm$",nil, "movapsXrm||movapdXrm", "movapsXmr||movapdXmr", "cvtpi2psXrMm|cvtsi2ssXrVmt|cvtpi2pdXrMm|cvtsi2sdXrVmt", "movntpsXmr|movntssXmr|movntpdXmr|movntsdXmr", "cvttps2piMrXm|cvttss2siVrXm|cvttpd2piMrXm|cvttsd2siVrXm", "cvtps2piMrXm|cvtss2siVrXm|cvtpd2piMrXm|cvtsd2siVrXm", "ucomissXrm||ucomisdXrm", "comissXrm||comisdXrm", --3x "wrmsr","rdtsc","rdmsr","rdpmc","sysenter","sysexit",nil,"getsec", "opc3*38",nil,"opc3*3a",nil,nil,nil,nil,nil, --4x "cmovoVrm","cmovnoVrm","cmovbVrm","cmovnbVrm", "cmovzVrm","cmovnzVrm","cmovbeVrm","cmovaVrm", "cmovsVrm","cmovnsVrm","cmovpeVrm","cmovpoVrm", "cmovlVrm","cmovgeVrm","cmovleVrm","cmovgVrm", --5x "movmskpsVrXm$||movmskpdVrXm$","sqrtpsXrm|sqrtssXrm|sqrtpdXrm|sqrtsdXrm", "rsqrtpsXrm|rsqrtssXrm","rcppsXrm|rcpssXrm", "andpsXrm||andpdXrm","andnpsXrm||andnpdXrm", "orpsXrm||orpdXrm","xorpsXrm||xorpdXrm", "addpsXrm|addssXrm|addpdXrm|addsdXrm","mulpsXrm|mulssXrm|mulpdXrm|mulsdXrm", "cvtps2pdXrm|cvtss2sdXrm|cvtpd2psXrm|cvtsd2ssXrm", "cvtdq2psXrm|cvttps2dqXrm|cvtps2dqXrm", "subpsXrm|subssXrm|subpdXrm|subsdXrm","minpsXrm|minssXrm|minpdXrm|minsdXrm", "divpsXrm|divssXrm|divpdXrm|divsdXrm","maxpsXrm|maxssXrm|maxpdXrm|maxsdXrm", --6x "punpcklbwPrm","punpcklwdPrm","punpckldqPrm","packsswbPrm", "pcmpgtbPrm","pcmpgtwPrm","pcmpgtdPrm","packuswbPrm", "punpckhbwPrm","punpckhwdPrm","punpckhdqPrm","packssdwPrm", "||punpcklqdqXrm","||punpckhqdqXrm", "movPrVSm","movqMrm|movdquXrm|movdqaXrm", --7x "pshufwMrmu|pshufhwXrmu|pshufdXrmu|pshuflwXrmu","pshiftw!Pmu", "pshiftd!Pmu","pshiftq!Mmu||pshiftdq!Xmu", "pcmpeqbPrm","pcmpeqwPrm","pcmpeqdPrm","emms|", "vmreadUmr||extrqXmuu$|insertqXrmuu$","vmwriteUrm||extrqXrm$|insertqXrm$", nil,nil, "||haddpdXrm|haddpsXrm","||hsubpdXrm|hsubpsXrm", "movVSmMr|movqXrm|movVSmXr","movqMmr|movdquXmr|movdqaXmr", --8x "joVj","jnoVj","jbVj","jnbVj","jzVj","jnzVj","jbeVj","jaVj", "jsVj","jnsVj","jpeVj","jpoVj","jlVj","jgeVj","jleVj","jgVj", --9x "setoBm","setnoBm","setbBm","setnbBm","setzBm","setnzBm","setbeBm","setaBm", "setsBm","setnsBm","setpeBm","setpoBm","setlBm","setgeBm","setleBm","setgBm", --Ax "push fs","pop fs","cpuid","btVmr","shldVmru","shldVmrc",nil,nil, "push gs","pop gs","rsm","btsVmr","shrdVmru","shrdVmrc","fxsave!Dmp","imulVrm", --Bx "cmpxchgBmr","cmpxchgVmr","$lssVrm","btrVmr", "$lfsVrm","$lgsVrm","movzxVrBmt","movzxVrWmt", "|popcntVrm","ud2Dp","bt!Vmu","btcVmr", "bsfVrm","bsrVrm|lzcntVrm|bsrWrm","movsxVrBmt","movsxVrWmt", --Cx "xaddBmr","xaddVmr", "cmppsXrmu|cmpssXrmu|cmppdXrmu|cmpsdXrmu","$movntiVmr|", "pinsrwPrWmu","pextrwDrPmu", "shufpsXrmu||shufpdXrmu","$cmpxchg!Qmp", "bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR", --Dx "||addsubpdXrm|addsubpsXrm","psrlwPrm","psrldPrm","psrlqPrm", "paddqPrm","pmullwPrm", "|movq2dqXrMm|movqXmr|movdq2qMrXm$","pmovmskbVrMm||pmovmskbVrXm", "psubusbPrm","psubuswPrm","pminubPrm","pandPrm", "paddusbPrm","padduswPrm","pmaxubPrm","pandnPrm", --Ex "pavgbPrm","psrawPrm","psradPrm","pavgwPrm", "pmulhuwPrm","pmulhwPrm", "|cvtdq2pdXrm|cvttpd2dqXrm|cvtpd2dqXrm","$movntqMmr||$movntdqXmr", "psubsbPrm","psubswPrm","pminswPrm","porPrm", "paddsbPrm","paddswPrm","pmaxswPrm","pxorPrm", --Fx "|||lddquXrm","psllwPrm","pslldPrm","psllqPrm", "pmuludqPrm","pmaddwdPrm","psadbwPrm","maskmovqMrm||maskmovdquXrm$", "psubbPrm","psubwPrm","psubdPrm","psubqPrm", "paddbPrm","paddwPrm","padddPrm","ud", } assert(map_opc2[255] == "ud") -- Map for three-byte opcodes. Can't wait for their next invention. local map_opc3 = { ["38"] = { -- [66] 0f 38 xx --0x [0]="pshufbPrm","phaddwPrm","phadddPrm","phaddswPrm", "pmaddubswPrm","phsubwPrm","phsubdPrm","phsubswPrm", "psignbPrm","psignwPrm","psigndPrm","pmulhrswPrm", nil,nil,nil,nil, --1x "||pblendvbXrma",nil,nil,nil, "||blendvpsXrma","||blendvpdXrma",nil,"||ptestXrm", nil,nil,nil,nil, "pabsbPrm","pabswPrm","pabsdPrm",nil, --2x "||pmovsxbwXrm","||pmovsxbdXrm","||pmovsxbqXrm","||pmovsxwdXrm", "||pmovsxwqXrm","||pmovsxdqXrm",nil,nil, "||pmuldqXrm","||pcmpeqqXrm","||$movntdqaXrm","||packusdwXrm", nil,nil,nil,nil, --3x "||pmovzxbwXrm","||pmovzxbdXrm","||pmovzxbqXrm","||pmovzxwdXrm", "||pmovzxwqXrm","||pmovzxdqXrm",nil,"||pcmpgtqXrm", "||pminsbXrm","||pminsdXrm","||pminuwXrm","||pminudXrm", "||pmaxsbXrm","||pmaxsdXrm","||pmaxuwXrm","||pmaxudXrm", --4x "||pmulddXrm","||phminposuwXrm", --Fx [0xf0] = "|||crc32TrBmt",[0xf1] = "|||crc32TrVmt", }, ["3a"] = { -- [66] 0f 3a xx --0x [0x00]=nil,nil,nil,nil,nil,nil,nil,nil, "||roundpsXrmu","||roundpdXrmu","||roundssXrmu","||roundsdXrmu", "||blendpsXrmu","||blendpdXrmu","||pblendwXrmu","palignrPrmu", --1x nil,nil,nil,nil, "||pextrbVmXru","||pextrwVmXru","||pextrVmSXru","||extractpsVmXru", nil,nil,nil,nil,nil,nil,nil,nil, --2x "||pinsrbXrVmu","||insertpsXrmu","||pinsrXrVmuS",nil, --4x [0x40] = "||dppsXrmu", [0x41] = "||dppdXrmu", [0x42] = "||mpsadbwXrmu", --6x [0x60] = "||pcmpestrmXrmu",[0x61] = "||pcmpestriXrmu", [0x62] = "||pcmpistrmXrmu",[0x63] = "||pcmpistriXrmu", }, } -- Map for VMX/SVM opcodes 0F 01 C0-FF (sgdt group with register operands). local map_opcvm = { [0xc1]="vmcall",[0xc2]="vmlaunch",[0xc3]="vmresume",[0xc4]="vmxoff", [0xc8]="monitor",[0xc9]="mwait", [0xd8]="vmrun",[0xd9]="vmmcall",[0xda]="vmload",[0xdb]="vmsave", [0xdc]="stgi",[0xdd]="clgi",[0xde]="skinit",[0xdf]="invlpga", [0xf8]="swapgs",[0xf9]="rdtscp", } -- Map for FP opcodes. And you thought stack machines are simple? local map_opcfp = { -- D8-DF 00-BF: opcodes with a memory operand. -- D8 [0]="faddFm","fmulFm","fcomFm","fcompFm","fsubFm","fsubrFm","fdivFm","fdivrFm", "fldFm",nil,"fstFm","fstpFm","fldenvVm","fldcwWm","fnstenvVm","fnstcwWm", -- DA "fiaddDm","fimulDm","ficomDm","ficompDm", "fisubDm","fisubrDm","fidivDm","fidivrDm", -- DB "fildDm","fisttpDm","fistDm","fistpDm",nil,"fld twordFmp",nil,"fstp twordFmp", -- DC "faddGm","fmulGm","fcomGm","fcompGm","fsubGm","fsubrGm","fdivGm","fdivrGm", -- DD "fldGm","fisttpQm","fstGm","fstpGm","frstorDmp",nil,"fnsaveDmp","fnstswWm", -- DE "fiaddWm","fimulWm","ficomWm","ficompWm", "fisubWm","fisubrWm","fidivWm","fidivrWm", -- DF "fildWm","fisttpWm","fistWm","fistpWm", "fbld twordFmp","fildQm","fbstp twordFmp","fistpQm", -- xx C0-FF: opcodes with a pseudo-register operand. -- D8 "faddFf","fmulFf","fcomFf","fcompFf","fsubFf","fsubrFf","fdivFf","fdivrFf", -- D9 "fldFf","fxchFf",{"fnop"},nil, {"fchs","fabs",nil,nil,"ftst","fxam"}, {"fld1","fldl2t","fldl2e","fldpi","fldlg2","fldln2","fldz"}, {"f2xm1","fyl2x","fptan","fpatan","fxtract","fprem1","fdecstp","fincstp"}, {"fprem","fyl2xp1","fsqrt","fsincos","frndint","fscale","fsin","fcos"}, -- DA "fcmovbFf","fcmoveFf","fcmovbeFf","fcmovuFf",nil,{nil,"fucompp"},nil,nil, -- DB "fcmovnbFf","fcmovneFf","fcmovnbeFf","fcmovnuFf", {nil,nil,"fnclex","fninit"},"fucomiFf","fcomiFf",nil, -- DC "fadd toFf","fmul toFf",nil,nil, "fsub toFf","fsubr toFf","fdivr toFf","fdiv toFf", -- DD "ffreeFf",nil,"fstFf","fstpFf","fucomFf","fucompFf",nil,nil, -- DE "faddpFf","fmulpFf",nil,{nil,"fcompp"}, "fsubrpFf","fsubpFf","fdivrpFf","fdivpFf", -- DF nil,nil,nil,nil,{"fnstsw ax"},"fucomipFf","fcomipFf",nil, } assert(map_opcfp[126] == "fcomipFf") -- Map for opcode groups. The subkey is sp from the ModRM byte. local map_opcgroup = { arith = { "add", "or", "adc", "sbb", "and", "sub", "xor", "cmp" }, shift = { "rol", "ror", "rcl", "rcr", "shl", "shr", "sal", "sar" }, testb = { "testBmi", "testBmi", "not", "neg", "mul", "imul", "div", "idiv" }, testv = { "testVmi", "testVmi", "not", "neg", "mul", "imul", "div", "idiv" }, incb = { "inc", "dec" }, incd = { "inc", "dec", "callUmp", "$call farDmp", "jmpUmp", "$jmp farDmp", "pushUm" }, sldt = { "sldt", "str", "lldt", "ltr", "verr", "verw" }, sgdt = { "vm*$sgdt", "vm*$sidt", "$lgdt", "vm*$lidt", "smsw", nil, "lmsw", "vm*$invlpg" }, bt = { nil, nil, nil, nil, "bt", "bts", "btr", "btc" }, cmpxchg = { nil, "sz*,cmpxchg8bQmp,cmpxchg16bXmp", nil, nil, nil, nil, "vmptrld|vmxon|vmclear", "vmptrst" }, pshiftw = { nil, nil, "psrlw", nil, "psraw", nil, "psllw" }, pshiftd = { nil, nil, "psrld", nil, "psrad", nil, "pslld" }, pshiftq = { nil, nil, "psrlq", nil, nil, nil, "psllq" }, pshiftdq = { nil, nil, "psrlq", "psrldq", nil, nil, "psllq", "pslldq" }, fxsave = { "$fxsave", "$fxrstor", "$ldmxcsr", "$stmxcsr", nil, "lfenceDp$", "mfenceDp$", "sfenceDp$clflush" }, prefetch = { "prefetch", "prefetchw" }, prefetcht = { "prefetchnta", "prefetcht0", "prefetcht1", "prefetcht2" }, } ------------------------------------------------------------------------------ -- Maps for register names. local map_regs = { B = { "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" }, B64 = { "al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" }, W = { "ax", "cx", "dx", "bx", "sp", "bp", "si", "di", "r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w" }, D = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d" }, Q = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" }, M = { "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7", "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7" }, -- No x64 ext! X = { "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15" }, } local map_segregs = { "es", "cs", "ss", "ds", "fs", "gs", "segr6", "segr7" } -- Maps for size names. local map_sz2n = { B = 1, W = 2, D = 4, Q = 8, M = 8, X = 16, } local map_sz2prefix = { B = "byte", W = "word", D = "dword", Q = "qword", M = "qword", X = "xword", F = "dword", G = "qword", -- No need for sizes/register names for these two. } ------------------------------------------------------------------------------ -- Output a nicely formatted line with an opcode and operands. local function putop(ctx, text, operands) local code, pos, hex = ctx.code, ctx.pos, "" local hmax = ctx.hexdump if hmax > 0 then for i=ctx.start,pos-1 do hex = hex..format("%02X", byte(code, i, i)) end if #hex > hmax then hex = sub(hex, 1, hmax)..". " else hex = hex..rep(" ", hmax-#hex+2) end end if operands then text = text.." "..operands end if ctx.o16 then text = "o16 "..text; ctx.o16 = false end if ctx.a32 then text = "a32 "..text; ctx.a32 = false end if ctx.rep then text = ctx.rep.." "..text; ctx.rep = false end if ctx.rex then local t = (ctx.rexw and "w" or "")..(ctx.rexr and "r" or "").. (ctx.rexx and "x" or "")..(ctx.rexb and "b" or "") if t ~= "" then text = "rex."..t.." "..text end ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false ctx.rex = false end if ctx.seg then local text2, n = gsub(text, "%[", "["..ctx.seg..":") if n == 0 then text = ctx.seg.." "..text else text = text2 end ctx.seg = false end if ctx.lock then text = "lock "..text; ctx.lock = false end local imm = ctx.imm if imm then local sym = ctx.symtab[imm] if sym then text = text.."\t->"..sym end end ctx.out(format("%08x %s%s\n", ctx.addr+ctx.start, hex, text)) ctx.mrm = false ctx.start = pos ctx.imm = nil end -- Clear all prefix flags. local function clearprefixes(ctx) ctx.o16 = false; ctx.seg = false; ctx.lock = false; ctx.rep = false ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false ctx.rex = false; ctx.a32 = false end -- Fallback for incomplete opcodes at the end. local function incomplete(ctx) ctx.pos = ctx.stop+1 clearprefixes(ctx) return putop(ctx, "(incomplete)") end -- Fallback for unknown opcodes. local function unknown(ctx) clearprefixes(ctx) return putop(ctx, "(unknown)") end -- Return an immediate of the specified size. local function getimm(ctx, pos, n) if pos+n-1 > ctx.stop then return incomplete(ctx) end local code = ctx.code if n == 1 then local b1 = byte(code, pos, pos) return b1 elseif n == 2 then local b1, b2 = byte(code, pos, pos+1) return b1+b2*256 else local b1, b2, b3, b4 = byte(code, pos, pos+3) local imm = b1+b2*256+b3*65536+b4*16777216 ctx.imm = imm return imm end end -- Process pattern string and generate the operands. local function putpat(ctx, name, pat) local operands, regs, sz, mode, sp, rm, sc, rx, sdisp local code, pos, stop = ctx.code, ctx.pos, ctx.stop -- Chars used: 1DFGIMPQRSTUVWXacdfgijmoprstuwxyz for p in gmatch(pat, ".") do local x = nil if p == "V" or p == "U" then if ctx.rexw then sz = "Q"; ctx.rexw = false elseif ctx.o16 then sz = "W"; ctx.o16 = false elseif p == "U" and ctx.x64 then sz = "Q" else sz = "D" end regs = map_regs[sz] elseif p == "T" then if ctx.rexw then sz = "Q"; ctx.rexw = false else sz = "D" end regs = map_regs[sz] elseif p == "B" then sz = "B" regs = ctx.rex and map_regs.B64 or map_regs.B elseif match(p, "[WDQMXFG]") then sz = p regs = map_regs[sz] elseif p == "P" then sz = ctx.o16 and "X" or "M"; ctx.o16 = false regs = map_regs[sz] elseif p == "S" then name = name..lower(sz) elseif p == "s" then local imm = getimm(ctx, pos, 1); if not imm then return end x = imm <= 127 and format("+0x%02x", imm) or format("-0x%02x", 256-imm) pos = pos+1 elseif p == "u" then local imm = getimm(ctx, pos, 1); if not imm then return end x = format("0x%02x", imm) pos = pos+1 elseif p == "w" then local imm = getimm(ctx, pos, 2); if not imm then return end x = format("0x%x", imm) pos = pos+2 elseif p == "o" then -- [offset] if ctx.x64 then local imm1 = getimm(ctx, pos, 4); if not imm1 then return end local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end x = format("[0x%08x%08x]", imm2, imm1) pos = pos+8 else local imm = getimm(ctx, pos, 4); if not imm then return end x = format("[0x%08x]", imm) pos = pos+4 end elseif p == "i" or p == "I" then local n = map_sz2n[sz] if n == 8 and ctx.x64 and p == "I" then local imm1 = getimm(ctx, pos, 4); if not imm1 then return end local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end x = format("0x%08x%08x", imm2, imm1) else if n == 8 then n = 4 end local imm = getimm(ctx, pos, n); if not imm then return end if sz == "Q" and (imm < 0 or imm > 0x7fffffff) then imm = (0xffffffff+1)-imm x = format(imm > 65535 and "-0x%08x" or "-0x%x", imm) else x = format(imm > 65535 and "0x%08x" or "0x%x", imm) end end pos = pos+n elseif p == "j" then local n = map_sz2n[sz] if n == 8 then n = 4 end local imm = getimm(ctx, pos, n); if not imm then return end if sz == "B" and imm > 127 then imm = imm-256 elseif imm > 2147483647 then imm = imm-4294967296 end pos = pos+n imm = imm + pos + ctx.addr if imm > 4294967295 and not ctx.x64 then imm = imm-4294967296 end ctx.imm = imm if sz == "W" then x = format("word 0x%04x", imm%65536) elseif ctx.x64 then local lo = imm % 0x1000000 x = format("0x%02x%06x", (imm-lo) / 0x1000000, lo) else x = format("0x%08x", imm) end elseif p == "R" then local r = byte(code, pos-1, pos-1)%8 if ctx.rexb then r = r + 8; ctx.rexb = false end x = regs[r+1] elseif p == "a" then x = regs[1] elseif p == "c" then x = "cl" elseif p == "d" then x = "dx" elseif p == "1" then x = "1" else if not mode then mode = ctx.mrm if not mode then if pos > stop then return incomplete(ctx) end mode = byte(code, pos, pos) pos = pos+1 end rm = mode%8; mode = (mode-rm)/8 sp = mode%8; mode = (mode-sp)/8 sdisp = "" if mode < 3 then if rm == 4 then if pos > stop then return incomplete(ctx) end sc = byte(code, pos, pos) pos = pos+1 rm = sc%8; sc = (sc-rm)/8 rx = sc%8; sc = (sc-rx)/8 if ctx.rexx then rx = rx + 8; ctx.rexx = false end if rx == 4 then rx = nil end end if mode > 0 or rm == 5 then local dsz = mode if dsz ~= 1 then dsz = 4 end local disp = getimm(ctx, pos, dsz); if not disp then return end if mode == 0 then rm = nil end if rm or rx or (not sc and ctx.x64 and not ctx.a32) then if dsz == 1 and disp > 127 then sdisp = format("-0x%x", 256-disp) elseif disp >= 0 and disp <= 0x7fffffff then sdisp = format("+0x%x", disp) else sdisp = format("-0x%x", (0xffffffff+1)-disp) end else sdisp = format(ctx.x64 and not ctx.a32 and not (disp >= 0 and disp <= 0x7fffffff) and "0xffffffff%08x" or "0x%08x", disp) end pos = pos+dsz end end if rm and ctx.rexb then rm = rm + 8; ctx.rexb = false end if ctx.rexr then sp = sp + 8; ctx.rexr = false end end if p == "m" then if mode == 3 then x = regs[rm+1] else local aregs = ctx.a32 and map_regs.D or ctx.aregs local srm, srx = "", "" if rm then srm = aregs[rm+1] elseif not sc and ctx.x64 and not ctx.a32 then srm = "rip" end ctx.a32 = false if rx then if rm then srm = srm.."+" end srx = aregs[rx+1] if sc > 0 then srx = srx.."*"..(2^sc) end end x = format("[%s%s%s]", srm, srx, sdisp) end if mode < 3 and (not match(pat, "[aRrgp]") or match(pat, "t")) then -- Yuck. x = map_sz2prefix[sz].." "..x end elseif p == "r" then x = regs[sp+1] elseif p == "g" then x = map_segregs[sp+1] elseif p == "p" then -- Suppress prefix. elseif p == "f" then x = "st"..rm elseif p == "x" then if sp == 0 and ctx.lock and not ctx.x64 then x = "CR8"; ctx.lock = false else x = "CR"..sp end elseif p == "y" then x = "DR"..sp elseif p == "z" then x = "TR"..sp elseif p == "t" then else error("bad pattern `"..pat.."'") end end if x then operands = operands and operands..", "..x or x end end ctx.pos = pos return putop(ctx, name, operands) end -- Forward declaration. local map_act -- Fetch and cache MRM byte. local function getmrm(ctx) local mrm = ctx.mrm if not mrm then local pos = ctx.pos if pos > ctx.stop then return nil end mrm = byte(ctx.code, pos, pos) ctx.pos = pos+1 ctx.mrm = mrm end return mrm end -- Dispatch to handler depending on pattern. local function dispatch(ctx, opat, patgrp) if not opat then return unknown(ctx) end if match(opat, "%|") then -- MMX/SSE variants depending on prefix. local p if ctx.rep then p = ctx.rep=="rep" and "%|([^%|]*)" or "%|[^%|]*%|[^%|]*%|([^%|]*)" ctx.rep = false elseif ctx.o16 then p = "%|[^%|]*%|([^%|]*)"; ctx.o16 = false else p = "^[^%|]*" end opat = match(opat, p) if not opat then return unknown(ctx) end -- ctx.rep = false; ctx.o16 = false --XXX fails for 66 f2 0f 38 f1 06 crc32 eax,WORD PTR [esi] --XXX remove in branches? end if match(opat, "%$") then -- reg$mem variants. local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end opat = match(opat, mrm >= 192 and "^[^%$]*" or "%$(.*)") if opat == "" then return unknown(ctx) end end if opat == "" then return unknown(ctx) end local name, pat = match(opat, "^([a-z0-9 ]*)(.*)") if pat == "" and patgrp then pat = patgrp end return map_act[sub(pat, 1, 1)](ctx, name, pat) end -- Get a pattern from an opcode map and dispatch to handler. local function dispatchmap(ctx, opcmap) local pos = ctx.pos local opat = opcmap[byte(ctx.code, pos, pos)] pos = pos + 1 ctx.pos = pos return dispatch(ctx, opat) end -- Map for action codes. The key is the first char after the name. map_act = { -- Simple opcodes without operands. [""] = function(ctx, name, pat) return putop(ctx, name) end, -- Operand size chars fall right through. B = putpat, W = putpat, D = putpat, Q = putpat, V = putpat, U = putpat, T = putpat, M = putpat, X = putpat, P = putpat, F = putpat, G = putpat, -- Collect prefixes. [":"] = function(ctx, name, pat) ctx[pat == ":" and name or sub(pat, 2)] = name if ctx.pos - ctx.start > 5 then return unknown(ctx) end -- Limit #prefixes. end, -- Chain to special handler specified by name. ["*"] = function(ctx, name, pat) return map_act[name](ctx, name, sub(pat, 2)) end, -- Use named subtable for opcode group. ["!"] = function(ctx, name, pat) local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end return dispatch(ctx, map_opcgroup[name][((mrm-(mrm%8))/8)%8+1], sub(pat, 2)) end, -- o16,o32[,o64] variants. sz = function(ctx, name, pat) if ctx.o16 then ctx.o16 = false else pat = match(pat, ",(.*)") if ctx.rexw then local p = match(pat, ",(.*)") if p then pat = p; ctx.rexw = false end end end pat = match(pat, "^[^,]*") return dispatch(ctx, pat) end, -- Two-byte opcode dispatch. opc2 = function(ctx, name, pat) return dispatchmap(ctx, map_opc2) end, -- Three-byte opcode dispatch. opc3 = function(ctx, name, pat) return dispatchmap(ctx, map_opc3[pat]) end, -- VMX/SVM dispatch. vm = function(ctx, name, pat) return dispatch(ctx, map_opcvm[ctx.mrm]) end, -- Floating point opcode dispatch. fp = function(ctx, name, pat) local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end local rm = mrm%8 local idx = pat*8 + ((mrm-rm)/8)%8 if mrm >= 192 then idx = idx + 64 end local opat = map_opcfp[idx] if type(opat) == "table" then opat = opat[rm+1] end return dispatch(ctx, opat) end, -- REX prefix. rex = function(ctx, name, pat) if ctx.rex then return unknown(ctx) end -- Only 1 REX prefix allowed. for p in gmatch(pat, ".") do ctx["rex"..p] = true end ctx.rex = true end, -- Special case for nop with REX prefix. nop = function(ctx, name, pat) return dispatch(ctx, ctx.rex and pat or "nop") end, } ------------------------------------------------------------------------------ -- Disassemble a block of code. local function disass_block(ctx, ofs, len) if not ofs then ofs = 0 end local stop = len and ofs+len or #ctx.code ofs = ofs + 1 ctx.start = ofs ctx.pos = ofs ctx.stop = stop ctx.imm = nil ctx.mrm = false clearprefixes(ctx) while ctx.pos <= stop do dispatchmap(ctx, ctx.map1) end if ctx.pos ~= ctx.start then incomplete(ctx) end end -- Extended API: create a disassembler context. Then call ctx:disass(ofs, len). local function create_(code, addr, out) local ctx = {} ctx.code = code ctx.addr = (addr or 0) - 1 ctx.out = out or io.write ctx.symtab = {} ctx.disass = disass_block ctx.hexdump = 16 ctx.x64 = false ctx.map1 = map_opc1_32 ctx.aregs = map_regs.D return ctx end local function create64_(code, addr, out) local ctx = create_(code, addr, out) ctx.x64 = true ctx.map1 = map_opc1_64 ctx.aregs = map_regs.Q return ctx end -- Simple API: disassemble code (a string) at address and output via out. local function disass_(code, addr, out) create_(code, addr, out):disass() end local function disass64_(code, addr, out) create64_(code, addr, out):disass() end -- Return register name for RID. local function regname_(r) if r < 8 then return map_regs.D[r+1] end return map_regs.X[r-7] end local function regname64_(r) if r < 16 then return map_regs.Q[r+1] end return map_regs.X[r-15] end -- Public module functions. module(...) create = create_ create64 = create64_ disass = disass_ disass64 = disass64_ regname = regname_ regname64 = regname64_
mit
ccyphers/kong
spec/02-integration/05-proxy/05-balancer_spec.lua
1
13983
-- these tests only apply to the ring-balancer -- for dns-record balancing see the `dns_spec` files local helpers = require "spec.helpers" local cache = require "kong.tools.database_cache" local dao_helpers = require "spec.02-integration.02-dao.helpers" local PORT = 21000 -- modified http-server. Accepts (sequentially) a number of incoming -- connections, and returns the number of succesful ones. -- Also features a timeout setting. local function http_server(timeout, count, port, ...) local threads = require "llthreads2.ex" local thread = threads.new({ function(timeout, count, port) local socket = require "socket" local server = assert(socket.tcp()) assert(server:setoption('reuseaddr', true)) assert(server:bind("*", port)) assert(server:listen()) local expire = socket.gettime() + timeout assert(server:settimeout(0.1)) local success = 0 while count > 0 do local client, err client, err = server:accept() if err == "timeout" then if socket.gettime() > expire then server:close() error("timeout") end elseif not client then server:close() error(err) else count = count - 1 local lines = {} local line, err while #lines < 7 do line, err = client:receive() if err then break else table.insert(lines, line) end end if err then client:close() server:close() error(err) end local s = client:send("HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n") client:close() if s then success = success + 1 end end end server:close() return success end }, timeout, count, port) return thread:start(...) end dao_helpers.for_each_dao(function(kong_config) describe("Ring-balancer #"..kong_config.database, function() local config_db setup(function() config_db = helpers.test_conf.database helpers.test_conf.database = kong_config.database end) teardown(function() helpers.test_conf.database = config_db config_db = nil end) describe("Balancing", function() local client, api_client, upstream, target1, target2 before_each(function() assert(helpers.dao.apis:insert { name = "balancer.test", hosts = { "balancer.test" }, upstream_url = "http://service.xyz.v1/path", }) upstream = assert(helpers.dao.upstreams:insert { name = "service.xyz.v1", slots = 10, }) target1 = assert(helpers.dao.targets:insert { target = "127.0.0.1:"..PORT, weight = 10, upstream_id = upstream.id, }) target2 = assert(helpers.dao.targets:insert { target = "127.0.0.1:"..(PORT+1), weight = 10, upstream_id = upstream.id, }) -- insert additional api + upstream with no targets assert(helpers.dao.apis:insert { name = "balancer.test2", hosts = { "balancer.test2" }, upstream_url = "http://service.xyz.v2/path", }) assert(helpers.dao.upstreams:insert { name = "service.xyz.v2", slots = 10, }) helpers.start_kong() client = helpers.proxy_client() api_client = helpers.admin_client() end) after_each(function() if client and api_client then client:close() api_client:close() end helpers.stop_kong() end) it("over multiple targets", function() local timeout = 10 local requests = upstream.slots * 2 -- go round the balancer twice -- setup target servers local server1 = http_server(timeout, requests/2, PORT) local server2 = http_server(timeout, requests/2, PORT+1) -- Go hit them with our test requests for _ = 1, requests do local res = assert(client:send { method = "GET", path = "/", headers = { ["Host"] = "balancer.test" } }) assert.response(res).has.status(200) end -- collect server results; hitcount local _, count1 = server1:join() local _, count2 = server2:join() -- verify assert.are.equal(requests/2, count1) assert.are.equal(requests/2, count2) end) it("adding a target", function() local timeout = 10 local requests = upstream.slots * 2 -- go round the balancer twice -- setup target servers local server1 = http_server(timeout, requests/2, PORT) local server2 = http_server(timeout, requests/2, PORT+1) -- Go hit them with our test requests for _ = 1, requests do local res = assert(client:send { method = "GET", path = "/", headers = { ["Host"] = "balancer.test" } }) assert.response(res).has.status(200) end -- collect server results; hitcount local _, count1 = server1:join() local _, count2 = server2:join() -- verify assert.are.equal(requests/2, count1) assert.are.equal(requests/2, count2) -- add a new target 3 local res = assert(api_client:send { method = "POST", path = "/upstreams/"..upstream.name.."/targets", headers = { ["Content-Type"] = "application/json" }, body = { target = "127.0.0.1:"..(PORT+2), weight = target1.weight/2 , -- shift proportions from 50/50 to 40/40/20 }, }) assert.response(res).has.status(201) -- wait for the change to become effective helpers.wait_for_invalidation(cache.targets_key(upstream.id)) -- now go and hit the same balancer again ----------------------------------------- -- setup target servers server1 = http_server(timeout, requests * 0.4, PORT) server2 = http_server(timeout, requests * 0.4, PORT+1) local server3 = http_server(timeout, requests * 0.2, PORT+2) -- Go hit them with our test requests for _ = 1, requests do local res = assert(client:send { method = "GET", path = "/", headers = { ["Host"] = "balancer.test" } }) assert.response(res).has.status(200) end -- collect server results; hitcount _, count1 = server1:join() _, count2 = server2:join() local _, count3 = server3:join() -- verify assert.are.equal(requests * 0.4, count1) assert.are.equal(requests * 0.4, count2) assert.are.equal(requests * 0.2, count3) end) it("removing a target", function() local timeout = 10 local requests = upstream.slots * 2 -- go round the balancer twice -- setup target servers local server1 = http_server(timeout, requests/2, PORT) local server2 = http_server(timeout, requests/2, PORT+1) -- Go hit them with our test requests for _ = 1, requests do local res = assert(client:send { method = "GET", path = "/", headers = { ["Host"] = "balancer.test" } }) assert.response(res).has.status(200) end -- collect server results; hitcount local _, count1 = server1:join() local _, count2 = server2:join() -- verify assert.are.equal(requests/2, count1) assert.are.equal(requests/2, count2) -- modify weight for target 2, set to 0 local res = assert(api_client:send { method = "POST", path = "/upstreams/"..upstream.name.."/targets", headers = { ["Content-Type"] = "application/json" }, body = { target = target2.target, weight = 0, -- disable this target }, }) assert.response(res).has.status(201) -- wait for the change to become effective helpers.wait_for_invalidation(cache.targets_key(target2.upstream_id)) -- now go and hit the same balancer again ----------------------------------------- -- setup target servers server1 = http_server(timeout, requests, PORT) -- Go hit them with our test requests for _ = 1, requests do local res = assert(client:send { method = "GET", path = "/", headers = { ["Host"] = "balancer.test" } }) assert.response(res).has.status(200) end -- collect server results; hitcount _, count1 = server1:join() -- verify all requests hit server 1 assert.are.equal(requests, count1) end) it("modifying target weight", function() local timeout = 10 local requests = upstream.slots * 2 -- go round the balancer twice -- setup target servers local server1 = http_server(timeout, requests/2, PORT) local server2 = http_server(timeout, requests/2, PORT+1) -- Go hit them with our test requests for _ = 1, requests do local res = assert(client:send { method = "GET", path = "/", headers = { ["Host"] = "balancer.test" } }) assert.response(res).has.status(200) end -- collect server results; hitcount local _, count1 = server1:join() local _, count2 = server2:join() -- verify assert.are.equal(requests/2, count1) assert.are.equal(requests/2, count2) -- modify weight for target 2 local res = assert(api_client:send { method = "POST", path = "/upstreams/"..target2.upstream_id.."/targets", headers = { ["Content-Type"] = "application/json" }, body = { target = target2.target, weight = target1.weight * 1.5, -- shift proportions from 50/50 to 40/60 }, }) assert.response(res).has.status(201) -- wait for the change to become effective helpers.wait_for_invalidation(cache.targets_key(target2.upstream_id)) -- now go and hit the same balancer again ----------------------------------------- -- setup target servers server1 = http_server(timeout, requests * 0.4, PORT) server2 = http_server(timeout, requests * 0.6, PORT+1) -- Go hit them with our test requests for _ = 1, requests do local res = assert(client:send { method = "GET", path = "/", headers = { ["Host"] = "balancer.test" } }) assert.response(res).has.status(200) end -- collect server results; hitcount _, count1 = server1:join() _, count2 = server2:join() -- verify assert.are.equal(requests * 0.4, count1) assert.are.equal(requests * 0.6, count2) end) it("failure due to targets all 0 weight", function() local timeout = 10 local requests = upstream.slots * 2 -- go round the balancer twice -- setup target servers local server1 = http_server(timeout, requests/2, PORT) local server2 = http_server(timeout, requests/2, PORT+1) -- Go hit them with our test requests for _ = 1, requests do local res = assert(client:send { method = "GET", path = "/", headers = { ["Host"] = "balancer.test" } }) assert.response(res).has.status(200) end -- collect server results; hitcount local _, count1 = server1:join() local _, count2 = server2:join() -- verify assert.are.equal(requests/2, count1) assert.are.equal(requests/2, count2) -- modify weight for both targets, set to 0 local res = assert(api_client:send { method = "POST", path = "/upstreams/"..upstream.name.."/targets", headers = { ["Content-Type"] = "application/json" }, body = { target = target1.target, weight = 0, -- disable this target }, }) assert.response(res).has.status(201) res = assert(api_client:send { method = "POST", path = "/upstreams/"..upstream.name.."/targets", headers = { ["Content-Type"] = "application/json" }, body = { target = target2.target, weight = 0, -- disable this target }, }) assert.response(res).has.status(201) -- wait for the change to become effective helpers.wait_for_invalidation(cache.targets_key(target2.upstream_id)) -- now go and hit the same balancer again ----------------------------------------- res = assert(client:send { method = "GET", path = "/", headers = { ["Host"] = "balancer.test" } }) assert.response(res).has.status(503) end) it("failure due to no targets", function() -- Go hit it with a request local res = assert(client:send { method = "GET", path = "/", headers = { ["Host"] = "balancer.test2" } }) assert.response(res).has.status(503) end) end) end) end) -- for 'database type'
apache-2.0
Ninjistix/darkstar
scripts/zones/Port_Bastok/npcs/Paujean.lua
5
2259
----------------------------------- -- Area: Port Bastok -- NPC: Paujean -- Starts & Finishes Quest: Silence of the Rams -- !pos -93.738 4.649 34.373 236 ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_Bastok/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/titles"); ----------------------------------- function onTrade(player,npc,trade) local SilenceOfTheRams = player:getQuestStatus(BASTOK,SILENCE_OF_THE_RAMS); if (SilenceOfTheRams == QUEST_ACCEPTED) then local count = trade:getItemCount(); local LumberingHorn = trade:hasItemQty(910,1); local RampagingHorn = trade:hasItemQty(911,1); if (LumberingHorn == true and RampagingHorn == true and count == 2) then player:startEvent(196); end end end; function onTrigger(player,npc) local SilenceOfTheRams = player:getQuestStatus(BASTOK,SILENCE_OF_THE_RAMS); local WildcatBastok = player:getVar("WildcatBastok"); if (player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok,2) == false) then player:startEvent(355); elseif (SilenceOfTheRams == QUEST_AVAILABLE and player:getFameLevel(NORG) >= 2) then player:startEvent(195); elseif (SilenceOfTheRams == QUEST_ACCEPTED) then player:showText(npc,PAUJEAN_DIALOG_1); else player:startEvent(25); end end; function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 195) then player:addQuest(BASTOK,SILENCE_OF_THE_RAMS); elseif (csid == 196) then player:tradeComplete(); player:completeQuest(BASTOK,SILENCE_OF_THE_RAMS); player:addFame(3,125); player:addItem(13201); player:messageSpecial(ITEM_OBTAINED,13201); player:addTitle(PURPLE_BELT); elseif (csid == 355) then player:setMaskBit(player:getVar("WildcatBastok"),"WildcatBastok",2,true); end end;
gpl-3.0
eugenesan/openwrt-luci
applications/luci-coovachilli/luasrc/model/cbi/coovachilli_auth.lua
79
2235
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("coovachilli") -- uam config s1 = m:section(TypedSection, "uam") s1.anonymous = true s1:option( Value, "uamserver" ) s1:option( Value, "uamsecret" ).password = true s1:option( Flag, "uamanydns" ) s1:option( Flag, "nouamsuccess" ) s1:option( Flag, "nouamwispr" ) s1:option( Flag, "chillixml" ) s1:option( Flag, "uamanyip" ).optional = true s1:option( Flag, "dnsparanoia" ).optional = true s1:option( Flag, "usestatusfile" ).optional = true s1:option( Value, "uamhomepage" ).optional = true s1:option( Value, "uamlisten" ).optional = true s1:option( Value, "uamport" ).optional = true s1:option( Value, "uamiport" ).optional = true s1:option( DynamicList, "uamdomain" ).optional = true s1:option( Value, "uamlogoutip" ).optional = true s1:option( DynamicList, "uamallowed" ).optional = true s1:option( Value, "uamui" ).optional = true s1:option( Value, "wisprlogin" ).optional = true s1:option( Value, "defsessiontimeout" ).optional = true s1:option( Value, "defidletimeout" ).optional = true s1:option( Value, "definteriminterval" ).optional = true s1:option( Value, "ssid" ).optional = true s1:option( Value, "vlan" ).optional = true s1:option( Value, "nasip" ).optional = true s1:option( Value, "nasmac" ).optional = true s1:option( Value, "wwwdir" ).optional = true s1:option( Value, "wwwbin" ).optional = true s1:option( Value, "localusers" ).optional = true s1:option( Value, "postauthproxy" ).optional = true s1:option( Value, "postauthproxyport" ).optional = true s1:option( Value, "locationname" ).optional = true -- mac authentication s2 = m:section(TypedSection, "macauth") s2.anonymous = true s2:option( Flag, "macauth" ) s2:option( Flag, "macallowlocal" ) s2:option( DynamicList, "macallowed" ) pw = s2:option( Value, "macpasswd" ) pw.optional = true pw.password = true s2:option( Value, "macsuffix" ).optional = true return m
apache-2.0
Ninjistix/darkstar
scripts/zones/Upper_Jeuno/npcs/Osker.lua
5
2608
----------------------------------- -- Area: Upper Jeuno -- NPC: Osker -- Involved in Quest: Chocobo's Wounds ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) local ANewDawnEvent = player:getVar("ANewDawn_Event"); if (trade:hasItemQty(717,1) and trade:getItemCount() == 1 and ANewDawnEvent == 3) then player:tradeComplete(); player:startEvent(148); end end; function onTrigger(player,npc) local ANewDawn = player:getQuestStatus(JEUNO,A_NEW_DAWN); local ANewDawnEvent = player:getVar("ANewDawn_Event"); local ChocobosWounds = player:getQuestStatus(JEUNO,CHOCOBO_S_WOUNDS); local feed = player:getVar("ChocobosWounds_Event"); -- A New Dawn if (ANewDawn == QUEST_ACCEPTED) then if (ANewDawnEvent == 2 or ANewDawnEvent == 3) then player:startEvent(146); elseif (ANewDawnEvent >= 4) then player:startEvent(147); end -- Chocobos Wounds elseif (ChocobosWounds == 0) then player:startEvent(62); elseif (ChocobosWounds == 1) then if (feed == 1) then player:startEvent(103); elseif (feed == 2) then player:startEvent(51); elseif (feed == 3) then player:startEvent(52); elseif (feed == 4) then player:startEvent(59); elseif (feed == 5) then player:startEvent(46); elseif (feed == 6) then player:startEvent(55); end elseif (ChocobosWounds == 2) then player:startEvent(55); -- Standard Dialog 0036 probably isnt correct elseif (ANewDawn == QUEST_COMPLETED) then player:startEvent(145); else player:startEvent(54); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local ANewDawnEvent = player:getVar("ANewDawn_Event"); if (csid == 146) then if (ANewDawnEvent == 2) then player:setVar("ANewDawn_Event",3); end elseif (csid == 148) then player:addKeyItem(217); player:messageSpecial(KEYITEM_OBTAINED, 217); player:setVar("ANewDawn_Event",4); end end;
gpl-3.0
jamiepg1/MCServer
lib/tolua++/src/bin/lua/operator.lua
42
6043
-- tolua: operator class -- Written by Waldemar Celes -- TeCGraf/PUC-Rio -- Jul 1998 -- $Id: $ -- This code is free software; you can redistribute it and/or modify it. -- The software provided hereunder is on an "as is" basis, and -- the author has no obligation to provide maintenance, support, updates, -- enhancements, or modifications. -- Operator class -- Represents an operator function or a class operator method. -- It stores the same fields as functions do plus: -- kind = set of character representing the operator (as it appers in C++ code) classOperator = { kind = '', } classOperator.__index = classOperator setmetatable(classOperator,classFunction) -- table to transform operator kind into the appropriate tag method name _TM = {['+'] = 'add', ['-'] = 'sub', ['*'] = 'mul', ['/'] = 'div', ['<'] = 'lt', ['<='] = 'le', ['=='] = 'eq', ['[]'] = 'geti', ['&[]'] = 'seti', --['->'] = 'flechita', } -- Print method function classOperator:print (ident,close) print(ident.."Operator{") print(ident.." kind = '"..self.kind.."',") print(ident.." mod = '"..self.mod.."',") print(ident.." type = '"..self.type.."',") print(ident.." ptr = '"..self.ptr.."',") print(ident.." name = '"..self.name.."',") print(ident.." const = '"..self.const.."',") print(ident.." cname = '"..self.cname.."',") print(ident.." lname = '"..self.lname.."',") print(ident.." args = {") local i=1 while self.args[i] do self.args[i]:print(ident.." ",",") i = i+1 end print(ident.." }") print(ident.."}"..close) end function classOperator:supcode_tmp() if not _TM[self.kind] then return classFunction.supcode(self) end -- no overload, no parameters, always inclass output("/* method:",self.name," of class ",self:inclass()," */") output("#ifndef TOLUA_DISABLE_"..self.cname) output("\nstatic int",self.cname,"(lua_State* tolua_S)") if overload < 0 then output('#ifndef TOLUA_RELEASE\n') end output(' tolua_Error tolua_err;') output(' if (\n') -- check self local is_func = get_is_function(self.parent.type) output(' !'..is_func..'(tolua_S,1,"'..self.parent.type..'",0,&tolua_err) ||\n') output(' !tolua_isnoobj(tolua_S,2,&tolua_err)\n )') output(' goto tolua_lerror;') output(' else\n') output('#endif\n') -- tolua_release output(' {') -- declare self output(' ',self.const,self.parent.type,'*','self = ') output('(',self.const,self.parent.type,'*) ') local to_func = get_to_func(self.parent.type) output(to_func,'(tolua_S,1,0);') -- check self output('#ifndef TOLUA_RELEASE\n') output(' if (!self) tolua_error(tolua_S,"'..output_error_hook("invalid \'self\' in function \'%s\'", self.name)..'",NULL);'); output('#endif\n') -- cast self output(' ',self.mod,self.type,self.ptr,'tolua_ret = ') output('(',self.mod,self.type,self.ptr,')(*self);') -- return value local t,ct = isbasic(self.type) if t then output(' tolua_push'..t..'(tolua_S,(',ct,')tolua_ret);') else t = self.type local push_func = get_push_function(t) new_t = string.gsub(t, "const%s+", "") if self.ptr == '' then output(' {') output('#ifdef __cplusplus\n') output(' void* tolua_obj = Mtolua_new((',new_t,')(tolua_ret));') output(' ',push_func,'(tolua_S,tolua_obj,"',t,'");') output(' tolua_register_gc(tolua_S,lua_gettop(tolua_S));') output('#else\n') output(' void* tolua_obj = tolua_copy(tolua_S,(void*)&tolua_ret,sizeof(',t,'));') output(' ',push_func,'(tolua_S,tolua_obj,"',t,'");') output(' tolua_register_gc(tolua_S,lua_gettop(tolua_S));') output('#endif\n') output(' }') elseif self.ptr == '&' then output(' ',push_func,'(tolua_S,(void*)&tolua_ret,"',t,'");') else if local_constructor then output(' ',push_func,'(tolua_S,(void *)tolua_ret,"',t,'");') output(' tolua_register_gc(tolua_S,lua_gettop(tolua_S));') else output(' ',push_func,'(tolua_S,(void*)tolua_ret,"',t,'");') end end end output(' }') output(' return 1;') output('#ifndef TOLUA_RELEASE\n') output('tolua_lerror:\n') output(' tolua_error(tolua_S,"'..output_error_hook("#ferror in function \'%s\'.", self.lname)..'",&tolua_err);') output(' return 0;') output('#endif\n') output('}') output('#endif //#ifndef TOLUA_DISABLE\n') output('\n') end -- Internal constructor function _Operator (t) setmetatable(t,classOperator) if t.const ~= 'const' and t.const ~= '' then error("#invalid 'const' specification") end append(t) if not t:inclass() then error("#operator can only be defined as class member") end --t.name = t.name .. "_" .. (_TM[t.kind] or t.kind) t.cname = t:cfuncname("tolua")..t:overload(t) t.name = "operator" .. t.kind -- set appropriate calling name return t end -- Constructor function Operator (d,k,a,c) local op_k = string.gsub(k, "^%s*", "") op_k = string.gsub(k, "%s*$", "") --if string.find(k, "^[%w_:%d<>%*%&]+$") then if d == "operator" and k ~= '' then d = k.." operator" elseif not _TM[op_k] then if flags['W'] then error("tolua: no support for operator" .. f.kind) else warning("No support for operator "..op_k..", ignoring") return nil end end local ref = '' local t = split_c_tokens(strsub(a,2,strlen(a)-1),',') -- eliminate braces local i=1 local l = {n=0} while t[i] do l.n = l.n+1 l[l.n] = Declaration(t[i],'var') i = i+1 end if k == '[]' then local _ _, _, ref = strfind(d,'(&)') d = gsub(d,'&','') elseif k=='&[]' then l.n = l.n+1 l[l.n] = Declaration(d,'var') l[l.n].name = 'tolua_value' end local f = Declaration(d,'func') if k == '[]' and (l[1]==nil or isbasic(l[1].type)~='number') then error('operator[] can only be defined for numeric index.') end f.args = l f.const = c f.kind = op_k f.lname = "."..(_TM[f.kind] or f.kind) if not _TM[f.kind] then f.cast_operator = true end if f.kind == '[]' and ref=='&' and f.const~='const' then Operator(d,'&'..k,a,c) -- create correspoding set operator end return _Operator(f) end
apache-2.0
Ninjistix/darkstar
scripts/zones/Rabao/Zone.lua
5
1039
----------------------------------- -- -- Zone: Rabao (247) -- ----------------------------------- package.loaded["scripts/zones/Rabao/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Rabao/TextIDs"); ----------------------------------- function onInitialize(zone) end; function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(-20.052,6.074,-122.408,193); end return cs; end; function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; function onRegionEnter(player,region) end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
dinodeck/ninety_nine_days_of_dev
002_bitmap_numbers/code/CombatChoiceState.lua
1
12958
CombatChoiceState = {} CombatChoiceState.__index = CombatChoiceState function CombatChoiceState:Create(context, actor) local this = { mStack = context.mStack, mCombatState = context, mActor = actor, mCharacter = context.mActorCharMap[actor], mUpArrow = gWorld.mIcons:Get('uparrow'), mDownArrow = gWorld.mIcons:Get('downarrow'), mMarker = Sprite.Create(), mHide = false, } this.mMarker:SetTexture(Texture.Find('continue_caret.png')) this.mMarkPos = this.mCharacter.mEntity:GetSelectPosition() this.mTime = 0 setmetatable(this, self) this.mSelection = Selection:Create { data = this.mActor.mActions, columns = 1, displayRows = 3, spacingX = 0, spacingY = 19, OnSelection = function(...) this:OnSelect(...) end, RenderItem = this.RenderAction, } this:CreateChoiceDialog() return this end function CombatChoiceState:Hide() self.mHide = true end function CombatChoiceState:Show() self.mHide = false end function CombatChoiceState:SetArrowPosition() local x = self.mTextbox.mSize.left local y = self.mTextbox.mSize.top local width = self.mTextbox.mWidth local height = self.mTextbox.mHeight local arrowPad = 9 local arrowX = x + width - arrowPad self.mUpArrow:SetPosition(arrowX, y - arrowPad) self.mDownArrow:SetPosition(arrowX, y - height + arrowPad) end function CombatChoiceState:CreateChoiceDialog() local x = -System.ScreenWidth()/2 local y = -System.ScreenHeight()/2 local height = self.mSelection:GetHeight() + 18 local width = self.mSelection:GetWidth() + 16 y = y + height + 16 x = x + 100 self.mTextbox = Textbox:Create { textScale = 1.2, text = "", size = { left = x, right = x + width, top = y, bottom = y - height }, textbounds = { left = -20, right = 0, top = 0, bottom = 2 }, panelArgs = { texture = Texture.Find("gradient_panel.png"), size = 3, }, selectionMenu = self.mSelection, stack = self.mStack, } end function CombatChoiceState:RenderAction(renderer, x, y, item) local text = Actor.ActionLabels[item] or "" renderer:DrawText2d(x, y, text) end function CombatChoiceState:OnSelect(index, data) print("on select", index, data) if data == "attack" then self.mSelection:HideCursor() local state = CombatTargetState:Create( self.mCombatState, { targetType = CombatTargetType.One, --switchSides = false, OnSelect = function(targets) self:TakeAction(data, targets) end, OnExit = function() self.mSelection:ShowCursor() end }) self.mStack:Push(state) elseif data == "flee" then self.mStack:Pop() -- choice state local queue = self.mCombatState.mEventQueue local event = CEFlee:Create(self.mCombatState, self.mActor) local tp = event:TimePoints(queue) queue:Add(event, tp) elseif data == "item" then self:OnItemAction() elseif data == "magic" then self:OnMagicAction() elseif data == "special" then self:OnSpecialAction() end end function CombatChoiceState:OnSpecialAction() local actor = self.mActor -- Create the selection box local x = self.mTextbox.mSize.left - 64 local y = self.mTextbox.mSize.top self.mSelection:HideCursor() local OnRenderItem = function(self, renderer, x, y, item) local text = "--" local cost = "0" local canPerform = false local mp = actor.mStats:Get("mp_now") local color = Vector.Create(1,1,1,1) if item then local def = SpecialDB[item] text = def.name cost = string.format("%d", def.mp_cost) if def.mp_cost > 0 then canPerform = mp >= def.mp_cost if not canPerform then color = Vector.Create(0.7, 0.7, 0.7, 1) end gNumberFont:AlignText("right", "center") gNumberFont:DrawText2d(renderer, x + 96, y, cost, color) end end renderer:AlignText("left", "center") renderer:DrawText2d(x, y, text, color) end local OnExit = function() self.mSelection:ShowCursor() end local OnSelection = function(selection, index, item) if not item then return end local def = SpecialDB[item] local mp = actor.mStats:Get("mp_now") if mp < def.mp_cost then return end -- Find associated event local event = nil if def.action == "slash" then event = CESlash elseif def.action == "steal" then event = CESteal end local targeter = self:CreateActionTargeter(def, selection, event) self.mStack:Push(targeter) end local state = BrowseListState:Create { stack = self.mStack, title = "Special", x = x, y = y, data = actor.mSpecial, OnExit = OnExit, OnRenderItem = OnRenderItem, OnSelection = OnSelection } self.mStack:Push(state) end function CombatChoiceState:OnMagicAction() local actor = self.mActor -- Create the selection box local x = self.mTextbox.mSize.left - 64 local y = self.mTextbox.mSize.top self.mSelection:HideCursor() local OnRenderItem = function(self, renderer, x, y, item) local text = "--" local cost = "0" local canCast = false local mp = actor.mStats:Get("mp_now") local color = Vector.Create(1,1,1,1) if item then local def = SpellDB[item] print(tostring(item), tostring(def)) text = def.name cost = string.format("%d", def.mp_cost) canCast = mp >= def.mp_cost if not canCast then color = Vector.Create(0.7, 0.7, 0.7, 1) end gNumberFont:AlignText("right", "center") gNumberFont:DrawText2d(renderer, x + 96, y, cost, color) end renderer:AlignText("left", "center") renderer:DrawText2d(x, y, text, color) end local OnExit = function() self.mCombatState:HideTip("") self.mSelection:ShowCursor() end local OnSelection = function(selection, index, item) if not item then return end print("spell selected:", item) local def = SpellDB[item] local mp = actor.mStats:Get("mp_now") if mp < def.mp_cost then return end local targeter = self:CreateActionTargeter(def, selection, CECastSpell) self.mStack:Push(targeter) end local state = BrowseListState:Create { stack = self.mStack, title = "MAGIC", x = x, y = y, data = actor.mMagic, OnExit = OnExit, OnRenderItem = OnRenderItem, OnSelection = OnSelection } self.mStack:Push(state) end function CombatChoiceState:CreateActionTargeter(def, browseState, combatEvent) local targetDef = def.target print(targetDef.type) browseState:Hide() self:Hide() local OnSelect = function(targets) self.mStack:Pop() -- target state self.mStack:Pop() -- spell browse state self.mStack:Pop() -- action state local queue = self.mCombatState.mEventQueue local event = combatEvent:Create(self.mCombatState, self.mActor, def, targets) local tp = event:TimePoints(queue) queue:Add(event, tp) end local OnExit = function() browseState:Show() self:Show() end return CombatTargetState:Create(self.mCombatState, { targetType = targetDef.type, defaultSelector = CombatSelector[targetDef.selector], switchSides = targetDef.switch_sides, OnSelect = OnSelect, OnExit = OnExit }) end function CombatChoiceState:OnItemAction() -- 1. Get the filtered item list local filter = function(def) return def.type == "useable" end local filteredItems = gWorld:FilterItems(filter) -- 2. Create the selection box local x = self.mTextbox.mSize.left - 64 local y = self.mTextbox.mSize.top self.mSelection:HideCursor() local OnFocus = function(item) local text = "" if item then local def = ItemDB[item.id] text = def.description end self.mCombatState:ShowTip(text) end local OnExit = function() self.mCombatState:HideTip("") self.mSelection:ShowCursor() end local OnRenderItem = function(self, renderer, x, y, item) local text = "--" if item then local def = ItemDB[item.id] text = def.name if item.count > 1 then text = string.format("%s x%00d", def.name, item.count) end end renderer:DrawText2d(x, y, text) end local OnSelection = function(selection, index, item) if not item then return end local def = ItemDB[item.id] --print("ITEM DATA>>>>>>>>", item.id, def) local targeter = self:CreateItemTargeter(def, selection) self.mStack:Push(targeter) end local state = BrowseListState:Create { stack = self.mStack, title = "ITEMS", x = x, y = y, data = filteredItems, OnExit = OnExit, OnRenderItem = OnRenderItem, OnFocus = OnFocus, OnSelection = OnSelection, } self.mStack:Push(state) end function CombatChoiceState:CreateItemTargeter(def, browseState) local targetDef = def.use.target self.mCombatState:ShowTip(def.use.hint) browseState:Hide() self:Hide() local OnSelect = function(targets) self.mStack:Pop() -- target state self.mStack:Pop() -- item box state self.mStack:Pop() -- action state local queue = self.mCombatState.mEventQueue local event = CEUseItem:Create(self.mCombatState, self.mActor, def, targets) local tp = event:TimePoints(queue) queue:Add(event, tp) end local OnExit = function() browseState:Show() self:Show() end return CombatTargetState:Create(self.mCombatState, { targetType = targetDef.type, defaultSelector = CombatSelector[targetDef.selector], switchSides = targetDef.switch_sides, OnSelect = OnSelect, OnExit = OnExit }) end function CombatChoiceState:TakeAction(id, targets) self.mStack:Pop() -- select state self.mStack:Pop() -- action state local queue = self.mCombatState.mEventQueue if id == "attack" then print("Entered attack state") local attack = CEAttack:Create(self.mCombatState, self.mActor, {player = true}, targets) local speed = self.mActor.mStats:Get("speed") local tp = queue:SpeedToTimePoints(speed) queue:Add(attack, tp) end end function CombatChoiceState:Enter() self.mCombatState.mSelectedActor = self.mActor end function CombatChoiceState:Exit() self.mCombatState.mSelectedActor = nil self.mTextbox:Exit() end function CombatChoiceState:Update(dt) self.mTextbox:Update(dt) -- Make the selection cursor bounce self.mTime = self.mTime + dt local bounce = self.mMarkPos + Vector.Create(0, math.sin(self.mTime * 5)) self.mMarker:SetPosition(bounce) end function CombatChoiceState:Render(renderer) if self.mHide then return end self.mTextbox:Render(renderer) self:SetArrowPosition() if self.mSelection:CanScrollUp() then renderer:DrawSprite(self.mUpArrow) end if self.mSelection:CanScrollDown() then renderer:DrawSprite(self.mDownArrow) end renderer:DrawSprite(self.mMarker) end function CombatChoiceState:HandleInput() self.mSelection:HandleInput() end
mit
Ninjistix/darkstar
scripts/globals/items/bowl_of_salt_ramen.lua
3
1656
----------------------------------------- -- ID: 6462 -- Item: bowl_of_salt_ramen -- Food Effect: 30Min, All Races ----------------------------------------- -- DEX +5 -- VIT +5 -- AGI +5 -- Accuracy +5% (cap 90) -- Ranged Accuracy +5% (cap 90) -- Evasion +5% (cap 90) -- Resist Slow +10 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- 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; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,6462); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 5); target:addMod(MOD_VIT, 5); target:addMod(MOD_AGI, 5); target:addMod(MOD_FOOD_ACCP, 5); target:addMod(MOD_FOOD_ACC_CAP, 90); target:addMod(MOD_FOOD_RACCP, 5); target:addMod(MOD_FOOD_RACC_CAP, 90); -- target:addMod(MOD_FOOD_EVAP, 5); -- target:addMod(MOD_FOOD_EVA_CAP, 90); target:addMod(MOD_SLOWRES, 10); end; function onEffectLose(target, effect) target:delMod(MOD_DEX, 5); target:delMod(MOD_VIT, 5); target:delMod(MOD_AGI, 5); target:delMod(MOD_FOOD_ACCP, 5); target:delMod(MOD_FOOD_ACC_CAP, 90); target:delMod(MOD_FOOD_RACCP, 5); target:delMod(MOD_FOOD_RACC_CAP, 90); -- target:delMod(MOD_FOOD_EVAP, 5); -- target:delMod(MOD_FOOD_EVA_CAP, 90); target:delMod(MOD_SLOWRES, 10); end;
gpl-3.0
abosalah22/zak
plugins/ingroup.lua
156
60323
do -- Check Member local function check_member_autorealm(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.peer_id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Welcome to your new realm !') end end end local function check_member_realm_add(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.peer_id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been added!') end end end function check_member_group(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.peer_id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as the owner.') end end end local function check_member_modadd(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.peer_id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', long_id = msg.to.peer_id, moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg}) end end local function autorealmadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg}) end end local function check_member_realmrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Realm configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = nil save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been removed!') end end end local function check_member_modrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.peer_id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = 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(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group has been removed') end end end --End Check Member function show_group_settingsmod(msg, target) if not is_momod(msg) then return "For moderators only!" end local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(target)]['settings']['lock_bots'] then bots_protection = data[tostring(target)]['settings']['lock_bots'] end local leave_ban = "no" if data[tostring(target)]['settings']['leave_ban'] then leave_ban = data[tostring(target)]['settings']['leave_ban'] end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_link'] then data[tostring(target)]['settings']['lock_link'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_sticker'] then data[tostring(target)]['settings']['lock_sticker'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['public'] then data[tostring(target)]['settings']['public'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_rtl'] then data[tostring(target)]['settings']['lock_rtl'] = 'no' end end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection.."\nLock links : "..settings.lock_link.."\nLock RTL: "..settings.lock_rtl.."\nLock sticker: "..settings.lock_sticker.."\nPublic: "..settings.public return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return 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 get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots protection is already enabled' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots protection has been enabled' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots protection is already disabled' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots protection has been disabled' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return 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_namemod(msg, data, target) if not is_momod(msg) then return 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 local function lock_group_floodmod(msg, data, target) if not is_momod(msg) then return 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_floodmod(msg, data, target) if not is_momod(msg) then return end if not is_owner(msg) then return "Only owners can unlock flood" 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 local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return 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_membermod(msg, data, target) if not is_momod(msg) then return 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 local function set_public_membermod(msg, data, target) if not is_momod(msg) then return end local group_member_lock = data[tostring(target)]['settings']['public'] local long_id = data[tostring(target)]['long_id'] if not long_id then data[tostring(target)]['long_id'] = msg.to.peer_id save_data(_config.moderation.data, data) end if group_member_lock == 'yes' then return 'Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'Group is now: public' end local function unset_public_membermod(msg, data, target) if not is_momod(msg) then return end local group_member_lock = data[tostring(target)]['settings']['public'] local long_id = data[tostring(target)]['long_id'] if not long_id then data[tostring(target)]['long_id'] = msg.to.peer_id save_data(_config.moderation.data, data) end if group_member_lock == 'no' then return 'Group is not public' else data[tostring(target)]['settings']['public'] = 'no' save_data(_config.moderation.data, data) return 'Group is now: not public' end end local function lock_group_leave(msg, data, target) if not is_momod(msg) then return end local leave_ban = data[tostring(target)]['settings']['leave_ban'] if leave_ban == 'yes' then return 'Leaving users will be banned' else data[tostring(target)]['settings']['leave_ban'] = 'yes' save_data(_config.moderation.data, data) end return 'Leaving users will be banned' end local function unlock_group_leave(msg, data, target) if not is_momod(msg) then return end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'no' then return 'Leaving users will not be banned' else data[tostring(target)]['settings']['leave_ban'] = 'no' save_data(_config.moderation.data, data) return 'Leaving users will not be banned' end end local function unlock_group_photomod(msg, data, target) if not is_momod(msg) then return 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_links(msg, data, target) if not is_momod(msg) then return end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'yes' then return 'Link posting is already locked' else data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) return 'Link posting has been locked' end end local function unlock_group_links(msg, data, target) if not is_momod(msg) then return end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'no' then return 'Link posting is not locked' else data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) return 'Link posting has been unlocked' end end local function lock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'yes' then return 'RTL is already locked' else data[tostring(target)]['settings']['lock_rtl'] = 'yes' save_data(_config.moderation.data, data) return 'RTL has been locked' end end local function unlock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'no' then return 'RTL is already unlocked' else data[tostring(target)]['settings']['lock_rtl'] = 'no' save_data(_config.moderation.data, data) return 'RTL has been unlocked' end end local function lock_group_sticker(msg, data, target) if not is_momod(msg) then return end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'yes' then return 'Sticker posting is already locked' else data[tostring(target)]['settings']['lock_sticker'] = 'yes' save_data(_config.moderation.data, data) return 'Sticker posting has been locked' end end local function unlock_group_sticker(msg, data, target) if not is_momod(msg) then return end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'no' then return 'Sticker posting is already unlocked' else data[tostring(target)]['settings']['lock_sticker'] = 'no' save_data(_config.moderation.data, data) return 'Sticker posting has been unlocked' end end local function lock_group_contacts(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_contacts'] if group_contacts_lock == 'yes' then return 'Contact posting is already locked' else data[tostring(target)]['settings']['lock_contacts'] = 'yes' save_data(_config.moderation.data, data) return 'Contact posting has been locked' end end local function unlock_group_contacts(msg, data, target) if not is_momod(msg) then return end local group_contacts_lock = data[tostring(target)]['settings']['lock_contacts'] if group_contacts_lock == 'no' then return 'Contact posting is already unlocked' else data[tostring(target)]['settings']['lock_contacts'] = 'no' save_data(_config.moderation.data, data) return 'Contact posting has been unlocked' end end local function enable_strict_rules(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['strict'] if strict == 'yes' then return 'Settings are already strictly enforced' else data[tostring(target)]['settings']['strict'] = 'yes' save_data(_config.moderation.data, data) return 'Settings will be strictly enforced' end end local function disable_strict_rules(msg, data, target) if not is_momod(msg) then return end local group_contacts_lock = data[tostring(target)]['settings']['strict'] if strict == 'no' then return 'Settings are not strictly enforced' else data[tostring(target)]['settings']['strict'] = 'no' save_data(_config.moderation.data, data) return 'Settings will not be strictly enforced' end end local function set_rulesmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n\n'..rules end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_momod(msg) then return end if not is_admin1(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_group(msg) then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function realmadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_momod(msg) then return end if not is_admin1(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_realm(msg) then return 'Realm is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg}) end -- Global functions function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin1(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_group(msg) then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end function realmrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin1(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_realm(msg) then return 'Realm is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg}) end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Chat rules:\n\n'..rules return rules 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, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been promoted.') end local function promote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'.. msg.from.username else member_username = full_name end local member_id = msg.from.peer_id if msg.to.peer_type == 'chat' then return promote(get_receiver(msg), member_username, member_id) end end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been demoted.') end local function demote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'..msg.from.username else member_username = full_name end local member_id = msg.from.peer_id if msg.to.peer_type == 'chat' then return demote(get_receiver(msg), member_username, member_id) end end local function setowner_by_reply(extra, success, result) local msg = result local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) local name_log = msg.from.print_name:gsub("_", " ") data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..msg.from.id.."] as owner") local text = msg.from.print_name:gsub("_", " ").." is the owner now" return send_large_msg(receiver, text) end local function promote_demote_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.peer_id local member_username = "@"..result.username local chat_id = extra.chat_id local mod_cmd = extra.mod_cmd local receiver = "chat#id"..chat_id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end local function mute_user_callback(extra, success, result) if result.service then local action = result.action.type if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then if result.action.user then user_id = result.action.user.peer_id end end else user_id = result.from.peer_id end local receiver = extra.receiver local chat_id = string.gsub(receiver, 'channel#id', '') if is_muted_user(chat_id, user_id) then mute_user(chat_id, user_id) send_large_msg(receiver, "["..user_id.."] removed from the muted user list") else unmute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] added to the muted user list") end end local function modlist(msg) local data = load_data(_config.moderation.data) local groups = "groups" if not data[tostring(groups)][tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - '..v..' [' ..k.. '] \n' i = i + 1 end return message end local function callbackres(extra, success, result) local user = result.peer_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 callback_mute_res(extra, success, result) local user_id = result.peer_id local receiver = extra.receiver local chat_id = string.gsub(receiver, 'chat#id', '') if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] removed from muted user list") else mute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] added to muted user list") end end local function help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(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(v.id, result.peer_id) 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.peer_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.peer_id) end end --[[local function user_msgs(user_id, chat_id) local user_info local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info = tonumber(redis:get(um_hash) or 0) return user_info end local function kick_zero(cb_extra, success, result) local chat_id = cb_extra.chat_id local chat = "chat#id"..chat_id local ci_user local re_user for k,v in pairs(result.members) do local si = false ci_user = v.peer_id local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) for i = 1, #users do re_user = users[i] if tonumber(ci_user) == tonumber(re_user) then si = true end end if not si then if ci_user ~= our_id then if not is_momod2(ci_user, chat_id) then chat_del_user(chat, 'user#id'..ci_user, ok_cb, true) end end end end end local function kick_inactive(chat_id, num, receiver) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) -- Get user info for i = 1, #users do local user_id = users[i] local user_info = user_msgs(user_id, chat_id) local nmsg = user_info if tonumber(nmsg) < tonumber(num) then if not is_momod2(user_id, chat_id) then chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true) end end end return chat_info(receiver, kick_zero, {chat_id = chat_id}) end]] local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)] and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if msg.to.type == 'chat' then if is_admin1(msg) or not is_support(msg.from.id) then-- Admin only if matches[1] == 'add' and not matches[2] then if not is_admin1(msg) and not is_support(msg.from.id) then-- Admin only savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to add group [ "..msg.to.id.." ]") return end if is_realm(msg) then return 'Error: Already a realm.' end savelog(msg.to.id, name_log.." ["..msg.from.id.."] added group [ "..msg.to.id.." ]") print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'add' and matches[2] == 'realm' then if not is_sudo(msg) then-- Admin only savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to add realm [ "..msg.to.id.." ]") return end if is_group(msg) then return 'Error: Already a group.' end savelog(msg.to.id, name_log.." ["..msg.from.id.."] added realm [ "..msg.to.id.." ]") print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm") return realmadd(msg) end if matches[1] == 'rem' and not matches[2] then if not is_admin1(msg) and not is_support(msg.from.id) then-- Admin only savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to remove group [ "..msg.to.id.." ]") return end if not is_group(msg) then return 'Error: Not a group.' end savelog(msg.to.id, name_log.." ["..msg.from.id.."] removed group [ "..msg.to.id.." ]") print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'rem' and matches[2] == 'realm' then if not is_sudo(msg) then-- Sudo only savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to remove realm [ "..msg.to.id.." ]") return end if not is_realm(msg) then return 'Error: Not a realm.' end savelog(msg.to.id, name_log.." ["..msg.from.id.."] removed realm [ "..msg.to.id.." ]") print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm") return realmrem(msg) end end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then return automodadd(msg) end --[[Experimental if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "super_group" then local chat_id = get_receiver(msg) users = {[1]="user#id167472799",[2]="user#id170131770"} for k,v in pairs(users) do chat_add_user(chat_id, v, ok_cb, false) end --chat_upgrade(chat_id, ok_cb, false) end ]] if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then return autorealmadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return 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' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_del_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 savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") 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 end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return 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 local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") 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) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") 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 'Please send me new group photo now' end if matches[1] == 'promote' and not matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only the owner can prmote new moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, promote_by_reply, false) end end if matches[1] == 'promote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can promote" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'promote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return resolve_username(username, promote_demote_res, cbres_extra) end if matches[1] == 'demote' and not matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only the owner can demote moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, demote_by_reply, false) end end if matches[1] == 'demote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then return "You can't demote yourself" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'demote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return resolve_username(username, promote_demote_res, cbres_extra) end if matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'set' then if matches[2] == 'rules' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end end --Begin chat settings if matches[1] == 'lock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ") return lock_group_leave(msg, data, target) end if matches[2] == 'links' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link posting ") return lock_group_links(msg, data, target) end if matches[2]:lower() == 'rtl' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked rtl chars. in names") return lock_group_rtl(msg, data, target) end if matches[2] == 'sticker' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked sticker posting") return lock_group_sticker(msg, data, target) end if matches[2] == 'contacts' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked contact posting") return lock_group_contacts(msg, data, target) end end if matches[1] == 'unlock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ") return unlock_group_leave(msg, data, target) end if matches[2] == 'links' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link posting") return unlock_group_links(msg, data, target) end if matches[2]:lower() == 'rtl' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked RTL chars. in names") return unlock_group_rtl(msg, data, target) end if matches[2] == 'sticker' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked sticker posting") return unlock_group_sticker(msg, data, target) end if matches[2] == 'contacts' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked contact posting") return unlock_group_contacts(msg, data, target) end end --End chat settings --Begin Chat mutes if matches[1] == 'mute' and is_owner(msg) then local chat_id = msg.to.id if matches[2] == 'audio' then local msg_type = 'Audio' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: mute "..msg_type) mute(chat_id, msg_type) return "Group "..matches[2].." has been muted" else return "Group mute "..matches[2].." is already on" end end if matches[2] == 'photo' then local msg_type = 'Photo' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: mute "..msg_type) mute(chat_id, msg_type) return "Group "..matches[2].." has been muted" else return "Group mute "..matches[2].." is already on" end end if matches[2] == 'video' then local msg_type = 'Video' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: mute "..msg_type) mute(chat_id, msg_type) return "Group "..matches[2].." has been muted" else return "Group mute "..matches[2].." is already on" end end if matches[2] == 'gifs' then local msg_type = 'Gifs' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." have been muted" else return "Group mute "..msg_type.." is already on" end end if matches[2] == 'documents' then local msg_type = 'Documents' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." have been muted" else return "Group mute "..msg_type.." is already on" end end if matches[2] == 'text' then local msg_type = 'Text' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: mute "..msg_type) mute(chat_id, msg_type) return "Group text has been muted" else return "Group mute text is already on" end end if matches[2] == 'all' then local msg_type = 'All' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: mute "..msg_type) mute(chat_id, msg_type) return "Mute "..msg_type.." has been enabled" else return "Mute "..msg_type.." is already on" end end end if matches[1] == 'unmute' and is_owner(msg) then local chat_id = msg.to.id if matches[2] == 'audio' then local msg_type = 'Audio' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: unmute "..msg_type) unmute(chat_id, msg_type) return "Group "..msg_type.." has been unmuted" else return "Group mute "..msg_type.." is already off" end end if matches[2] == 'photo' then local msg_type = 'Photo' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: unmute "..msg_type) unmute(chat_id, msg_type) return "Group "..msg_type.." has been unmuted" else return "Group mute "..msg_type.." is already off" end end if matches[2] == 'Video' then local msg_type = 'Video' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: unmute "..msg_type) unmute(chat_id, msg_type) return "Group "..msg_type.." has been unmuted" else return "Group mute "..msg_type.." is already off" end end if matches[2] == 'gifs' then local msg_type = 'Gifs' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." have been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'documents' then local msg_type = 'Documents' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." have been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'text' then local msg_type = 'Text' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: unmute message") unmute(chat_id, msg_type) return "Group text has been unmuted" else return "Group mute text is already off" end end if matches[2] == 'all' then local msg_type = 'All' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: unmute "..msg_type) unmute(chat_id, msg_type) return "Mute "..msg_type.." has been disabled" else return "Mute "..msg_type.." is already disabled" end end end --Begin chat muteuser if matches[1] == "muteuser" and is_momod(msg) then local chat_id = msg.to.id local hash = "mute_user"..chat_id local user_id = "" if type(msg.reply_id) ~= "nil" then local receiver = get_receiver(msg) local get_cmd = "mute_user" get_message(msg.reply_id, mute_user_callback, {receiver = receiver, get_cmd = get_cmd}) elseif matches[1] == "muteuser" and string.match(matches[2], '^%d+$') then local user_id = matches[2] if is_muted_user(chat_id, user_id) then mute_user(chat_id, user_id) return "["..user_id.."] removed from the muted users list" else unmute_user(chat_id, user_id) return "["..user_id.."] added to the muted user list" end elseif matches[1] == "muteuser" and not string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local get_cmd = "mute_user" local username = matches[2] local username = string.gsub(matches[2], '@', '') resolve_username(username, callback_mute_res, {receiver = receiver, get_cmd = get_cmd}) end end --End Chat muteuser if matches[1] == "muteslist" and is_momod(msg) then local chat_id = msg.to.id if not has_mutes(chat_id) then set_mutes(chat_id) return mutes_list(chat_id) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup muteslist") return mutes_list(chat_id) end if matches[1] == "mutelist" and is_momod(msg) then local chat_id = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup mutelist") return muted_user_list(chat_id) end if matches[1] == 'settings' and is_momod(msg) then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, target) end if matches[1] == 'public' and is_momod(msg) then local target = msg.to.id if matches[2] == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public") return set_public_membermod(msg, data, target) end if matches[2] == 'no' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public") return unset_public_membermod(msg, data, target) end end if msg.to.type == 'chat' then if matches[1] == 'newlink' and not is_realm(msg) then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'link' then if not is_momod(msg) then return "For moderators only!" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end if matches[1] == 'setowner' and matches[2] then if not is_owner(msg) then return "For owner only!" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = matches[2].." added as owner" return text end if matches[1] == 'setowner' and not matches[2] then if not is_owner(msg) then return "only for the owner!" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, setowner_by_reply, false) end end end if matches[1] == 'owner' then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "no owner,ask admins in support groups to set owner for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "Group owner is ["..group_owner..']' end if matches[1] == 'setgpowner' then local receiver = "chat#id"..matches[2] if not is_admin1(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as owner" send_large_msg(receiver, text) return end if matches[1] == 'setflood' then if not is_momod(msg) then return "For moderators only!" end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Group flood has been set to '..matches[2] end if msg.to.type == 'chat' then if matches[1] == 'clean' then if not is_owner(msg) then return "Only owner can clean" end if matches[2] == 'member' then if not is_owner(msg) then return "Only admins can clean members" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' then local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'about' then local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if msg.to.type == 'chat' then if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin1(msg) then return nil end if not is_realm(msg) then local receiver = get_receiver(msg) return modrem(msg), print("Closing Group..."), chat_info(receiver, killchat, {receiver=receiver}) else return 'This is a realm' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin1(msg) then return nil end if not is_group(msg) then local receiver = get_receiver(msg) return realmrem(msg), print("Closing Realm..."), chat_info(receiver, killrealm, {receiver=receiver}) else return 'This is a group' end end if matches[1] == 'help' then if not is_momod(msg) or is_realm(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'res' then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") resolve_username(username, callbackres, cbres_extra) return end if matches[1] == 'kickinactive' then --send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]') if not is_momod(msg) then return 'Only a moderator can kick inactive users' end local num = 1 if matches[2] then num = matches[2] end local chat_id = msg.to.id local receiver = get_receiver(msg) return kick_inactive(chat_id, num, receiver) end end end end local function pre_process(msg) if not msg.text and msg.media then msg.text = '['..msg.media.type..']' end return msg end return { patterns = { "^[#!/](add)$", "^[#!/](add) (realm)$", "^[#!/](rem)$", "^[#!/](rem) (realm)$", "^[#!/](rules)$", "^[#!/](about)$", "^[#!/](setname) (.*)$", "^[#!/](setphoto)$", "^[#!/](promote) (.*)$", "^[#!/](promote)", "^[#!/](help)$", "^[#!/](clean) (.*)$", "^[#!/](kill) (chat)$", "^[#!/](kill) (realm)$", "^[#!/](demote) (.*)$", "^[#!/](demote)", "^[#!/](set) ([^%s]+) (.*)$", "^[#!/](lock) (.*)$", "^[#!/](setowner) (%d+)$", "^[#!/](setowner)", "^[#!/](owner)$", "^[#!/](res) (.*)$", "^[#!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id) "^[#!/](unlock) (.*)$", "^[#!/](setflood) (%d+)$", "^[#!/](settings)$", "^[#!/](public) (.*)$", "^[#!/](modlist)$", "^[#!/](newlink)$", "^[#!/](link)$", "^[#!/]([Mm]ute) ([^%s]+)$", "^[#!/]([Uu]nmute) ([^%s]+)$", "^[#!/]([Mm]uteuser)$", "^[#!/]([Mm]uteuser) (.*)$", "^[#!/]([Mm]uteslist)$", "^[#!/]([Mm]utelist)$", "^[#!/](kickinactive)$", "^[#!/](kickinactive) (%d+)$", "%[(document)%]", "%[(photo)%]", "%[(video)%]", "%[(audio)%]", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process } end
gpl-2.0
Ninjistix/darkstar
scripts/globals/spells/burst_ii.lua
4
1264
----------------------------------------- -- Spell: Burst II -- Deals lightning damage to an enemy and lowers its resistance against earth. ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster, target, spell) return 0; end; function onSpellCast(caster, target, spell) local spellParams = {}; spellParams.hasMultipleTargetReduction = false; spellParams.resistBonus = 1.0; spellParams.V0 = 800; spellParams.V50 = 900; spellParams.V100 = 1000; spellParams.V200 = 1200; spellParams.M0 = 2; spellParams.M50 = 2; spellParams.M100 = 2; spellParams.M200 = 2; if (caster:getMerit(MERIT_BURST_II) ~= 0) then spellParams.AMIIburstBonus = (caster:getMerit(MERIT_BURST_II) - 1) * 0.03; spellParams.AMIIaccBonus = (caster:getMerit(MERIT_BURST_II) - 1) * 5; end -- no point in making a separate function for this if the only thing they won't have in common is the name handleNinjutsuDebuff(caster,target,spell,30,10,MOD_EARTHRES); return doElementalNuke(caster, spell, target, spellParams); end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Port_San_dOria/npcs/Coribalgeant.lua
5
1075
----------------------------------- -- Area: Port San d'Oria -- NPC: Coribalgeant -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_San_dOria/TextIDs"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; function onTrigger(player,npc) player:startEvent(599); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
hvbommel/domoticz
dzVents/runtime/lodash.lua
9
67279
--- -- lodash for lua -- @module lodash -- @author Ted Moghimi -- @license MIT -- 20200120; added _.isEqual ( http://lua-users.org/lists/lua-l/2014-09/msg00463.html ) local _ = { _VERSION = '0.03' } --- Array -- @section Array --- -- Creates an array of elements split into groups the length of size. -- If collection can’t be split evenly, the final chunk will be the -- remaining elements. -- @usage local t = _.chunk({'x', 'y', 'z', 1, 2, 3, 4, true , false}, 4) -- _.print(t) -- --> {{"x", "y", "z", 1}, {2, 3, 4, true}, {false}} -- -- @param array The array to process. -- @param[opt=1] size The length of each chunk. -- @return the new array containing chunks. _.chunk = function (array, size) local t = {} local size = size == 0 and 1 or size or 1 local c, i = 1, 1 while true do t[i] = {} for j = 1, size do _.push(t[i], array[c]) c = c + 1 end if _.gt(c, #array) then break end i = i + 1 end return t end --- -- Creates an array with all falsey values removed. The values false, -- nil are falsey. -- @usage local t = _.compact({'x', 'y', nil, 1, 2, 3, false, true , false}) -- _.print(t) -- --> {"x", "y", 1, 2, 3, true} -- -- @param array The array to compact -- @return Returns the new array of filtered values _.compact = function (array) local t = {} for k, v in pairs(array) do if v then _.push(t, v) end end return t end --- -- Creates an array of unique array values not included in the other -- provided arrays. -- @usage _.print(_.difference({3, 1, 2, 9, 5, 9}, {4, 5}, {9, 1})) -- --> {3, 2} -- -- @param array The array to inspect. -- @param ... The arrays of values to exclude. -- @return Returns the new array of filtered values. _.difference = function (array, ...) local t = {} local c = 1 local tmp = _.table(...) for k, v in ipairs(array) do while not _.isNil(tmp[c]) do for j, v2 in ipairs(tmp[c]) do if v == v2 then goto doubleBreak end end c = c + 1 end _.push(t, v) ::doubleBreak:: c = 1 end return t end --- -- Creates a slice of array with n elements dropped from the beginning. -- @usage _.print(_.drop({1, 2, 3, 4, 5, 6}, 2)) -- --> {3, 4, 5, 6} -- -- @param array The array to query. -- @param[opt=1] n The number of elements to drop. -- @return Returns the slice of array. _.drop = function (array, n) local n = n or 1 return _.slice(array, n + 1) end local callIteratee = function (predicate, selfArg, ...) local result local predicate = predicate or _.identity if selfArg then result = predicate(selfArg, ...) else result = predicate(...) end return result end --- -- Creates a slice of array with n elements dropped from the end. -- @usage _.print(_.dropRight({1, 2, 3, 4, 5, 6}, 2)) -- --> {1, 2, 3, 4} -- -- @param array The array to query. -- @param[opt=1] n The number of elements to drop. -- @return Returns the slice of array. _.dropRight = function (array, n) local n = n or 1 return _.slice(array, nil, #array - n) end local dropWhile = function(array, predicate, selfArg, start, step, right) local t = {} local c = start while not _.isNil(array[c]) do ::cont:: if #t == 0 and callIteratee(predicate, selfArg, array[c], c, array) then c = c + step goto cont end if right then _.enqueue(t, array[c]) else _.push(t, array[c]) end c = c + step end return t end --- -- Creates a slice of array excluding elements dropped from the end. -- Elements are dropped until predicate returns falsey. -- @usage _.print(_.dropRightWhile({1, 5, 2, 3, 4, 5, 4, 4}, function(n) -- return n > 3 -- end)) -- --> {1, 5, 2, 3} -- -- @param array The array to query. -- @param[opt=_.identity] predicate The function to invoked per iteratin. -- @param[opt] selfArg The self binding of predicate. -- @return Return the slice of array. _.dropRightWhile = function(array, predicate, selfArg) return dropWhile(array, predicate, selfArg, #array, -1, true) end --- -- Creates a slice of array excluding elements dropped from the beginning. -- Elements are dropped until predicate returns falsey. -- @usage _.print(_.dropWhile({1, 2, 2, 3, 4, 5, 4, 4, 2}, function(n) -- return n < 3 -- end)) -- --> {3, 4, 5, 4, 4, 2} -- -- @param array The array to query. -- @param[opt=_.idenitity] predicate The function invoked per iteration. -- @param[opt] selfArg The self binding of predicate. -- @return Return the slice of array. _.dropWhile = function(array, predicate, selfArg) return dropWhile(array, predicate, selfArg, 1, 1) end --- -- Push value to first element of array --- --@Usage local array = {1, 2, 3, 4} -- _.enqueue(array, 5) -- _print(array) -- --> {5, 1, 2, 3, 4} -- -- @param array; Array to modify -- @param: value; Value to fill first element of Array with -- @return array _.enqueue = function (array, value) return table.insert(array, 1, value) end --- -- Fills elements of array with value from start up to, including, end. -- @usage local array = {1, 2, 3, 4} -- _.fill(array, 'x', 2, 3) -- _.print(array) -- --> {1, "x", "x", 4} -- -- @param array The array to fill. -- @param value The value to fill array with. -- @param[opt=1] start The start position. -- @param[opt=#array] stop The end position. -- @return Returns array. _.fill = function (array, value, start, stop) local start = start or 1 local stop = stop or #array for i=start, stop, start > stop and -1 or 1 do array[i] = value end return array end local findIndex = function(array, predicate, selfArg, start, step) local c = start while not _.isNil(array[c]) do if callIteratee(predicate, selfArg, array[c], c, array) then return c end c = c + step end return -1 end --- -- This method is like [_.find](#_.find) except that it returns the index of the -- first element predicate returns truthy for instead of the element itself. -- @usage _.print(_.findIndex({{a = 1}, {a = 2}, {a = 3}, {a = 2}, {a = 3}}, function(v) -- return v.a == 3 -- end)) -- --> 3 -- -- @param array The array to search. -- @param[opt=_.idenitity] predicate The function invoked per iteration. -- @param[opt] selfArg The self binding of predicate. -- @return Returns the index of the found element, else -1. _.findIndex = function (array, predicate, selfArg) return findIndex(array, predicate, selfArg, 1, 1) end --- -- This method is like [_.findIndex](#_.findIndex) except that it iterates over -- elements of collection from right to left. -- @usage _.print(_.findLastIndex({{a = 1}, {a = 2}, {a = 3}, {a = 2}, {a = 3}}, function(v) -- return v.a == 3 -- end)) -- --> 5 -- -- @param array The array to search. -- @param[opt=_.idenitity] predicate The function invoked per iteration. -- @param[opt] selfArg The self binding of predicate. -- @return Returns the index of the found element, else -1. _.findLastIndex = function (array, predicate, selfArg) return findIndex(array, predicate, selfArg, #array, -1) end --- -- Gets the first element of array. -- @usage _.print(_.first({'w', 'x', 'y', 'z'})) -- --> w -- -- @param array The array to query. -- @return Returns the first element of array. _.first = function (array) return array[1] end --- -- Flattens a nested array. -- If isDeep is true the array is recursively flattened, otherwise -- it’s only flattened a single level. -- @usage _.print(_.flatten({1, 2, {3, 4, {5, 6}}})) -- --> {1, 2, 3, 4, {5, 6}} -- _.print(_.flatten({1, 2, {3, 4, {5, 6}}}, true)) -- --> {1, 2, 3, 4, 5, 6} -- -- @param array The array to flatten. -- @param isDeep Specify a deep flatten -- @return Returns the new flattened array. _.flatten = function(array, isDeep) local t = {} for k, v in ipairs(array) do if _.isTable(v) then local childeren if isDeep then childeren = _.flatten(v) else childeren = v end for k2, v2 in ipairs(childeren) do _.push(t, v2) end else _.push(t, v) end end return t end --- -- Recursively flattens a nested array. -- @usage _.print(_.flattenDeep({1, 2, {3, 4, {5, 6}}})) -- --> {1, 2, 3, 4, 5, 6} -- -- @param array The array to flatten. -- @return Returns the new flattened array. _.flattenDeep = function (array) return _.flatten(array, true) end --- -- Gets the index at which the first occurrence of value is found in array. -- @usage _.print(_.indexOf({2, 3, 'x', 4}, 'x')) -- --> 3 -- -- @param array The array to search. -- @param value The value to search for. -- @param[opt=1] fromIndex The index to search from. -- @return Returns the index of the matched value, else -1. _.indexOf = function (array, value, fromIndex) return _.findIndex(array, function(n) return n == value end) end -- --- -- Gets all but the last element of array. -- @usage _.print(_.initial({1, 2, 3, 'a'})) -- --> {1, 2, 3} -- -- @param array The array to query. -- @return Returns the slice of array. _.initial = function (array) return _.slice(array, nil, #array - 1) end -- --- -- Creates an array of unique values that are included in all of the -- provided arrays. -- @usage _.print(_.intersection({1, 2}, {4, 2}, {2, 1})) -- --> {2} -- -- @param The arrays to inspect. -- @return Returns the new array of shared values. _.intersection = function (...) local tmp = _.table(...) local first = table.remove(tmp, 1) local t = {} for i, v in ipairs(first) do local notFound = false for i2, v2 in ipairs(tmp) do if _.indexOf(v2, v) == -1 then notFound = true break end end if not notFound then _.push(t, v) end end return t -- body end --- -- Gets the last element of array. -- @usage _.print(_.last({'w', 'x', 'y', 'z'})) -- --> z -- -- @param array The array to query. -- @return Returns the last element of array. _.last = function(array) return array[#array] end --- -- This method is like [_.indexOf](#_.indexOf) except that it iterates -- over elements of array from right to left. -- @usage _.print(_.lastIndexOf({2, 3, 'x', 4, 'x', 5}, 'x')) -- --> 5 -- -- @param array The array to search. -- @param value The value to search for. -- @param[opt=#array] fromIndex The index to search from. -- @return Returns the index of the matched value, else -1. _.lastIndexOf = function (array, value, fromIndex) return _.findLastIndex(array, function(n) return n == value end) end --- -- Removes all provided values from array. -- @usage local array = {1, 2, 3, 4, 5, 4, 1, 2, 3} -- _.pull(array, 2, 3) -- _.print(array) -- --> {1, 4, 5, 4, 1} -- @param array The array to modify. -- @param ... The values to remove. -- @return Returns array _.pull = function(array, ...) local i = 1 while not _.isNil(array[i]) do for k, v in ipairs(_.table(...)) do if array[i] == v then table.remove(array, i) goto cont end end i = i + 1 ::cont:: end return array end _.push = function (array, value) return table.insert(array, value) end --- -- Removes elements from array corresponding to the given indexes and -- returns an array of the removed elements. Indexes may be specified -- as an array of indexes or as individual arguments. -- @usage local array = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'} -- local t = _.pullAt(array, 4, 9, 8) -- _.print(array) -- --> {"a", "b", "c", "e", "f", "g", "j"} -- _.print(t) -- --> {"d", "h", "i"} -- -- @param array The array to modify. -- @param ... The indexes of elements to remove -- @return Returns the new array of removed elements. _.pullAt = function (array, ...) local t = {} local tmp = _.table(...) table.sort(tmp, function(a, b) return _.gt(a, b) end) for i, index in ipairs(tmp) do _.enqueue(t, table.remove(array, index)) end return t end --- -- Removes all elements from array that predicate returns truthy for -- and returns an array of the removed elements. -- @usage local array = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 1, 2, 3, 5, 4} -- local t = _.remove(array, function(value) -- return value > 4 -- end) -- _.print(array) -- --> {1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4} -- _.print(t) -- --> {5, 6, 7, 5, 6, 5} -- -- @param array The array to modify. -- @param predicate The function invoked per iteration. -- @return Returns the new array of removed elements _.remove = function(array, predicate) local t = {} local c = 1 local predicate = predicate or _.identity while not _.isNil(array[c]) do if predicate(array[c], c, array) then _.push(t, table.remove(array, c)) goto cont end c = c + 1 ::cont:: end return t end --- -- Gets all but the first element of array. -- @usage _.print(_.rest({1, 2, 3, 'a'})) -- --> {2, 3, 'a'} -- @param array The array to query. -- @return Returns the slice ofa array. _.rest = function (array) return _.slice(array, 2, #array) end --- -- Reverses the array so the first element becomes the last, the second -- element becomes the second to last, and so on. -- @usage _.print(_.reverse({1, 2, 3, 'a', 'b'})) -- --> {'b', 'a', 3, 2, 1} -- -- @param array The array to mutate. -- @return Returns the new reversed array. _.reverse = function (array) local t = {} for i, v in ipairs(array) do _.enqueue(t, v) end return t end --- -- Creates a slice of array from start up to, including, end. -- @usage _.print(_.slice({1, 2, 3, 4, 5, 6}, 2, 3)) -- --> {2, 3} -- -- @param array The array to slice. -- @param[opt=1] start The start position. -- @param[opt=#array] stop The end position -- @return Returns the slice of array. _.slice = function (array, start, stop) local start = start or 1 local stop = stop or #array local t = {} for i=start, stop do t[i - start + 1] = array[i] end return t end --- -- Creates a slice of array with n elements taken from the beginning. -- @usage _.print(_.take({1, 2, 3, 4, 5}, 3)) -- --> {1, 2, 3} -- -- @param array The array to query. -- @param[opt=1] n The number of elements to take. -- @return Returns the slice of array. _.take = function(array, n) local n = n or 1 return _.slice(array, 1, n) end --- -- Creates a slice of array with n elements taken from the end. -- @usage _.print(_.takeRight({1, 2, 3, 4, 5}, 3)) -- --> {3, 4, 5} -- -- @param array The array to query. -- @param[opt=1] n The number of elements to take. -- @return Returns the slice of array. _.takeRight = function (array, n) local n = n or 1 return _.slice(array, #array - n +1) end local takeWhile = function(array, predicate, selfArg, start, step, right) local t = {} local c = start while not _.isNil(array[c]) do if callIteratee(predicate, selfArg, array[c], c, array) then if right then _.enqueue(t, array[c]) else _.push(t, array[c]) end else break end c = c + step end return t end --- -- Creates a slice of array with elements taken from the end. Elements -- are taken until predicate returns falsey. The predicate is bound to -- selfArg and invoked with three arguments: (value, index, array). -- @usage _.print(_.takeRightWhile({1, 2, 3, 4, 5, 6, 7, 8}, function(n) -- return n > 4 -- end)) -- --> {5, 6, 7, 8} -- -- @param array The array to query. -- @param predicate The function invoked per iteration. -- @param selfArg The self binding of predicate. _.takeRightWhile = function (array, predicate, selfArg) return takeWhile(array, predicate, selfArg, #array, -1, true) end --- -- Creates an array of unique values, from all of the -- provided arrays. -- @usage _.print(_.union({1, 2}, {4, 2}, {2, 1})) -- --> {1, 2, 4} -- -- @param ... The arrays to inspect _.union = function (...) local tmp = _.table(...) local t = {} for i, array in ipairs(tmp) do for i2, v in ipairs(array) do if _.indexOf(t, v) == -1 then _.push(t, v) end end end return t end --- -- Creates a slice of array with elements taken from the beginning. Elements -- are taken until predicate returns falsey. The predicate is bound to -- selfArg and invoked with three arguments: (value, index, array). -- @usage _.print(_.takeWhile({1, 2, 3, 4, 5, 6, 7, 8}, function(n) -- return n < 5 -- end)) -- --> {1, 2, 3, 4} -- -- @param array The array to query. -- @param predicate The function invoked per iteration. -- @param selfArg The self binding of predicate. _.takeWhile = function (array, predicate, selfArg) return takeWhile(array, predicate, selfArg, 1, 1) end --- -- Creates a duplicate-free version of an array in which only the first -- occurence of each element is kept. If an iteratee function is provided -- it’s invoked for each element in the array to generate the criterion -- by which uniqueness is computed. The iteratee is bound to thisArg and -- invoked with three arguments: (value, index, array). -- @usage _.print(_.uniq({1, 3, 2, 2})) -- --> {1, 3, 2} --_.print(_.uniq({{x=1}, {x=2}, {x=2}, {x=3}, {x=1}}, function(n) -- return n.x -- end)) -- --> {{["x"]=1}, {["x"]=2}, {["x"]=3}} -- -- @param array The array to inspect. -- @param iteratee The function invoked per iteration. -- @param selfArg The self binding of predicate. -- @return Returns the new duplicate-value-free array. _.uniq = function(array, iteratee, selfArg) local t = {} local results = {} for k, v in ipairs(array) do local r = callIteratee(iteratee, selfArg, v, k, array) if _.indexOf(results, r) == -1 then _.push(t, v) end _.push(results, r) end return t end --- -- The inverse of _.pairs; this method returns an object composed from -- arrays of property names and values. Provide either a single two dimensional -- array, e.g. [[key1, value1], [key2, value2]] or two arrays, one of -- property names and one of corresponding values. -- @usage _.print(_.zipObject({{'fred', 30}, {'alex', 20}})) -- --> {["alex"]=20, ["fred"]=30} -- _.print(_.zipObject({'fred', 'alex'}, {30, 20})) -- --> {["alex"]=20, ["fred"]=30} -- -- @param ... The properties/values -- @return Returns the new object. _.zipObject = function (...) local tmp = _.table(...) local t = {} if #tmp == 1 then for i, pair in ipairs(tmp[1]) do t[pair[1]] = pair[2] end else for i = 1, #tmp[1] do t[tmp[1][i]] = tmp[2][i] end end return t end --- -- This method is like [_.zip](#_.zip) except that it accepts an array of grouped -- elements and creates an array regrouping the elements to their pre-zip -- configuration. -- @usage local t = _.zip({'a', 'b', 'c'}, {1, 2, 3}, {10, 20, 30}) -- _.print(t) -- --> {{"a", 1, 10}, {"b", 2, 20}, {"c", 3, 30}} -- _.print(_.unzip(t)) -- --> {{"a", "b", "c"}, {1, 2, 3}, {10, 20, 30}} -- -- @param array The array of grouped elements to process. -- @return Returns the new array of regrouped elements. _.unzip = function (array) return _.zip(_.args(array)) end --- -- Creates an array excluding all provided values -- @usage _.print(_.without({1,1, 2, 3, 2, 3, 5, 5, 1, 2}, 5, 1)) -- --> {2, 3, 2, 3, 2} -- -- @param array The array to filter. -- @param ... The values to exclude. -- @return Returns the new array of filtered values. _.without = function (array, ...) local t = {} for i, v in ipairs(array) do local args = _.table(...) if _.indexOf(args, v) == -1 then _.push(t, v) end end return t end --- -- Creates an array of grouped elements, the first of which contains -- the first elements of the given arrays, the second of which contains -- the second elements of the given arrays, and so on. -- @usage local t = _.zip({'a', 'b', 'c'}, {1, 2, 3}, {10, 20, 30}) -- _.print(t) -- --> {{"a", 1, 10}, {"b", 2, 20}, {"c", 3, 30}} -- -- @param ... The arrays to process -- @return Returns the new array of grouped elements. _.zip = function (...) local t = {} for i, array in ipairs(_.table(...)) do for j, v in ipairs(array) do t[j] = t[j] or {} t[j][i] = v end end return t end --- Collection -- @section Collection --- -- Creates an array of elements corresponding to the given keys, -- or indexes, of collection. Keys may be specified as individual -- arguments or as arrays of keys. -- @usage _.print(_.at({'1', '2', '3', '4', a='a', b='b'}, {1, 2}, 'b')) -- --> {"1", "2", "b"} -- -- @param collection The collection to iterate over. -- @param ... The property names or indexes of elements to pick, -- specified individually or in arrays. -- @return Return the new array of picked elements. _.at = function (collection, ...) local t = {} for k, key in ipairs(_.table(...)) do if _.isTable(key) then for k, key in ipairs(key) do _.push(t, collection[key]) end else _.push(t, collection[key]) end end return t end --- -- Creates an object composed of keys generated from the results of -- running each element of collection through iteratee. The corresponding -- value of each key is the number of times the key was returned by -- iteratee. The iteratee is bound to selfArg and invoked with three arguments: -- (value, index|key, collection). -- -- @usage _.print(_.countBy({4.3, 6.1, 6.4}, function(n) -- return math.floor(n) -- end)) -- --> {[4]=1, [6]=2} -- -- @param collection The collection to iterate over. (table|string) -- @param[opt=_.identity] iteratee The function invoked per iteration. -- @param[opt] selfArg The self binding of predicate. -- @return Returns the composed aggregate object. _.countBy = function (collection, iteratee, selfArg) local t = {} for k, v in _.iter(collection) do local r = _.str( callIteratee(iteratee, selfArg, v, k, collection) ) if _.isNil(t[r]) then t[r] = 1 else t[r] = t[r] + 1 end end return t end --- -- Creates an object composed of keys generated from the results of -- running each element of collection through iteratee. The corresponding -- value of each key is an array of the elements responsible for generating -- the key. The iteratee is bound to selfArg and invoked with three arguments: -- (value, index|key, collection). -- @usage _.print(_.groupBy({4.3, 6.1, 6.4}, function(n) -- return math.floor(n) -- end)) -- --> {[4]={4.3}, [6]={6.1, 6.4}} -- -- @param collection The collection to iterate over. (table|string) -- @param[opt=_.identity] iteratee The function invoked per iteration. -- @param[opt] selfArg The self binding of predicate. -- @return Returns the composed aggregate object. _.groupBy = function (collection, iteratee, selfArg) local t = {} for k, v in _.iter(collection) do local r = _.str( callIteratee(iteratee, selfArg, v, k, collection) ) if _.isNil(t[r]) then t[r] = {v} else _.push(t[r], v) end end return t end --- -- Creates an object composed of keys generated from the results of -- running each element of collection through iteratee. The corresponding -- value of each key is the last element responsible for generating the key. -- The iteratee function is bound to selfArg and invoked with three arguments: -- (value, index|key, collection). -- @usage local keyData = { -- {dir='l', a=1}, -- {dir='r', a=2} -- } -- _.print('40.indexBy :', _.indexBy(keyData, function(n) -- return n.dir -- end)) -- --> {["l"]={[a]=1, [dir]="l"}, ["r"]={[a]=2, [dir]="r"}} -- -- @param collection The collection to iterate over. (table|string) -- @param[opt=_.identity] iteratee The function invoked per iteration. -- @param[opt] selfArg The self binding of predicate. -- @return Returns the composed aggregate object. _.indexBy = function (collection, iteratee, selfArg) local t = {} for k, v in _.iter(collection) do local r = _.str( callIteratee(iteratee, selfArg, v, k, collection) ) t[r] = v end return t end --- -- Checks if predicate returns truthy for all elements of collection. -- The predicate is bound to selfArg and invoked with three arguments: -- (value, index|key, collection). -- @usage _.print(_.every({1, 2, 3, 4, '5', 6}, _.isNumber)) -- --> false -- _.print(_.every({1, 2, 3, 4, 5, 6}, _.isNumber)) -- --> true -- -- @param collection The collection to iterate over. (table|string) -- @param[opt=_.identity] predicate The function invoked per iteration -- @param[opt] selfArg The self binding of predicate. _.every = function (collection, predicate, selfArg) for k, v in _.iter(collection) do if not callIteratee(predicate, selfArg, v, k, collection) then return false end end return true end local filter = function(collection, predicate, selfArg, reject) local t = {} for k, v in _.iter(collection) do local check = callIteratee(predicate, selfArg, v, k, collection) if reject then if not check then _.push(t, v) end else if check then _.push(t, v) end end end return t end --- -- Iterates over elements of collection, returning an array of all -- elements predicate returns truthy for. The predicate is bound to -- selfArg and invoked with three arguments: (value, index|key, collection). -- @usage _.print(_.filter({1, 2, 3, 4, '5', 6, '7'}, _.isNumber)) -- --> {1, 2, 3, 4, 6} -- -- @param collection The collection to iterate over. (table|string) -- @param[opt=_.identity] predicate The function invoked per iteration -- @param[opt] selfArg The self binding of predicate. _.filter = function (collection, predicate, selfArg) return filter(collection, predicate, selfArg) end --- -- Iterates over elements of collection invoking iteratee for each element. -- The iteratee is bound to selfArg and invoked with three arguments: -- (value, index|key, collection). Iteratee functions may exit iteration -- early by explicitly returning false. -- -- @param collection The collection to iterate over. (table|string) -- @param[opt=_.identity] predicate The function invoked per iteration -- @param[opt] selfArg The self binding of predicate. -- @return Returns collection. _.forEach = function (collection, predicate, selfArg) for k, v in _.iter(collection) do callIteratee(predicate, selfArg, v, k, collection) end return collection end --- -- This method is like [_.forEach](#_.forEach) except that it iterates -- over elements of collection from right to left. -- -- @param collection The collection to iterate over. (table|string) -- @param[opt=_.identity] predicate The function invoked per iteration -- @param[opt] selfArg The self binding of predicate. -- @return Returns collection. _.forEachRight = function (collection, predicate, selfArg) for k, v in _.iterRight(collection) do callIteratee(predicate, selfArg, v, k, collection) end return collection end --- -- Checks if target is in collection. -- @usage print(_.includes({1, 2, 'x', 3, ['5']=4, x=3, 5}, 'x')) -- --> true -- print(_.includes({1, 2, 'x', 3, ['5']=4, x=3, 5}, 'z')) -- --> false -- @param collection The collection to search -- @param target The value to search for. _.includes = function (collection, target) local result = _.find(collection, function (n) return n == target end) return result ~= nil end --- -- Invokes method of each element in collection, returning an array of the -- results of each invoked method. Any additional arguments are provided -- to each invoked method. func bound to, each element in collection. -- @usage _.print(_.invoke({'1.first', '2.second', '3.third'}, string.sub, 1, 1)) -- --> {"1", "2", "3"} -- -- @param collection The collection to iterate over. -- @param method The method to invoke per iteration. -- @param ... The arguments to invoke the method with. -- @return Returns the array of results. _.invoke = function (collection, method, ...) local t = {} for k, v in _.iter(collection) do _.push(t, callIteratee(method, v, ...)) end return t end --- -- Creates an array of values by running each element in collection through -- iteratee. The iteratee is bound to selfArg and invoked with three -- arguments: (value, index|key, collection). -- @usage _.print(_.map({1, 2, 3, 4, 5, 6, 7, 8, 9}, function(n) -- return n * n -- end)) -- --> {1, 4, 9, 16, 25, 36, 49, 64, 81} -- -- @param collection The collection to iterate over. (table|string) -- @param[opt=_.identity] iteratee The function invoked per iteration -- @param[opt] selfArg The self binding of predicate. _.map = function (collection, iteratee, selfArg) local t = {} for k, v in _.iter(collection) do t[k] = callIteratee(iteratee, selfArg, v, k, collection) end return t end --- -- Creates an array of elements split into two groups, the first of -- which contains elements predicate returns truthy for, while the second -- of which contains elements predicate returns falsey for. The predicate -- is bound to selfArg and invoked with three arguments: -- (value, index|key, collection). -- @usage _.print(_.partition({1, 2, 3, 4, 5, 6, 7}, function (n) -- return n > 3 -- end)) -- --> {{4, 5, 6, 7}, {1, 2, 3}} -- -- @param collection The collection to iterate over. (table|string) -- @param[opt=_.identity] predicate The function invoked per iteration -- @param[opt] selfArg The self binding of predicate. -- @return Returns the array of grouped elements. _.partition = function (collection, predicate, selfArg) local t = {{}, {}} for k, v in _.iter(collection) do if callIteratee(predicate, selfArg, v, k, collection) then _.push(t[1], v) else _.push(t[2], v) end end return t end --- -- Gets the property value of path from all elements in collection. -- @usage local users = { -- { user = 'barney', age = 36, child = {age = 5}}, -- { user = 'fred', age = 40, child = {age = 6} } -- } -- _.print(_.pluck(users, {'user'})) -- --> {"barney", "fred"} -- _.print(_.pluck(users, {'child', 'age'})) -- --> {5, 6} -- -- @param collection The collection to iterate over. -- @param path The path of the property to pluck. _.pluck = function (collection, path) local t = {} for k, value in _.iter(collection) do _.push(t, _.get(value, path)) end return t end --- -- Reduces collection to a value which is the accumulated result of -- running each element in collection through iteratee, where each -- successive invocation is supplied the return value of the previous. -- If accumulator is not provided the first element of collection is used -- as the initial value. The iteratee is bound to selfArg and invoked -- with four arguments: (accumulator, value, index|key, collection). -- @usage _.print(_.reduce({1, 2, 3}, function(total, n) -- return n + total; -- end)) -- --> 6 -- _.print(_.reduce({a = 1, b = 2}, function(result, n, key) -- result[key] = n * 3 -- return result; -- end, {})) -- --> {["a"]=3, ["b"]=6} -- -- @param collection The collection to iterate over. -- @param[opt=_.identity] iteratee The function invoked per iteration. -- @param[opt=<first element>] accumulator The initial value. -- @param[opt] selfArg The self binding of predicate. -- @return Returns the accumulated value. _.reduce = function (collection, iteratee, accumulator, selfArg) local accumulator = accumulator for k, v in _.iter(collection) do if _.isNil(accumulator) then accumulator = v else accumulator = callIteratee(iteratee, selfArg, accumulator, v, k, collection) end end return accumulator end --- -- This method is like _.reduce except that it iterates over elements -- of collection from right to left. -- @usage local array = {0, 1, 2, 3, 4, 5}; -- _.print(_.reduceRight(array, function(str, other) -- return str .. other -- end, '')) -- --> 543210 -- -- @param collection The collection to iterate over. -- @param[opt=_.identity] iteratee The function invoked per iteration. -- @param[opt=<first element>] accumulator The initial value. -- @param[opt] selfArg The self binding of predicate. -- @return Returns the accumulated value. _.reduceRight = function (collection, iteratee, accumulator, selfArg) local accumulator = accumulator for k, v in _.iterRight(collection) do if _.isNil(accumulator) then accumulator = v else accumulator = callIteratee(iteratee, selfArg, accumulator, v, k, collection) end end return accumulator end --- -- The opposite of [_.filter](#_.filter); this method returns the elements of -- collection that predicate does not return truthy for. -- @usage _.print(_.reject({1, 2, 3, 4, '5', 6, '7'}, _.isNumber)) -- --> {"5", "7"} -- -- @param collection The collection to iterate over. (table|string) -- @param[opt=_.identity] predicate The function invoked per iteration -- @param[opt] selfArg The self binding of predicate. _.reject = function (collection, predicate, selfArg) return filter(collection, predicate, selfArg, true) end --- -- Gets a random element or n random elements from a collection. -- @usage _.print(_.sample({1, 2, 3, a=4, b='x', 5, 23, 24}, 4)) -- --> {5, "x", 1, 23} -- _.print(_.sample({1, 2, 3, a=4, b='x', 5, 23, 24})) -- --> 4 -- -- @param collection The collection to sample. -- @param[opt=1] n The number of elements to sample. -- @return Returns the random sample(s). _.sample = function (collection, n) local n = n or 1 local t = {} local keys = _.keys(collection) for i=1, n do local pick = keys[_.random(1, #keys)] _.push(t, _.get(collection, {pick})) end return #t == 1 and t[1] or t end --- -- Gets the size of collection by returning its length for array-like -- values or the number of own enumerable properties for objects. -- @usage _.print(_.size({'abc', 'def'})) -- --> 2 -- _.print(_.size('abcdefg')) -- --> 7 -- _.print(_.size({a=1, b=2,c=3})) -- --> 3 -- -- @param collection The collection to inspect. -- @return Returns the size of collection. _.size = function (collection) local c = 0 for k, v in _.iter(collection) do c = c + 1 end return c end --- -- Checks if predicate returns truthy for any element of collection. -- The function returns as soon as it finds a passing value and does -- not iterate over the entire collection. The predicate is bound to -- selfArg and invoked with three arguments: (value, index|key, collection). -- -- @usage _.print(_.some({1, 2, 3, 4, 5, 6}, _.isString)) -- --> false -- _.print(_.some({1, 2, 3, 4, '5', 6}, _.isString)) -- --> true -- @param collection The collection to iterate over. (table|string) -- @param[opt=_.identity] predicate The function invoked per iteration -- @param[opt] selfArg The self binding of predicate. -- @return Returns true if any element passes the predicate check, else false. _.some = function (collection, predicate, selfArg) for k, v in _.iter(collection) do if callIteratee(predicate, selfArg, v, k, collection) then return true end end return false end --- -- Creates an array of elements, sorted in ascending order by the -- results of running each element in a collection through iteratee. -- The iteratee is bound to selfArg and -- invoked with three arguments: (value, index|key, collection). -- @usage local t = {1, 2, 3} -- _.print(_.sortBy(t, function (a) -- return math.sin(a) -- end)) -- --> {1, 3, 2} -- local users = { -- { user='fred' }, -- { user='alex' }, -- { user='zoee' }, -- { user='john' }, -- } -- _.print(_.sortBy(users, function (a) -- return a.user -- end)) -- --> {{["user"]="alex"}, {["user"]="fred"}, {["user"]="john"}, {["user"]="zoee"}} -- -- @param collection The collection to iterate over. -- @param[opt=_.identity] predicate The function invoked per iteration -- @param[opt] selfArg The self binding of predicate. -- @return Returns the new sorted array. _.sortBy = function (collection, predicate, selfArg) local t ={} local empty = true local previous for k, v in _.iter(collection) do if empty then _.push(t, v) previous = callIteratee(predicate, selfArg, v, k, collection) empty = false else local r = callIteratee(predicate, selfArg, v, k, collection) if _.lt(previous, r) then table.insert(t, v) previous = r else table.insert(t, #t, v) end end end return t end --- -- Iterates over elements of collection, returning the first element -- predicate returns truthy for. The predicate is bound to selfArg and -- invoked with three arguments: (value, index|key, collection). -- @usage _.print(_.find({{a = 1}, {a = 2}, {a = 3}, {a = 2}, {a = 3}}, function(v) -- return v.a == 3 -- end)) -- --> {[a]=3} -- -- @param collection The collection to search. (table|string) -- @param predicate The function invoked per iteration -- @param selfArg The self binding of predicate. _.find = function (collection, predicate, selfArg) for k, v in _.iter(collection) do if callIteratee(predicate, selfArg, v, k, collection) then return v end end end --- -- This method is like _.find except that it iterates over elements of -- collection from right to left. -- @usage _.findLast({{a = 1}, {a = 2}, {a = 3, x = 1}, {a = 2}, {a = 3, x = 2}}, -- function(v) -- return v.a == 3 -- end)) -- --> {[a]=3, [x]=2} -- -- @param collection The collection to search. (table|string) -- @param predicate The function invoked per iteration -- @param selfArg The self binding of predicate. _.findLast = function (collection, predicate, selfArg) for k, v in _.iterRight(collection) do if callIteratee(predicate, selfArg, v, k, collection) then return v end end end --- Function -- @section Function --- -- This method creates a function that invokes func once it’s called n -- or more times. -- @usage local printAfter3 = _.after(3, print) -- for i = 1, 5 do -- printAfter3('done', i) -- end -- --> done 4 -- --> done 5 -- -- @param n The number of calls before func invoked. -- @param func The function to restrict. -- @return Returns the new restricted function. _.after = function(n, func) local i = 1 return function(...) if _.gt(i, n) then return func(...) end i = i + 1 end end --- -- Creates a function that accepts up to n arguments ignoring any -- additional arguments. -- @usage local printOnly3 =_.ary(print, 3) -- printOnly3(1, 2, 3, 'x', 'y', 6) -- --> 1 2 3 -- -- @param func The function to cap arguments for. -- @param n the arity cap. -- @return Returns the new function _.ary = function(func, n) return function(...) if n == 1 then return func((...)) else local t = _.table(...) local first = _.take(t, n) return func(_.args(first)) end end end --- -- Creates a function that invokes func while it’s called less than n times. -- Subsequent calls to the created function return the result of the -- last func invocation. -- @usage local printBefore3 = _.before(3, print) -- for i = 1, 10 do -- printBefore3(i, 'ok') -- end -- --> 1 ok -- --> 2 ok -- --> 3 ok -- -- @param n The number of calls at which func is no longer invoked. -- @param func The function to restrict. -- @return Returns the new restriced function. _.before = function (n, func) local i = 1 local result return function (...) if _.lte(i, n) then result = func(...) end i = i + 1 return result end end --- -- Creates a function that runs each argument through a corresponding -- transform function. -- @usage local increment = function(...) -- return _.args(_.map(_.table(...), function(n) -- return n + 1 -- end)) -- end -- local pow = function(...) -- return _.args(_.map(_.table(...), function(n) -- return n * n -- end)) -- end -- local modded = _.modArgs(function(...) -- print(...) -- end, {increment, increment}, pow) -- modded(0, 1, 2) -- --> 4 9 16 -- -- @param func The function to wrap -- @param ... The functions to transform arguments, specified as -- individual functions or arrays of functions. -- @return Returns the new function. _.modArgs = function (func, ...) local transforms = {} for i, v in ipairs( _.table(...)) do if _.isFunction(v) then _.push(transforms, v) elseif _.isTable(v) then for k2, v2 in _.iter(v) do if _.isFunction(v2) then _.push(transforms, v2) end end end end return function(...) local args for i, transform in ipairs(transforms) do if _.isNil(args) then args = _.table(transform(...)) else args = _.table(transform(_.args(args))) end end if _.isNil(args) then return func(...) else return func(_.args(args)) end end end --- -- Creates a function that negates the result of the predicate func. -- The func predicate is invoked with arguments of the created function. -- @usage local isEven = function (n) -- return n % 2 == 0 -- end -- local isOdd = _.negate(isEven) -- _.print(_.filter({1, 2, 3, 4, 5, 6}, isEven)) -- --> {2, 4, 6} -- _.print(_.filter({1, 2, 3, 4, 5, 6}, isOdd)) -- --> {1, 3, 5} -- -- @param func The preadicate to negate. -- @return Returns the new function _.negate = function (func) return function(...) return not func(...) end end --- -- Creates a function that is restricted to invoking func once. Repeat -- calls to the function return the value of the first call. The func -- is invoked with arguments of the created function. -- @usage local createApp = function(version) -- print('App created with version '..version) -- return version -- end -- local initialize = _.once(createApp) -- initialize(1.1) -- initialize(1.1) -- initialize(1.1) -- --> App created with version 1.1 -- --> 1.1 -- --> 1.1 -- --> 1.1 -- -- @param func The function to restrict. -- @return Returns the new function. _.once = function (func) local called = false; local result return function(...) if not called then result = func(...) called = true end return result end end --- -- Creates a function that invokes func with arguments arranged according -- to the specified indexes where the argument value at the first index -- is provided as the first argument, the argument value at the second -- index is provided as the second argument, and so on. -- @usage local rearged = _.rearg(function(a, b, c) -- return {a, b, c}; -- end, 2, 1, 3) -- _.print(rearged('a', 'b', 'c')) -- --> {"b", "a", "c"} -- _.print(rearged('b', 'a', 'c')) -- --> {"a", "b", "c"} -- -- @param func The function to rearrange arguments for. -- @param ... The arranged argument indexes, specified as individual -- indexes or arrays of indexes. -- @return Returns the new function. _.rearg = function (func, ...) local indexes = {} for i, v in ipairs(_.table(...)) do if _.isNumber(v) then _.push(indexes, v) elseif _.isTable(v) then for k2, v2 in _.iter(v) do if _.isNumber(v2) then _.push(indexes, v2) end end end end return function(...) local args = _.table(...) local newArgs = {} for i, index in ipairs(indexes) do _.push(newArgs, args[index]) end if #indexes == 0 then return func(...) else return func(_.args(newArgs)) end end end --- Lang -- @section Lang --- --- -- Cast value to arguments -- @usage print(_.args({1, 2, 3})) -- --> 1 2 3 -- -- @param value value to cast -- @return Returns arguments _.args = function (value) if _.isTable(value) then return table.unpack(value) else return table.unpack({value}) end end --- -- Checks if value is greater than other. -- @usage _.print(_.gt(1, 3)) -- --> false -- _.print(_.gt(4, 3)) -- --> true -- -- @param value The value to compare. -- @param other The other value to compare. _.gt = function (value, other, ...) local value, other = _.cast(value, other) if _.isString(value) or _.isNumber(value) then return value > other elseif _.isFunction(value) then return value(...) > other(...) end return false end --- -- Checks if value is greater than other. -- @usage _.print(_.gte(1, 3)) -- --> false -- _.print(_.gte(3, 3)) -- --> true -- -- @param value The value to compare. -- @param other The other value to compare. _.gte = function (value, other, ...) if _.isNil(value) or _.isBoolean(value) then return value == other end local value, other = _.cast(value, other) if _.isString(value) or _.isNumber(value) then return value >= other elseif _.isFunction(value) then return value(...) >= other(...) elseif _.isTable(value) then return false end return false end --- -- Checks if value is classified as a boolean primitive. -- @usage _.print(_.isBoolean(false)) -- --> true -- _.print(_.isBoolean('x')) -- --> false -- -- @param value the value to check -- @return Returns true if value is correctly classified, else false. _.isBoolean = function(value) return type(value) == 'boolean' end --- -- Checks if value is empty. A value is considered empty unless it’s an -- arguments table, array, string with a length greater than 0 or an --object with own enumerable properties. --@usage _.print(_.isEmpty(true)) -- --> true -- _.print(_.isEmpty(1)) -- --> true -- _.print(_.isEmpty({1, 2, 3})) -- --> false -- _.print(_.isEmpty({a= 1})) -- --> false -- -- @param value The value to inspect. -- @return Returns true if value is empty, else false. _.isEmpty = function (value) if _.isString(value) then return #value == 0 elseif _.isTable(value) then local i = 0 for k, v in _.iter(value) do i = i + 1 end return i == 0 else return true end end --- -- Checks if parm1 and parm2 are equal. Parm can be a boolean, string, number, function or table --- --@usage _.print(_.isEqual(true)) -- --> true -- _.print(_.isEmpty(1)) -- --> true -- _.print(_.isEmpty({1, 2, 3})) -- --> false -- _.print(_.isEmpty({a= 1})) -- --> false -- -- @param parm1, parm2 The values to compare -- @return Returns true if values are equal, else false. _.isEqual = function (parm1, parm2) local avoid_loops = {} local function recurse(t1, t2) if type(t1) ~= type(t2) then return false end if type(t1) ~= "table" then return t1 == t2 end if avoid_loops[t1] then return avoid_loops[t1] == t2 end avoid_loops[t1] = t2 local t2keys = {} local t2tablekeys = {} for k, _ in pairs(t2) do if type(k) == "table" then table.insert(t2tablekeys, k) end t2keys[k] = true end for k1, v1 in pairs(t1) do local v2 = t2[k1] if type(k1) == "table" then local ok = false for i, tk in ipairs(t2tablekeys) do if _.isEqual(k1, tk) and recurse(v1, t2[tk]) then table.remove(t2tablekeys, i) t2keys[tk] = nil ok = true break end end if not ok then return false end else if v2 == nil then return false end t2keys[k1] = nil if not recurse(v1, v2) then return false end end end if next(t2keys) then return false end return true end return recurse(parm1, parm2) end --- -- Checks if value is classified as a function primitive. -- @usage _.print(_.isFunction(function() end)) -- --> true -- _.print(_.isFunction(1)) -- --> false -- -- @param value the value to check -- @return Returns true if value is correctly classified, else false. _.isFunction = function(value) return type(value) == 'function' end --- -- Checks if value is classified as a nil primitive. -- @usage _.print(_.isNil(variable) -- --> true -- variable = 1 -- _.print(_.isNil(variable)) -- --> false -- -- @param value the value to check -- @return Returns true if value is correctly classified, else false. _.isNil = function(value) return type(value) == 'nil' end --- -- Checks if value is classified as a number primitive. -- @usage _.print(_.isNumber(1)) -- --> true -- _.print(_.isNumber('1')) -- --> false -- -- @param value the value to check -- @return Returns true if value is correctly classified, else false. _.isNumber = function(value) return type(value) == 'number' end --- -- Checks if value is classified as a string primitive. -- @usage _.print(_.isString('1')) -- --> true -- _.print(_.isString(1)) -- --> false -- -- @param value the value to check -- @return Returns true if value is correctly classified, else false. _.isString = function(value) return type(value) == 'string' end --- -- Checks if value is classified as a table primitive. -- @usage _.print(_.isTable({'1'})) -- --> true -- _.print(_.isString(1)) -- --> false -- -- @param value the value to check -- @return Returns true if value is correctly classified, else false. _.isTable = function(value) return type(value) == 'table' end -- local implicitCast function (...) -- if -- end --- -- Checks if value is less than other. -- @usage _.print(_.lt(1, 3)) -- --> true -- _.print(_.lt(3, 3)) -- --> false -- -- @param value The value to compare. -- @param other The other value to compare. _.lt = function (value, other, ...) local value, other = _.cast(value, other) if _.isString(value) or _.isNumber(value) then return value < other elseif _.isFunction(value) then return value(...) < other(...) end return false end --- -- Checks if value is less than or euqal to other. -- @usage _.print(_.lt(4, 3)) -- --> false -- _.print(_.lt(3, 3)) -- --> true -- @param value The value to compare. -- @param other The other value to compare. _.lte = function (value, other, ...) if _.isNil(value) or _.isBoolean(value) then return value == other end local value, other = _.cast(value, other) if _.isString(value) or _.isNumber(value) then return value <= other elseif _.isFunction(value) then return value(...) <= other(...) elseif _.isTable(value) then return false end return false end _.cast = function (a, b) if type(a) == type(b) then return a, b end local cast if _.isString(a) then cast = _.str elseif _.isBoolean(a) then cast = _.bool elseif _.isNumber(a) then cast = _.num elseif _.isFunction(a) then cast = _.func elseif _.isTable(a) then cast = _.table end return a, cast(b) end --- -- Cast parameters to a function that return passed parameters. -- @usage local f = _.func(1, 2, 3) -- _.print(f()) -- --> 1 2 3 -- -- @param value value to cast -- @param ... The parameters to pass to any detected function -- @return casted value _.func = function (...) local t = _.table(...) return function () return _.args(t) end end --- -- Cast parameters to table using table.pack -- @usage print(_.table(1, 2, 3)) -- --> {1, 2, 3} -- print(_.table("123")) -- --> {"123"} -- print(_.table(0)) -- --> {0} -- -- @param value value to cast -- @param ... The parameters to pass to any detected function -- @return casted value _.table = function (...) return table.pack(...) end --- -- Cast anything to boolean. If any function detected, call and cast its -- result. Return false for 0, nil, table and empty string. -- @usage print(_.bool({1, 2, 3})) -- --> false -- print(_.bool("123")) -- --> true -- print(_.bool(0)) -- --> false -- print(_.bool(function(a) return a end, "555")) -- --> true -- -- @param value value to cast -- @param ... The parameters to pass to any detected function -- @return casted value _.bool = function (value, ...) local bool = false if _.isString(value) then bool = #value > 0 elseif _.isBoolean(value) then bool = value elseif _.isNumber(value) then bool = value ~= 0 elseif _.isFunction(value) then bool = _.bool(value(...)) end return bool end --- -- Cast anything to number. If any function detected, call and cast its -- result. Return 0 for nil and table. -- @usage print(_.num({1, 2, 3})) -- --> 0 -- print(_.num("123")) -- --> 123 -- print(_.num(true)) -- --> 1 -- print(_.num(function(a) return a end, "555")) -- --> 555 -- -- @param value value to cast -- @param ... The parameters to pass to any detected function -- @return casted value _.num = function (value, ...) local num = 0 if _.isString(value) then ok = pcall(function() num = value + 0 end) if not ok then num = math.huge end elseif _.isBoolean(value) then num = value and 1 or 0 elseif _.isNumber(value) then num = value elseif _.isFunction(value) then num = _.num(value(...)) end return num end local dblQuote = function (v) return '"'..v..'"' end --- -- Cast anything to string. If any function detected, call and cast its -- result. -- @usage print(_.str({1, 2, 3, 4, {k=2, {'x', 'y'}}})) -- --> {1, 2, 3, 4, {{"x", "y"}, ["k"]=2}} -- print(_.str({1, 2, 3, 4, function(a) return a end}, 5)) -- --> {1, 2, 3, 4, 5} -- -- @param value value to cast -- @param ... The parameters to pass to any detected function -- @return casted value _.str = function (value, ...) local str = ''; -- local v; if _.isString(value) then str = value elseif _.isBoolean(value) then str = value and 'true' or 'false' elseif _.isNil(value) then str = 'nil' elseif _.isNumber(value) then str = value .. '' elseif _.isFunction(value) then str = _.str(value(...)) elseif _.isTable(value) then str = '{' for k, v in pairs(value) do v = _.isString(v) and dblQuote(v) or _.str(v, ...) if _.isNumber(k) then str = str .. v .. ', ' else str = str .. '[' .. dblQuote(k) .. ']=' .. v .. ', ' end end str = str:sub(0, #str - 2) .. '}' end return str end --- Number -- @section Number --- -- Checks if n is between start and up to but not including, end. -- If end is not specified it’s set to start with start then set to 0. -- @usage print(_.inRange(-3, -4, 8)) -- --> true -- -- @param n The number to check. -- @param start The start of the range. -- @param stop The end of the range. -- @return Returns true if n is in the range, else false. _.inRange = function (n, start, stop) local _start = _.isNil(stop) and 0 or start or 0 local _stop = _.isNil(stop) and start or stop or 1 return n >= _start and n < _stop end --- -- Produces a random number between min and max (inclusive). -- If only one argument is provided a number between 0 and the given -- number is returned. If floating is true, a floating-point number is -- returned instead of an integer. -- @usage _.print(_.random()) -- --> 1 -- _.print(_.random(5)) -- --> 3 -- _.print(_.random(5, 10, true)) -- --> 8.8120200577248 -- -- @param[opt=0] min the minimum possible value. -- @param[opt=1] max the maximum possible value. -- @param[opt=false] floating Specify returning a floating-point number. -- @return Returns the random number. _.random = function (min, max, floating) local minim = _.isNil(max) and 0 or min or 0 local maxim = _.isNil(max) and min or max or 1 math.randomseed(os.clock() * math.random(os.time())) local r = math.random(minim, maxim) if floating then r = r + math.random() end return r end --- -- Rounds a float number to the required number of decimals -- If only one argument is provided it's round to an integer -- @usage _print(_.round(math.pi) -- --> 3 -- _.print(_.round(math.pi, 2) -- --> 3.14 -- -- @param the float to convert -- @param[opt=1] the number of deceimals to round to -- @return Returns the round number. _.round = function (x, n) x = tonumber(x) if not(_.isNumber(x)) then return x end n = 10^(n or 0) x = x * n if x >= 0 then x = math.floor(x + 0.5) else x = math.ceil(x - 0.5) end return x / n end --- Object -- @section Object --- -- Gets the property value at path of object. If the resolved value -- is nil the defaultValue is used in its place. -- @usage local object = {a={b={c={d=5}}}} -- _.print(_.get(object, {'a', 'b', 'c', 'd'})) -- --> 5 -- -- @param object The object to query. -- @param path The path of the property to get. -- @param[opt=nil] defaultValue The value returned if the resolved value is nil. -- @return Returns the resolved value. _.get = function (object, path, defaultValue) if _.isTable(object) then local value = object local c = 1 while not _.isNil(path[c]) do if not _.isTable(value) then return defaultValue end value = value[path[c]] c = c + 1 end return value or defaultValue elseif _.isString(object) then local index = path[1] return object:sub(index, index) end end --- -- Checks if path is a direct property. -- @usage local object = {a={b={c={d}}}} -- print(_.has(object, {'a', 'b', 'c'})) -- --> true -- -- @param object The object to query -- @param path The path to check (Array) _.has = function (object, path) local obj = object local c = 1 local exist = true while not _.isNil(path[c]) do obj = obj[path[c]] if _.isNil(obj) then exist = false break end c = c + 1 end return exist end --- -- This method is like _.find except that it returns the key of the -- first element predicate returns truthy for instead of the element itself. -- @usage _.print(_.findKey({a={a = 1}, b={a = 2}, c={a = 3, x = 1}}, -- function(v) -- return v.a == 3 -- end)) -- --> c -- -- @param object The collection to search. (table|string) -- @param predicate The function invoked per iteration -- @param selfArg The self binding of predicate. -- @return Returns the key of the matched element, else nil _.findKey = function (object, predicate, selfArg) for k, v in _.iter(object) do if callIteratee(predicate, selfArg, v, k, object) then return k end end end --- -- This method is like _.find except that it returns the key of the -- first element predicate returns truthy for instead of the element itself. -- @usage _.print(_.findLastKey({a={a=3}, b={a = 2}, c={a=3, x = 1}}, -- function(v) -- return v.a == 3 -- end)) -- --> c -- -- @param object The object to search. (table|string) -- @param predicate The function invoked per iteration -- @param selfArg The self binding of predicate. -- @return Returns the key of the matched element, else nil _.findLastKey = function (object, predicate, selfArg) for k, v in _.iterRight(object) do if callIteratee(predicate, selfArg, v, k, object) then return k end end end --- -- Creates an array of function property names from all enumerable -- properties, own and inherited, of object. -- @usage _.print(_.functions(table)) -- --> {"concat", "insert", "maxn", "pack", "remove", "sort", "unpack"} -- -- @param object The object to inspect. -- @return Returns the new array of property names. _.functions = function(object) local t = {} for k, v in _.iter(object) do if _.isFunction(v) then _.push(t, k) end end return t end --- -- Creates an object composed of the inverted keys and values of object. -- If object contains duplicate values, subsequent values overwrite -- property assignments of previous values unless multiValue is true. -- @usage _.print(_.invert({a='1', b='2', c='3', d='3'})) -- --> {[2]="b", [3]="d", [1]="a"} -- _.print(_.invert({a='1', b='2', c='3', d='3'}, true)) -- --> {[2]="b", [3]={"c", "d"}, [1]="a"} -- -- @param object The object to invert. -- @param multiValue Allow multiple values per key. -- @return Returns the new inverted object. _.invert = function (object, multiValue) local t = {} for k, v in _.iter(object) do if multiValue and not _.isNil(t[v]) then t[v] = { t[v] } _.push(t[v], k) else t[v] = k end end return t end local getSortedKeys = function(collection, desc) local sortedKeys = {} for k, v in pairs(collection) do table.insert(sortedKeys, k) end if desc then table.sort(sortedKeys, _.gt) else table.sort(sortedKeys, _.lt) end return sortedKeys end --- -- Creates an array of the own enumerable property names of object. -- @usage _.print(_.keys("test")) -- --> {1, 2, 3, 4} -- _.print(_.keys({a=1, b=2, c=3})) -- --> {"c", "b", "a"} -- -- @param object The object to query. (table|string) -- @return Returns the array of property names. _.keys = function (object) if _.isTable(object) then return getSortedKeys(object) elseif _.isString(object) then local keys = {} for i=1, #object do keys[i] = i end return keys end end --- -- Creates a two dimensional array of the key-value pairs for object. -- @usage _.print(_.pairs({1, 2, 'x', a='b'})) -- --> {{1, 1}, {2, 2}, {3, "x"}, {"a", "b"}} -- -- @param object The object to query -- @return Returns the new array of key-value pairs. _.pairs = function (object) local t = {} for k, v in _.iter(object) do _.push(t, {k, v}) end return t end --- -- This method is like _.get except that if the resolved value is a -- function it’s invoked with additional parameters and its result is returned. -- @usage local object = {a=5, b={c=function(a) print(a) end}} -- _.result(object, {'b', 'c'}, nil, 5) -- --> 5 -- -- @param object The object to query. -- @param path The path of the property to get. -- @param[opt=nil] defaultValue The value returned if the resolved value is nil. -- @param ... Additional parameters to pass to function -- @return Returns the resolved value. _.result = function (object, path, defaultValue, ...) local result = _.get(object, path, defaultValue) if _.isFunction(result) then return result(...) else return result end end --- -- Creates an array of the own enumerable property values of object. -- @usage _.print(_.values("test")) -- --> {"t", "e", "s", "t"} -- _.print(_.values({a=1, b=2, c=3})) -- --> {1, 3, 2} -- -- @param object The object to query. (table|string) -- @return Returns the array of property values. _.values = function (object) local t = {} for k, v in _.iter(object) do _.push(t, v) end return t end --- String -- @section String --- Utility -- @section Utility --- -- Creates a function that returns value. -- @usage local object = {x=5} -- local getter = _.constant(object) -- _.print(getter() == object); -- --> true -- -- @param value Any value. -- @return Returns the new function. _.constant = function(value) return _.func(value) end --- -- This method returns the first argument provided to it. -- @usage local object = {x=5} -- _.print(_.identity(object) == object); -- --> true -- -- @param value Any value. -- @return Returns value. _.identity = function(...) return ... end local iterCollection = function(table, desc) local sortedKeys = getSortedKeys(table, desc) local i = 0 return function () if _.lt(i, #sortedKeys) then i = i + 1 local key = sortedKeys[i] return key, table[key] end end end _.iter = function(value) if _.isString(value) then local i = 0 return function() if _.lt(i, #value) then i = i + 1 local c = value:sub(i, i) return i, c end end elseif _.isTable(value) then return iterCollection(value) else return function() end end end _.iterRight = function(value) if _.isString(value) then local i = #value + 1 return function() if _.gt(i, 1) then i = i - 1 local c = value:sub(i, i) return i, c end end elseif _.isTable(value) then return iterCollection(value, true) else return function() end end end --- -- A no-operation function that returns nil regardless of the arguments -- it receives. -- @usage local object = {x=5} -- _.print(_.noop(object) == nil); -- --> true -- -- @param ... Any arguments -- @return Returns nil _.noop = function(...) return nil end --- -- Print more readable representation of arguments using _.str -- @usage _.print({1, 2, 3, 4, {k=2, {'x', 'y'}}}) -- --> {1, 2, 3, 4, {{"x", "y"}, [k]=2}} -- -- @param ... values to print -- @return Return human readable string of the value _.print = function(...) local t = _.table(...) for i, v in ipairs(t) do t[i] = _.str(t[i]) end return print(_.args(t)) end --- -- Creates an array of numbers (positive and/or negative) progressing -- from start up to, including, end. -- If end is not specified it’s set to start with start then set to 1. -- @usage _.print(_.range(5, 20, 3)) -- --> {5, 8, 11, 14, 17, 20} -- -- @param[opt=1] start The start of the range. -- @param stop Then end of the range. -- @param[opt=1] step The value to increment or decrement by -- @return Returns the new array of numbers _.range = function(start, ...) local start = start local args = _.table(...) local a, b, c if #args == 0 then a = 1 -- according to lua b = start c = 1 else a = start b = args[1] c = args[2] or 1 end local t = {} for i = a, b, c do _.push(t, i) end return t end return _
gpl-3.0
Ninjistix/darkstar
scripts/globals/spells/valor_minuet_ii.lua
5
1536
----------------------------------------- -- Spell: Valor Minuet II -- Grants Attack bonus to all allies. ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED); local power = 10; if (sLvl+iLvl > 85) then power = power + math.floor((sLvl+iLvl-85) / 6); end if (power >= 32) then power = 32; end local iBoost = caster:getMod(MOD_MINUET_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); if (iBoost > 0) then power = power + 1 + (iBoost-1)*4; end power = power + caster:getMerit(MERIT_MINUET_EFFECT); if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_MINUET,power,0,duration,caster:getID(), 0, 2)) then spell:setMsg(msgBasic.MAGIC_NO_EFFECT); end return EFFECT_MINUET; end;
gpl-3.0
carnalis/Urho3D
bin/Data/LuaScripts/15_Navigation.lua
11
22134
-- Navigation example. -- This sample demonstrates: -- - Generating a navigation mesh into the scene -- - Performing path queries to the navigation mesh -- - Rebuilding the navigation mesh partially when adding or removing objects -- - Visualizing custom debug geometry -- - Raycasting drawable components -- - Making a node follow the Detour path require "LuaScripts/Utilities/Sample" local endPos = nil local currentPath = {} local useStreaming = false local streamingDistance = 2 local navigationTiles = {} local addedTiles = {} function Start() -- Execute the common startup for samples SampleStart() -- Create the scene content CreateScene() -- Create the UI content CreateUI() -- Setup the viewport for displaying the scene SetupViewport() -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_RELATIVE) -- Hook up to the frame update and render post-update events SubscribeToEvents() end function CreateScene() scene_ = Scene() -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000) -- Also create a DebugRenderer component so that we can draw debug geometry scene_:CreateComponent("Octree") scene_:CreateComponent("DebugRenderer") -- Create scene node & StaticModel component for showing a static plane local planeNode = scene_:CreateChild("Plane") planeNode.scale = Vector3(100.0, 1.0, 100.0) local planeObject = planeNode:CreateComponent("StaticModel") planeObject.model = cache:GetResource("Model", "Models/Plane.mdl") planeObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml") -- Create a Zone component for ambient lighting & fog control local zoneNode = scene_:CreateChild("Zone") local zone = zoneNode:CreateComponent("Zone") zone.boundingBox = BoundingBox(-1000.0, 1000.0) zone.ambientColor = Color(0.15, 0.15, 0.15) zone.fogColor = Color(0.5, 0.5, 0.7) zone.fogStart = 100.0 zone.fogEnd = 300.0 -- Create a directional light to the world. Enable cascaded shadows on it local lightNode = scene_:CreateChild("DirectionalLight") lightNode.direction = Vector3(0.6, -1.0, 0.8) local light = lightNode:CreateComponent("Light") light.lightType = LIGHT_DIRECTIONAL light.castShadows = true light.shadowBias = BiasParameters(0.00025, 0.5) -- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8) -- Create some mushrooms local NUM_MUSHROOMS = 100 for i = 1, NUM_MUSHROOMS do CreateMushroom(Vector3(Random(90.0) - 45.0, 0.0, Random(90.0) - 45.0)) end -- Create randomly sized boxes. If boxes are big enough, make them occluders. Occluders will be software rasterized before -- rendering to a low-resolution depth-only buffer to test the objects in the view frustum for visibility local NUM_BOXES = 20 for i = 1, NUM_BOXES do local boxNode = scene_:CreateChild("Box") local size = 1.0 + Random(10.0) boxNode.position = Vector3(Random(80.0) - 40.0, size * 0.5, Random(80.0) - 40.0) boxNode:SetScale(size) local boxObject = boxNode:CreateComponent("StaticModel") boxObject.model = cache:GetResource("Model", "Models/Box.mdl") boxObject.material = cache:GetResource("Material", "Materials/Stone.xml") boxObject.castShadows = true if size >= 3.0 then boxObject.occluder = true end end -- Create Jack node that will follow the path jackNode = scene_:CreateChild("Jack") jackNode.position = Vector3(-5, 0, 20) local modelObject = jackNode:CreateComponent("AnimatedModel") modelObject.model = cache:GetResource("Model", "Models/Jack.mdl") modelObject.material = cache:GetResource("Material", "Materials/Jack.xml") modelObject.castShadows = true -- Create a NavigationMesh component to the scene root local navMesh = scene_:CreateComponent("NavigationMesh") -- Set small tiles to show navigation mesh streaming navMesh.tileSize = 32 -- Create a Navigable component to the scene root. This tags all of the geometry in the scene as being part of the -- navigation mesh. By default this is recursive, but the recursion could be turned off from Navigable scene_:CreateComponent("Navigable") -- Add padding to the navigation mesh in Y-direction so that we can add objects on top of the tallest boxes -- in the scene and still update the mesh correctly navMesh.padding = Vector3(0.0, 10.0, 0.0) -- Now build the navigation geometry. This will take some time. Note that the navigation mesh will prefer to use -- physics geometry from the scene nodes, as it often is simpler, but if it can not find any (like in this example) -- it will use renderable geometry instead navMesh:Build() -- Create the camera. Limit far clip distance to match the fog cameraNode = scene_:CreateChild("Camera") local camera = cameraNode:CreateComponent("Camera") camera.farClip = 300.0 -- Set an initial position for the camera scene node above the plane and looking down cameraNode.position = Vector3(0.0, 50.0, 0.0) pitch = 80.0 cameraNode.rotation = Quaternion(pitch, yaw, 0.0) end function CreateUI() -- Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will -- control the camera, and when visible, it will point the raycast target local style = cache:GetResource("XMLFile", "UI/DefaultStyle.xml") local cursor = Cursor:new() cursor:SetStyleAuto(style) ui.cursor = cursor -- Set starting position of the cursor at the rendering window center cursor:SetPosition(graphics.width / 2, graphics.height / 2) -- Construct new Text object, set string to display and font to use local instructionText = ui.root:CreateChild("Text") instructionText.text = "Use WASD keys to move, RMB to rotate view\n".. "LMB to set destination, SHIFT+LMB to teleport\n".. "MMB or O key to add or remove obstacles\n".. "Tab to toggle navigation mesh streaming\n".. "Space to toggle debug geometry" instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) -- The text has multiple rows. Center them in relation to each other instructionText.textAlignment = HA_CENTER -- Position the text relative to the screen center instructionText.horizontalAlignment = HA_CENTER instructionText.verticalAlignment = VA_CENTER instructionText:SetPosition(0, ui.root.height / 4) end function SetupViewport() -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera")) renderer:SetViewport(0, viewport) end function SubscribeToEvents() -- Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate") -- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request -- debug geometry SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate") end function MoveCamera(timeStep) input.mouseVisible = input.mouseMode ~= MM_RELATIVE mouseDown = input:GetMouseButtonDown(MOUSEB_RIGHT) -- Override the MM_RELATIVE mouse grabbed settings, to allow interaction with UI input.mouseGrabbed = mouseDown -- Right mouse button controls mouse cursor visibility: hide when pressed ui.cursor.visible = not mouseDown -- Do not move if the UI has a focused element (the console) if ui.focusElement ~= nil then return end -- Movement speed as world units per second local MOVE_SPEED = 20.0 -- Mouse sensitivity as degrees per pixel local MOUSE_SENSITIVITY = 0.1 -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees -- Only move the camera when the cursor is hidden if not ui.cursor.visible then local mouseMove = input.mouseMove yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y pitch = Clamp(pitch, -90.0, 90.0) -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero cameraNode.rotation = Quaternion(pitch, yaw, 0.0) end -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed if input:GetKeyDown(KEY_W) then cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_S) then cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_A) then cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_D) then cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end -- Set destination or teleport with left mouse button if input:GetMouseButtonPress(MOUSEB_LEFT) then SetPathPoint() end -- Add or remove objects with middle mouse button, then rebuild navigation mesh partially if input:GetMouseButtonPress(MOUSEB_MIDDLE) or input:GetKeyPress(KEY_O) then AddOrRemoveObject() end -- Toggle debug geometry with space if input:GetKeyPress(KEY_SPACE) then drawDebug = not drawDebug end end function SetPathPoint() local hitPos, hitDrawable = Raycast(250.0) local navMesh = scene_:GetComponent("NavigationMesh") if hitPos then local pathPos = navMesh:FindNearestPoint(hitPos, Vector3.ONE) if input:GetQualifierDown(QUAL_SHIFT) then -- Teleport currentPath = {} jackNode:LookAt(Vector3(pathPos.x, jackNode.position.y, pathPos.z), Vector3(0.0, 1.0, 0.0)) jackNode.position = pathPos else -- Calculate path from Jack's current position to the end point endPos = pathPos currentPath = navMesh:FindPath(jackNode.position, endPos) end end end function AddOrRemoveObject() -- Raycast and check if we hit a mushroom node. If yes, remove it, if no, create a new one local hitPos, hitDrawable = Raycast(250.0) if not useStreaming and hitDrawable then -- The part of the navigation mesh we must update, which is the world bounding box of the associated -- drawable component local updateBox = nil local hitNode = hitDrawable.node if hitNode.name == "Mushroom" then updateBox = hitDrawable.worldBoundingBox hitNode:Remove() else local newNode = CreateMushroom(hitPos) local newObject = newNode:GetComponent("StaticModel") updateBox = newObject.worldBoundingBox end -- Rebuild part of the navigation mesh, then recalculate path if applicable local navMesh = scene_:GetComponent("NavigationMesh") navMesh:Build(updateBox) if table.maxn(currentPath) > 0 then currentPath = navMesh:FindPath(jackNode.position, endPos) end end end function CreateMushroom(pos) local mushroomNode = scene_:CreateChild("Mushroom") mushroomNode.position = pos mushroomNode.rotation = Quaternion(0.0, Random(360.0), 0.0) mushroomNode:SetScale(2.0 + Random(0.5)) local mushroomObject = mushroomNode:CreateComponent("StaticModel") mushroomObject.model = cache:GetResource("Model", "Models/Mushroom.mdl") mushroomObject.material = cache:GetResource("Material", "Materials/Mushroom.xml") mushroomObject.castShadows = true return mushroomNode end function Raycast(maxDistance) local pos = ui.cursorPosition -- Check the cursor is visible and there is no UI element in front of the cursor if (not ui.cursor.visible) or (ui:GetElementAt(pos, true) ~= nil) then return nil, nil end local camera = cameraNode:GetComponent("Camera") local cameraRay = camera:GetScreenRay(pos.x / graphics.width, pos.y / graphics.height) -- Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit local octree = scene_:GetComponent("Octree") local result = octree:RaycastSingle(cameraRay, RAY_TRIANGLE, maxDistance, DRAWABLE_GEOMETRY) if result.drawable ~= nil then return result.position, result.drawable end return nil, nil end function ToggleStreaming(enabled) local navMesh = scene_:GetComponent("NavigationMesh") if enabled then local maxTiles = (2 * streamingDistance + 1) * (2 * streamingDistance + 1) local boundingBox = BoundingBox(navMesh.boundingBox) SaveNavigationData() navMesh:Allocate(boundingBox, maxTiles) else navMesh:Build() end end function UpdateStreaming() local navMesh = scene_:GetComponent("NavigationMesh") -- Center the navigation mesh at the jack local jackTile = navMesh:GetTileIndex(jackNode.worldPosition) local beginTile = VectorMax(IntVector2(0, 0), jackTile - IntVector2(1, 1) * streamingDistance) local endTile = VectorMin(jackTile + IntVector2(1, 1) * streamingDistance, navMesh.numTiles - IntVector2(1, 1)) -- Remove tiles local numTiles = navMesh.numTiles for i,tileIdx in pairs(addedTiles) do if not (beginTile.x <= tileIdx.x and tileIdx.x <= endTile.x and beginTile.y <= tileIdx.y and tileIdx.y <= endTile.y) then addedTiles[i] = nil navMesh:RemoveTile(tileIdx) end end -- Add tiles for z = beginTile.y, endTile.y do for x = beginTile.x, endTile.x do local i = z * numTiles.x + x if not navMesh:HasTile(IntVector2(x, z)) and navigationTiles[i] then addedTiles[i] = IntVector2(x, z) navMesh:AddTile(navigationTiles[i]) end end end end function SaveNavigationData() local navMesh = scene_:GetComponent("NavigationMesh") navigationTiles = {} addedTiles = {} local numTiles = navMesh.numTiles for z = 0, numTiles.y - 1 do for x = 0, numTiles.x - 1 do local i = z * numTiles.x + x navigationTiles[i] = navMesh:GetTileData(IntVector2(x, z)) end end end function HandleUpdate(eventType, eventData) -- Take the frame time step, which is stored as a float local timeStep = eventData["TimeStep"]:GetFloat() -- Move the camera, scale movement with time step MoveCamera(timeStep) -- Make Jack follow the Detour path FollowPath(timeStep) -- Update streaming if input:GetKeyPress(KEY_TAB) then useStreaming = not useStreaming ToggleStreaming(useStreaming) end if useStreaming then UpdateStreaming() end end function FollowPath(timeStep) if table.maxn(currentPath) > 0 then local nextWaypoint = currentPath[1] -- NB: currentPath[1] is the next waypoint in order -- Rotate Jack toward next waypoint to reach and move. Check for not overshooting the target local move = 5 * timeStep local distance = (jackNode.position - nextWaypoint):Length() if move > distance then move = distance end jackNode:LookAt(nextWaypoint, Vector3(0.0, 1.0, 0.0)) jackNode:Translate(Vector3(0.0, 0.0, 1.0) * move) -- Remove waypoint if reached it if distance < 0.1 then table.remove(currentPath, 1) end end end function HandlePostRenderUpdate(eventType, eventData) -- If draw debug mode is enabled, draw navigation mesh debug geometry if drawDebug then local navMesh = scene_:GetComponent("NavigationMesh") navMesh:DrawDebugGeometry(true) end -- Visualize the start and end points and the last calculated path local size = table.maxn(currentPath) if size > 0 then local debug = scene_:GetComponent("DebugRenderer") debug:AddBoundingBox(BoundingBox(endPos - Vector3(0.1, 0.1, 0.1), endPos + Vector3(0.1, 0.1, 0.1)), Color(1.0, 1.0, 1.0)) -- Draw the path with a small upward bias so that it does not clip into the surfaces local bias = Vector3(0.0, 0.05, 0.0) debug:AddLine(jackNode.position + bias, currentPath[1] + bias, Color(1.0, 1.0, 1.0)) if size > 1 then for i = 1, size - 1 do debug:AddLine(currentPath[i] + bias, currentPath[i + 1] + bias, Color(1.0, 1.0, 1.0)) end end end end -- Create XML patch instructions for screen joystick layout specific to this sample app function GetScreenJoystickPatchString() return "<patch>" .. " <add sel=\"/element\">" .. " <element type=\"Button\">" .. " <attribute name=\"Name\" value=\"Button3\" />" .. " <attribute name=\"Position\" value=\"-120 -120\" />" .. " <attribute name=\"Size\" value=\"96 96\" />" .. " <attribute name=\"Horiz Alignment\" value=\"Right\" />" .. " <attribute name=\"Vert Alignment\" value=\"Bottom\" />" .. " <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" .. " <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" .. " <attribute name=\"Hover Image Offset\" value=\"0 0\" />" .. " <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"Label\" />" .. " <attribute name=\"Horiz Alignment\" value=\"Center\" />" .. " <attribute name=\"Vert Alignment\" value=\"Center\" />" .. " <attribute name=\"Color\" value=\"0 0 0 1\" />" .. " <attribute name=\"Text\" value=\"Teleport\" />" .. " </element>" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"KeyBinding\" />" .. " <attribute name=\"Text\" value=\"LSHIFT\" />" .. " </element>" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" .. " <attribute name=\"Text\" value=\"LEFT\" />" .. " </element>" .. " </element>" .. " <element type=\"Button\">" .. " <attribute name=\"Name\" value=\"Button4\" />" .. " <attribute name=\"Position\" value=\"-120 -12\" />" .. " <attribute name=\"Size\" value=\"96 96\" />" .. " <attribute name=\"Horiz Alignment\" value=\"Right\" />" .. " <attribute name=\"Vert Alignment\" value=\"Bottom\" />" .. " <attribute name=\"Texture\" value=\"Texture2D;Textures/TouchInput.png\" />" .. " <attribute name=\"Image Rect\" value=\"96 0 192 96\" />" .. " <attribute name=\"Hover Image Offset\" value=\"0 0\" />" .. " <attribute name=\"Pressed Image Offset\" value=\"0 0\" />" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"Label\" />" .. " <attribute name=\"Horiz Alignment\" value=\"Center\" />" .. " <attribute name=\"Vert Alignment\" value=\"Center\" />" .. " <attribute name=\"Color\" value=\"0 0 0 1\" />" .. " <attribute name=\"Text\" value=\"Obstacles\" />" .. " </element>" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" .. " <attribute name=\"Text\" value=\"MIDDLE\" />" .. " </element>" .. " </element>" .. " </add>" .. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" .. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Set</replace>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" .. " <attribute name=\"Text\" value=\"LEFT\" />" .. " </element>" .. " </add>" .. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" .. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"KeyBinding\" />" .. " <attribute name=\"Text\" value=\"SPACE\" />" .. " </element>" .. " </add>" .. "</patch>" end
mit
dinodeck/ninety_nine_days_of_dev
004_stat_numbers/code/Scrollbar.lua
10
2903
Scrollbar = {} Scrollbar.__index = Scrollbar function Scrollbar:Create(texture, height) local this = { mX = 0, mY = 0, mHeight = height or 300, mTexture = texture, mValue = 0, mUpSprite = Sprite.Create(), mDownSprite = Sprite.Create(), mBackgroundSprite = Sprite.Create(), mCaretSprite = Sprite.Create(), mCaretSize = 1, } local texWidth = texture:GetWidth() local texHeight = texture:GetHeight() this.mUpSprite:SetTexture(texture) this.mDownSprite:SetTexture(texture) this.mBackgroundSprite:SetTexture(texture) this.mCaretSprite:SetTexture(texture) -- There are expected to be 4 equally sized pieces -- that make up a scrollbar. this.mTileHeight = texHeight/4 this.mUVs = GenerateUVs(texWidth, this.mTileHeight, texture) this.mUpSprite:SetUVs(unpack(this.mUVs[1])) this.mCaretSprite:SetUVs(unpack(this.mUVs[2])) this.mBackgroundSprite:SetUVs(unpack(this.mUVs[3])) this.mDownSprite:SetUVs(unpack(this.mUVs[4])) -- Height ignore the up and down arrows this.mLineHeight = this.mHeight - (this.mTileHeight*2) setmetatable(this, self) this:SetPosition(0, 0) return this end function Scrollbar:SetPosition(x, y) self.mX = x self.mY = y local top = y + self.mHeight / 2 local bottom = y - self.mHeight / 2 local halfTileHeight = self.mTileHeight / 2 self.mUpSprite:SetPosition(x, top - halfTileHeight) self.mDownSprite:SetPosition(x, bottom + halfTileHeight) self.mBackgroundSprite:SetScale(1, self.mLineHeight / self.mTileHeight) self.mBackgroundSprite:SetPosition(self.mX, self.mY) self:SetNormalValue(self.mValue) end function Scrollbar:SetNormalValue(v) self.mValue = v self.mCaretSprite:SetScale(1, self.mCaretSize) -- caret 0 is the top of the scrollbar local caretHeight = self.mTileHeight * self.mCaretSize local halfCaretHeight = caretHeight / 2 self.mStart = self.mY + (self.mLineHeight / 2) - halfCaretHeight -- Subtracting caret, to take into account the first -halfcaret and the one at the other end self.mStart = self.mStart - ((self.mLineHeight - caretHeight)*self.mValue) self.mCaretSprite:SetPosition(self.mX, self.mStart) end function Scrollbar:Render(renderer) renderer:DrawSprite(self.mUpSprite) renderer:DrawSprite(self.mBackgroundSprite) renderer:DrawSprite(self.mDownSprite) renderer:DrawSprite(self.mCaretSprite) end function Scrollbar:SetScrollCaretScale(normalValue) self.mCaretSize = ((self.mLineHeight )*normalValue)/self.mTileHeight --print('cSize', normalValue, self.mCaretSize, self.mLineHeight - self.mTileHeight) -- Don't let it go below 1 self.mCaretSize = math.max(1, self.mCaretSize) end
mit
Ninjistix/darkstar
scripts/zones/Mhaura/npcs/Tya_Padolih.lua
4
1212
----------------------------------- -- Area: Mhaura -- NPC: Tya Padolih -- Standard Merchant NPC -- !pos -48 -4 30 249 ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mhaura/TextIDs"); require("scripts/globals/shop"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local stock = { 4716, 4147, -- Scroll of Regen 4718, 7516, -- Scroll of Regen II 4881, 10752, -- Scroll of Sleepga 4690, 29030, -- Scroll of Baramnesia 4691, 29030, -- Scroll of Baramnesra 4744, 5523, -- Scroll of Invisible 4745, 2400, -- Scroll of Sneak 4746, 1243, -- Scroll of Deodorize 4912, 18032, -- Scroll of Distract 4914, 25038 -- Scroll of Frazzle } player:showText(npc,TYAPADOLIH_SHOP_DIALOG); showShop(player, STATIC, stock); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/spells/bluemagic/seedspray.lua
31
2112
----------------------------------------- -- Spell: Seedspray -- Delivers a threefold attack. Additional effect: Weakens defense. Chance of effect varies with TP -- Spell cost: 61 MP -- Monster Type: Plantoids -- Spell Type: Physical (Slashing) -- Blue Magic Points: 2 -- Stat Bonus: VIT+1 -- Level: 61 -- Casting Time: 4 seconds -- Recast Time: 35 seconds -- Skillchain Element(s): Ice (Primary) and Wind (Secondary) - (can open Impaction, Compression, Fragmentation, Scission or Gravitation; can close Induration or Detonation) -- Combos: Beast Killer ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_CRITICAL; params.dmgtype = DMGTYPE_SLASH; params.scattr = SC_GRAVITATION; params.numhits = 3; params.multiplier = 1.925; params.tp150 = 1.25; params.tp300 = 1.25; params.azuretp = 1.25; params.duppercap = 61; params.str_wsc = 0.0; params.dex_wsc = 0.30; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.20; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); local chance = math.random(); if (damage > 0 and chance > 1) then local typeEffect = EFFECT_DEFENSE_DOWN; target:delStatusEffect(typeEffect); target:addStatusEffect(typeEffect,4,0,getBlueEffectDuration(caster,resist,typeEffect)); end return damage; end;
gpl-3.0
Xamla/torch-ros
lua/NodeHandle.lua
1
19359
--- Interface class to create subscribers, publishers, etc. -- @classmod NodeHandle local ffi = require 'ffi' local torch = require 'torch' local ros = require 'ros.env' local utils = require 'ros.utils' local std = ros.std local NodeHandle = torch.class('ros.NodeHandle', ros) function init() local NodeHandle_method_names = { 'new', 'delete', 'shutdown', 'ok', 'getNamespace', 'getUnresolvedNamespace', 'resolveName', 'subscribe', 'advertise', 'serviceClient', 'advertiseService', 'hasParam', 'deleteParam', 'getParamString', 'getParamDouble', 'getParamFloat', 'getParamInt', 'getParamBool', 'setParamString', 'setParamDouble', 'setParamFloat', 'setParamInt', 'setParamBool', 'getParamStringVector', 'getParamBoolVector', 'getParamIntVector', 'getParamDoubleVector', 'getParamFloatVector', 'setParamStringVector', 'setParamBoolVector', 'setParamIntVector', 'setParamDoubleVector', 'setParamFloatVector', 'getParamStringMap', 'getParamVariable' } return utils.create_method_table('ros_NodeHandle_', NodeHandle_method_names) end local f = init() --- NodeHandle constructor. -- When a NodeHandle is constructed, it checks to see if the global -- node state has already been started. If so, it increments a global -- reference count. If not, it starts the node with ros::start() and -- sets the reference count to 1. -- @tparam[opt] string ns Namespace for this NodeHandle. This acts in addition to any namespace assigned to this ROS node. eg. If the node's namespace is "/a" and the namespace passed in here is "b", all topics/services/parameters will be prefixed with "/a/b/" -- @tparam[opt] parent ros:NodeHandle Parent node handle. If the passed "ns" is relative (does not start with a slash), it is equivalent to calling: NodeHandle child(parent.getNamespace() + "/" + ns, remappings). If the passed "ns" is absolute (does start with a slash), it is equivalent to calling: NodeHandle child(ns, remappings) -- @tparam[opt] tab remappings remapping table function NodeHandle:__init(ns, parent, remappings) if remappings ~= nil and type(remappings) == 'table' then remappings = std.StringMap(remappings) end self.o = f.new(ns or '', utils.cdata(parent), utils.cdata(remappings)) end --- Get the cdata of this object function NodeHandle:cdata() return self.o end function NodeHandle:addSerializationHandler(handler) if self.serialization_handlers == nil then self.serialization_handlers = {} end self.serialization_handlers[handler:getType()] = handler end --- Shutdown every handle created through this NodeHandle. -- This method will unadvertise every topic and service advertisement, -- and unsubscribe every subscription created through this NodeHandle. function NodeHandle:shutdown() f.shutdown(self.o) end --- Check whether it's time to exit. -- @treturn bool true if we're still OK, false if it's time to exit function NodeHandle:ok() return f.ok(self.o) end --- Returns the namespace associated with this NodeHandle. -- @treturn string The namespace function NodeHandle:getNamespace() return ffi.string(f.getNamespace(self.o)) end --- Returns the namespace associated with this NodeHandle as it was passed in (before it was resolved) -- @treturn string The unresolved namespace string function NodeHandle:getUnresolvedNamespace() return ffi.string(f.getUnresolvedNamespace(self.o)) end --- Resolves a name into a fully-qualified name. -- @tparam string name Name to remap -- @tparam bool remap Whether to apply name-remapping rules -- @treturn string Resolved name function NodeHandle:resolveName(name, remap) local result = std.String() f.resolveName(self.o, name, remap or true, result:cdata()) return result end --- Subscribe to a ROS topic -- @tparam string Topic to subscribe to -- @tparam ?string|ros.MsgSpec msg_spec Message specification of the topic one wants to subscribe to -- @tparam[opt=1000] int queue_size Number of incoming messages to queue up for processing (messages in excess of this queue capacity will be discarded). -- @tparam[opt] std.StringVector transports Transport method (udp, tcp) -- @tparam[opt] std.StringMap transport_options Various transport options like tcp_nodelay, maxDatagramSize, etc. -- @tparam[opt] ros.CallbackQueue callback queue. -- @treturn ros.Subscriber A ros.Subscriber object function NodeHandle:subscribe(topic, msg_spec, queue_size, transports, transport_options, callback_queue) if type(msg_spec) == 'string' then msg_spec = ros.get_msgspec(msg_spec) end if transports ~= nil and not torch.isTypeOf(transports, std.StringVector) then if type(transports) == 'table' or type(transports) == 'string' then transports = std.StringVector(transports) else error("Invalid argument 'transports'") end end if transport_options ~= nil and not torch.isTypeOf(transport_options, std.StringMap) then if type(transport_options) == 'string' then local name = transport_options transport_options = std.StringMap(transport_options) transport_options[name] = 'true' elseif type(transport_options) == 'table' then transport_options = std.StringMap(transport_options) else error("Invalid argument 'transport_options'") end end if callback_queue ~= nil and not torch.isTypeOf(callback_queue, ros.CallbackQueue) then error('Invalid type of explicitly specified callback queue.') end local buffer = ros.MessageBuffer(queue_size) local s = f.subscribe( self.o, buffer:cdata(), topic, queue_size or 1000, msg_spec:md5(), msg_spec.type, utils.cdata(transports), utils.cdata(transport_options), utils.cdata(callback_queue) ) return ros.Subscriber(s, buffer, msg_spec, callback_queue, self.serialization_handlers) end --- Advertise a topic -- This call connects to the master to publicize that the node will be publishing messages on the given topic. -- @tparam string topic Topic to advertise on -- @tparam ?string|ros.MsgSpec msg_spec Message specification of the topic one wants to publish to -- @tparam[opt=1000] int queue_size Maximum number of outgoing messages to be queued for delivery to subscribers -- @tparam[opt=false] bool latch If true, the last message published on this topic will be saved and sent to new subscribers when they connect -- @tparam[opt] func connect_cb Callback to be called if a client connects -- @tparam[opt] func disconnect_cb Callback to be called if a client disconnects -- @tparam[opt=ros.DEFAULT_CALLBACK_QUEUE] ros.CallbackQueue callback_queue Callback queue -- @treturn ros.Publisher ROS publisher function NodeHandle:advertise(topic, msg_spec, queue_size, latch, connect_cb, disconnect_cb, callback_queue) if type(msg_spec) == 'string' then msg_spec = ros.get_msgspec(msg_spec) end if connect_cb ~= nil or disconnect_cb ~= nil then callback_queue = callback_queue or ros.DEFAULT_CALLBACK_QUEUE if not torch.isTypeOf(callback_queue, ros.CallbackQueue) then error('Invalid type of explicitly specified callback queue.') end else callback_queue = ffi.NULL end local connect_, disconnect_ = ffi.NULL, ffi.NULL if connect_cb ~= nil then connect_ = ffi.cast('_ServiceStatusCallback', function(name, topic) connect_cb(ffi.string(name), ffi.string(topic)) end) end if disconnect_cb ~= nil then disconnect_ = ffi.cast('_ServiceStatusCallback', function(name, topic) disconnect_cb(ffi.string(name), ffi.string(topic)) end) end local p = f.advertise(self.o, topic, queue_size or 1000, msg_spec:md5(), msg_spec.type, msg_spec.definition, msg_spec.has_header, latch or false, connect_, disconnect_, utils.cdata(callback_queue)) return ros.Publisher(p, msg_spec, connect_, disconnect_, self.serialization_handlers) end --- Create a client for a service -- @tparam string service_name Name of the service to contact -- @tparam ?string|ros.SrvSpec service_spec Service specification -- @tparam[opt=false] bool persistent Whether this connection should persist. Persistent services keep the connection to the remote host active so that subsequent calls will happen faster. In general persistent services are discouraged, as they are not as robust to node failure as non-persistent services. -- @tparam[opt] tab header_values Key/value pairs you'd like to send along in the connection handshake function NodeHandle:serviceClient(service_name, service_spec, persistent, header_values) if type(service_spec) == 'string' then service_spec = ros.SrvSpec(service_spec) end if not torch.isTypeOf(service_spec, ros.SrvSpec) then error("NodeHandle:serviceClient(): invalid 'service_spec' argument.") end local client = f.serviceClient(self.o, service_name, service_spec:md5(), persistent or false, utils.cdata(header_values)) return ros.ServiceClient(client, service_spec, nil, nil, self.serialization_handlers) end --- Advertise a service -- This call connects to the master to publicize that the node will be offering an RPC service with the given name. -- @tparam string service_name Name of the service -- @tparam ros.SrvSpec service_spec Service specification -- @tparam func service_handler_func Service handler function -- @tparam[opt=ros.DEFAULT_CALLBACK_QUEUE] ros.CallbackQueue callback_queue ROS callback queue -- @treturn ros.ServiceServer function NodeHandle:advertiseService(service_name, service_spec, service_handler_func, callback_queue) callback_queue = callback_queue or ros.DEFAULT_CALLBACK_QUEUE if not torch.isTypeOf(callback_queue, ros.CallbackQueue) then error('Invalid type of explicitly specified callback queue.') end -- create message serialization/deserialization wrapper function local function handler(request_storage, response_storage, header_values) -- create torch.ByteStorage() obj from THByteStorage* and addref request_storage = torch.pushudata(request_storage, 'torch.ByteStorage') request_storage:retain() response_storage = ros.SerializedMessage.fromPtr(response_storage) -- create class around header values string map... local header = torch.factory('std.StringMap')() rawset(header, 'o', header_values) -- deserialize request local request_msg = ros.Message(service_spec.request_spec, true) request_msg:deserialize(ros.StorageReader(request_storage)) local response_msg = ros.Message(service_spec.response_spec) -- call actual service handler function local ok, status = pcall(service_handler_func, request_msg, response_msg, header) if not ok then ros.ERROR(status) status = false end -- serialize response local sw = ros.StorageWriter(response_storage) local v = response_msg:serializeServiceResponse(sw, status) sw:shrinkToFit() return status end local cb = ffi.cast("ServiceRequestCallback", handler) local srv_ptr = f.advertiseService( self.o, service_name, service_spec:md5(), service_spec.type, service_spec.request_spec.type, service_spec.response_spec.type, cb, callback_queue:cdata() ) return ros.ServiceServer(srv_ptr, cb, service_handler_func) end --- Check whether a parameter exists on the parameter server. -- @tparam string key The key to check. -- @treturn bool true if the parameter exists, false otherwise function NodeHandle:hasParam(key) return f.hasParam(self.o, key) end --- Delete a parameter from the parameter server. -- @tparam string key The key to delete. -- @treturn bool true if the deletion succeeded, false otherwise. function NodeHandle:deleteParam(key) return f.deleteParam(self.o, key) end --- Get the parameter value for key key. -- @tparam string key The key to get the value for -- @treturn string The key value -- @treturn bool true if the parameter value was retrieved, false otherwise function NodeHandle:getParamString(key) local result = std.String() local ok = f.getParamString(self.o, key, result:cdata()) return result:get(), ok end local double_ct = ffi.typeof('double[1]') local float_ct = ffi.typeof('float[1]') local int_ct = ffi.typeof('int[1]') local bool_ct = ffi.typeof('bool[1]') --- Get the parameter value for key key. -- @tparam string key The key to get the value for -- @treturn number The key value -- @treturn bool true if the parameter value was retrieved, false otherwise function NodeHandle:getParamDouble(key) local result = double_ct(0) local ok = f.getParamDouble(self.o, key, result) return result[0], ok end --- Get the parameter value for key key. -- @tparam string key The key to get the value for -- @treturn number The key value -- @treturn bool true if the parameter value was retrieved, false otherwise function NodeHandle:getParamFloat(key) local result = float_ct(0) local ok = f.getParamFloat(self.o, key, result) return result[0], ok end --- Get the parameter value for key key. -- @tparam string key The key to get the value for -- @treturn int The key value -- @treturn bool true if the parameter value was retrieved, false otherwise function NodeHandle:getParamInt(key) local result = int_ct(0) local ok = f.getParamInt(self.o, key, result) return result[0], ok end --- Get the parameter value for key key. -- @tparam string key The key to get the value for -- @treturn bool The key value -- @treturn bool true if the parameter value was retrieved, false otherwise function NodeHandle:getParamBool(key) local result = bool_ct(0) local ok = f.getParamBool(self.o, key, result) return result[0], ok end --- Set the parameter value for key key. -- @tparam string key The key to set the value -- @tparam string value The value of the key -- @treturn bool true if the parameter value was set successfully, false otherwise function NodeHandle:setParamString(key, value) f.setParamString(self.o, key, value) end --- Set the parameter value for key key. -- @tparam string key The key to set the value -- @tparam number value The value of the key -- @treturn bool true if the parameter value was set successfully, false otherwise function NodeHandle:setParamDouble(key, value) f.setParamDouble(self.o, key, value) end --- Set the parameter value for key key. -- @tparam string key The key to set the value -- @tparam number value The value of the key -- @treturn bool true if the parameter value was set successfully, false otherwise function NodeHandle:setParamFloat(key, value) f.setParamFloat(self.o, key, value) end --- Set the parameter value for key key. -- @tparam string key The key to set the value -- @tparam int value The value of the key -- @treturn bool true if the parameter value was set successfully, false otherwise function NodeHandle:setParamInt(key, value) f.setParamInt(self.o, key, value) end --- Set the parameter value for key key. -- @tparam string key The key to set the value -- @tparam bool value The value of the key -- @treturn bool true if the parameter value was set successfully, false otherwise function NodeHandle:setParamBool(key, value) f.setParamBool(self.o, key, value) end --- Get the parameter value for key key. -- @tparam string key The key to get the value for -- @treturn std.StringVector The key value -- @treturn bool true if the parameters value was retrieved, false otherwise function NodeHandle:getParamStringVector(key) local result = std.StringVector() local ok = f.getParamStringVector(self.o, key, result:cdata()) return result, ok end --- Get the parameter value for key key. -- @tparam string key The key to get the value for -- @treturn torch.ByteTensor The key value -- @treturn bool true if the parameters value was retrieved, false otherwise function NodeHandle:getParamBoolVector(key) local result = torch.ByteTensor() local ok = f.getParamBoolVector(self.o, key, result:cdata()) return result, ok end --- Get the parameter value for key key. -- @tparam string key The key to get the value for -- @treturn torch.IntTensor The key value -- @treturn bool true if the parameters value was retrieved, false otherwise function NodeHandle:getParamIntVector(key) local result = torch.IntTensor() local ok = f.getParamIntVector(self.o, key, result:cdata()) return result, ok end --- Get the parameter value for key key. -- @tparam string key The key to get the value for -- @treturn torch.DoubleTensor The key value -- @treturn bool true if the parameters value was retrieved, false otherwise function NodeHandle:getParamDoubleVector(key) local result = torch.DoubleTensor() local ok = f.getParamDoubleVector(self.o, key, result:cdata()) return result, ok end --- Get the parameter value for key key. -- @tparam string key The key to get the value for -- @treturn torch.FloatTensor The key value -- @treturn bool true if the parameters value was retrieved, false otherwise function NodeHandle:getParamFloatVector(key) local result = torch.FloatTensor() local ok = f.getParamDoubleVector(self.o, key, result:cdata()) return result, ok end --- Get the parameter value for key key. -- @tparam string key The key to get the value for -- @treturn std.StringMap The key value -- @treturn bool true if the parameters value was retrieved, false otherwise function NodeHandle:getParamStringMap(key) local result = std.StringMap() local ok = f.getParamStringMap(self.o, key, result:cdata()) return result, ok end --- Set the parameter value for key key. -- @tparam string key The key to set the value -- @tparam std.StringVector value The value of the key -- @treturn bool true if the parameter value was set successfully, false otherwise function NodeHandle:setParamStringVector(key, value) f.setParamStringVector(self.o, key, value:cdata()) end --- Set the parameter value for key key. -- @tparam string key The key to set the value -- @tparam torch.ByteTensor value The value of the key -- @treturn bool true if the parameter value was set successfully, false otherwise function NodeHandle:setParamBoolVector(key, value) f.setParamBoolVector(self.o, key, value:cdata()) end --- Set the parameter value for key key. -- @tparam string key The key to set the value -- @tparam torch.IntTensor value The value of the key -- @treturn bool true if the parameter value was set successfully, false otherwise function NodeHandle:setParamIntVector(key, value) f.setParamIntVector(self.o, key, value:cdata()) end --- Set the parameter value for key key. -- @tparam string key The key to set the value -- @tparam torch.DoubleTensor value The value of the key -- @treturn bool true if the parameter value was set successfully, false otherwise function NodeHandle:setParamDoubleVector(key, value) f.setParamDoubleVector(self.o, key, value:cdata()) end --- Set the parameter value for key key. -- @tparam string key The key to set the value -- @tparam torch.FloatTensor value The value of the key -- @treturn bool true if the parameter value was set successfully, false otherwise function NodeHandle:setParamFloatVector(key, value) f.setParamFloatVector(self.o, key, value:cdata()) end --- Get an arbitrary XML/RPC value from the parameter server. -- @tparam string key The key to get the value -- @treturn table function NodeHandle:getParamVariable(key) local result = std.Variable() f.getParamVariable(self.o, key, result:cdata()) return result:get() end
bsd-3-clause
aqasaeed/hesamm
plugins/inrealm.lua
10
24043
-- 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 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 function run(msg, matches) --vardump(msg) 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 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 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] == '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 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)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
Ninjistix/darkstar
scripts/globals/weaponskills/detonator.lua
10
1667
----------------------------------- -- Detonator -- Marksmanship weapon skill -- Skill Level: 250 -- Delivers a single-hit attack. Damage varies with TP. -- In order to obtain Detonator, the quest Shoot First, Ask Questions Later must be completed. -- Despite the lack of a STR weaponskill mod, STR is still the most potent stat for increasing this weaponskill's damage to the point at which fSTR2 is capped. -- Aligned with the Flame Gorget & Light Gorget. -- Aligned with the Flame Belt & Light Belt. -- Element: None -- Modifiers: AGI:30% -- 100%TP 200%TP 300%TP -- 1.50 2.00 2.50 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 1; params.ftp100 = 1.5; params.ftp200 = 2; params.ftp300 = 2.5; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.3; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 1.5; params.ftp200 = 2.5; params.ftp300 = 5.0; params.agi_wsc = 0.7; end local damage, criticalHit, tpHits, extraHits = doRangedWeaponskill(player, target, wsID, params, tp, primary, action); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Ninjistix/darkstar
scripts/globals/items/ukonvasara.lua
3
3322
----------------------------------------- -- ID: 19461 -- Item: Ukonvasara ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/msg"); require("scripts/globals/weaponskills"); require("scripts/globals/weaponskillids"); ----------------------------------- local NAME_WEAPONSKILL = "AFTERMATH_UKONVASARA"; local NAME_EFFECT_LOSE = "AFTERMATH_LOST_UKONVASARA"; -- https://www.bg-wiki.com/bg/Relic_Aftermath local aftermathTable = {}; -- Ukonvasara 85 aftermathTable[19461] = { { -- Tier 1 duration = 30, mods = { { id = MOD_REM_OCC_DO_DOUBLE_DMG, power = 30 } } }, { -- Tier 2 duration = 60, mods = { { id = MOD_REM_OCC_DO_DOUBLE_DMG, power = 40 } } }, { -- Tier 3 duration = 60, mods = { { id = MOD_REM_OCC_DO_DOUBLE_DMG, power = 50 } } } }; aftermathTable[19539] = aftermathTable[19461]; -- Ukonvasara (90) aftermathTable[19637] = aftermathTable[19461]; -- Ukonvasara (95) aftermathTable[19810] = aftermathTable[19461]; -- Ukonvasara (99) aftermathTable[19858] = aftermathTable[19461]; -- Ukonvasara (99/II) aftermathTable[20839] = aftermathTable[19461]; -- Ukonvasara (119) aftermathTable[20840] = aftermathTable[19461]; -- Ukonvasara (119/II) -- Ukonvasara (119/III) aftermathTable[21758] = { { -- Tier 1 duration = 60, mods = { { id = MOD_REM_OCC_DO_TRIPLE_DMG, power = 30 } } }, { -- Tier 2 duration = 120, mods = { { id = MOD_REM_OCC_DO_TRIPLE_DMG, power = 40 } } }, { -- Tier 3 duration = 180, mods = { { id = MOD_REM_OCC_DO_TRIPLE_DMG, power = 50 } } } }; function onWeaponskill(user, target, wsid, tp, action) if (wsid == WEAPONSKILL_UKKOS_FURY) then -- Ukko's Fury onry local itemId = user:getEquipID(SLOT_MAIN); if (shouldApplyAftermath(user, tp)) then if (aftermathTable[itemId]) then -- Apply the effect and add mods addEmpyreanAftermathEffect(user, tp, aftermathTable[itemId]); -- Add a listener for when aftermath wears (to remove mods) user:addListener("EFFECT_LOSE", NAME_EFFECT_LOSE, aftermathLost); end end end end function aftermathLost(target, effect) if (effect:getType() == EFFECT_AFTERMATH) then local itemId = target:getEquipID(SLOT_MAIN); if (aftermathTable[itemId]) then -- Remove mods removeEmpyreanAftermathEffect(target, effect, aftermathTable[itemId]); -- Remove the effect listener target:removeListener(NAME_EFFECT_LOSE); end end end function onItemCheck(player, param, caster) if (param == ITEMCHECK_EQUIP) then player:addListener("WEAPONSKILL_USE", NAME_WEAPONSKILL, onWeaponskill); elseif (param == ITEMCHECK_UNEQUIP) then -- Make sure we clean up the effect and mods if (player:hasStatusEffect(EFFECT_AFTERMATH)) then aftermathLost(player, player:getStatusEffect(EFFECT_AFTERMATH)); end player:removeListener(NAME_WEAPONSKILL); end return 0; end
gpl-3.0
Ninjistix/darkstar
scripts/zones/Northern_San_dOria/Zone.lua
4
3995
----------------------------------- -- -- Zone: Northern_San_dOria (231) -- ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/events/harvest_festivals"); require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/zones/Northern_San_dOria/MobIDs"); require("scripts/globals/conquest"); require("scripts/globals/missions"); require("scripts/globals/npc_util"); require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/titles"); require("scripts/globals/zone"); ----------------------------------- function onInitialize(zone) SetExplorerMoogles(N_SANDY_EXPLORER_MOOGLE); zone:registerRegion(1, -7,-3,110, 7,-1,155); applyHalloweenNpcCostumes(zone:getID()) end; function onZoneIn(player,prevZone) local currentMission = player:getCurrentMission(SANDORIA); local MissionStatus = player:getVar("MissionStatus"); local cs = -1; -- FIRST LOGIN (START CS) if (player:getPlaytime(false) == 0) then if (OPENING_CUTSCENE_ENABLE == 1) then cs = 535; end player:setPos(0,0,-11,191); player:setHomePoint(); end -- MOG HOUSE EXIT if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(130,-0.2,-3,160); if (player:getMainJob() ~= player:getVar("PlayerMainJob")) then cs = 30004; end player:setVar("PlayerMainJob",0); end -- RDM AF3 CS if (player:getVar("peaceForTheSpiritCS") == 5 and player:getFreeSlotsCount() >= 1) then cs = 49; elseif (player:getCurrentMission(COP) == THE_ROAD_FORKS and player:getVar("EMERALD_WATERS_Status") == 1) then --EMERALD_WATERS-- COP 3-3A: San d'Oria Route player:setVar("EMERALD_WATERS_Status",2); cs = 0x000E; elseif (currentMission == THE_HEIR_TO_THE_LIGHT and MissionStatus == 0) then cs = 1; elseif (currentMission == THE_HEIR_TO_THE_LIGHT and MissionStatus == 4) then cs = 0; elseif (player:hasCompletedMission(SANDORIA,COMING_OF_AGE) and tonumber(os.date("%j")) == player:getVar("Wait1DayM8-1_date")) then cs = 16; end return cs; end; function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; function onRegionEnter(player,region) switch (region:GetRegionID()): caseof { [1] = function (x) -- Chateau d'Oraguille access pNation = player:getNation(); currentMission = player:getCurrentMission(pNation) if ((pNation == 0 and player:getRank() >= 2) or (pNation > 0 and player:hasCompletedMission(pNation,5) == 1) or (currentMission >= 5 and currentMission <= 9) or (player:getRank() >= 3)) then player:startEvent(569); else player:startEvent(568); end end, } end; function onRegionLeave(player,region) end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 535) then player:messageSpecial(ITEM_OBTAINED,536); -- adventurer coupon elseif (csid == 1) then player:setVar("MissionStatus",1); elseif (csid == 0) then player:setVar("MissionStatus",5); elseif (csid == 30004 and option == 0) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); elseif (csid == 569) then player:setPos(0,0,-13,192,0xe9); elseif (csid == 49 and npcUtil.completeQuest(player, SANDORIA, PEACE_FOR_THE_SPIRIT, {item = 12513, fame = AF3_FAME, title = PARAGON_OF_RED_MAGE_EXCELLENCE})) then player:setVar("peaceForTheSpiritCS",0); elseif (csid == 16) then player:setVar("Wait1DayM8-1_date",0); player:setVar("Mission8-1Completed",1); end end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Periqia/IDs.lua
7
6561
Periqia = { text = { -- General Texts ITEM_CANNOT_BE_OBTAINED = 6381, -- You cannot obtain the <item>. Come back after sorting your inventory. FULL_INVENTORY_AFTER_TRADE = 6385, -- You cannot obtain the <item>. Try trading again after sorting your inventory. ITEM_OBTAINED = 6387, -- Obtained: <item>. GIL_OBTAINED = 6388, -- Obtained <number> gil. KEYITEM_OBTAINED = 6390, -- Obtained key item: <keyitem>. KEYITEM_LOST = 6391, -- Lost key item: <keyitem>. NOT_HAVE_ENOUGH_GIL = 6392, -- You do not have enough gil. ITEMS_OBTAINED = 6396, -- You obtain <number> <item>! -- Assault Texts ASSAULT_31_START = 7476, -- Commencing <assault>! Objective: Escort the prisoner ASSAULT_32_START = 7477, -- Commencing <assault>! Objective: Destroy the undead ASSAULT_33_START = 7478, -- Commencing <assault>! Objective: Find the survivors ASSAULT_34_START = 7479, -- Commencing <assault>! Objective: Eliminate the Black Baron ASSAULT_35_START = 7480, -- Commencing <assault>! Objective: Activate the bridge ASSAULT_36_START = 7481, -- Commencing <assault>! Objective: xterminate the chigoes ASSAULT_37_START = 7482, -- Commencing <assault>! Objective: Clear the mine fields ASSAULT_38_START = 7483, -- Commencing <assault>! Objective: Locate the generals ASSAULT_39_START = 7484, -- Commencing <assault>! Objective: Retrieve the Mark-IIs ASSAULT_40_START = 7485, -- Commencing <assault>! Objective: Assassinate King Goldemar TIME_TO_COMPLETE = 7506, -- You have <number> [minute/minutes] (Earth time) to complete this mission. MISSION_FAILED = 7507, -- The mission has failed. Leaving area. RUNE_UNLOCKED_POS = 7508, -- Mission objective completed. Unlocking Rune of Release <rune>. RUNE_UNLOCKED = 7509, -- Mission objective completed. Unlocking Rune of Release. ASSAULT_POINTS_OBTAINED = 7510, -- You gain <number> [Assault point/Assault points]! TIME_REMAINING_MINUTES = 7511, -- Time remaining: <number> [minute/minutes] (Earth time). TIME_REMAINING_SECONDS = 7512, -- Time remaining: <number> [second/seconds] (Earth time). PARTY_FALLEN = 7514, -- All party members have fallen in battle. Mission failure in <number> [minute/minutes]. -- Seagull Grounded EXCALIACE_START = 7523, -- Such a lot of trouble for one little corsair... Shall we be on our way? EXCALIACE_END1 = 7524, -- Yeah, I got it. Stay here and keep quiet. EXCALIACE_END2 = 7525, -- Hey... It was a short trip, but nothing is ever dull around you, huh? EXCALIACE_ESCAPE = 7526, -- Heh. The Immortals really must be having troubles finding troops if they sent this bunch of slowpokes to watch over me... EXCALIACE_PAIN1 = 7527, -- Oomph! EXCALIACE_PAIN2 = 7528, -- Ouch! EXCALIACE_PAIN3 = 7529, -- Youch! EXCALIACE_PAIN4 = 7530, -- Damn, that's gonna leave a mark! EXCALIACE_PAIN5 = 7531, -- Urggh! EXCALIACE_CRAB1 = 7532, -- Over to you. EXCALIACE_CRAB2 = 7533, -- What's this guy up to? EXCALIACE_CRAB3 = 7534, -- Uh-oh. EXCALIACE_DEBAUCHER1 = 7535, -- Wh-what the...!? EXCALIACE_DEBAUCHER2 = 7536, -- H-help!!! EXCALIACE_RUN = 7537, -- Now's my chance! EXCALIACE_TOO_CLOSE = 7538, -- Okay, okay, you got me! I promise I won't run again if you step back a bit...please. Someone's been eating too much garlic... EXCALIACE_TIRED = 7539, -- <Pant>...<wheeze>... EXCALIACE_CAUGHT = 7540, -- Damn... }, mobs = { -- Seagull Grounded [31] = { CRAB1 = 17006594, CRAB2 = 17006595, CRAB3 = 17006596, CRAB4 = 17006597, CRAB5 = 17006598, CRAB6 = 17006599, CRAB7 = 17006600, CRAB8 = 17006601, CRAB9 = 17006602, DEBAUCHER1 = 17006603, PUGIL1 = 17006604, PUGIL2 = 17006605, PUGIL3 = 17006606, PUGIL4 = 17006607, PUGIL5 = 17006608, DEBAUCHER2 = 17006610, DEBAUCHER3 = 17006611, }, -- Shades of Vengeance [79] = { K23H1LAMIA1 = 17006754, K23H1LAMIA2 = 17006755, K23H1LAMIA3 = 17006756, K23H1LAMIA4 = 17006757, K23H1LAMIA5 = 17006758, K23H1LAMIA6 = 17006759, K23H1LAMIA7 = 17006760, K23H1LAMIA8 = 17006761, K23H1LAMIA9 = 17006762, K23H1LAMIA10 = 17006763, } }, npcs = { EXCALIACE = 17006593, ANCIENT_LOCKBOX = 17006809, RUNE_OF_RELEASE = 17006810, _1K1 = 17006840, _1K2 = 17006841, _1K3 = 17006842, _1K4 = 17006843, _1K5 = 17006844, _1K6 = 17006845, _1K7 = 17006846, _1K8 = 17006847, _1K9 = 17006848, _1KA = 17006849, _1KB = 17006850, _1KC = 17006851, _1KD = 17006852, _1KE = 17006853, _1KF = 17006854, _1KG = 17006855, _1KH = 17006856, _1KI = 17006857, _1KJ = 17006858, _1KK = 17006859, _1KL = 17006860, _1KM = 17006861, _1KN = 17006862, _1KO = 17006863, _1KP = 17006864, _1KQ = 17006865, _1KR = 17006866, _1KS = 17006867, _1KT = 17006868, _1KU = 17006869, _1KV = 17006870, _1KW = 17006871, _1KX = 17006872, _1KY = 17006873, _1KZ = 17006874, _JK0 = 17006875, _JK1 = 17006876, _JK2 = 17006877, _JK3 = 17006878, _JK4 = 17006879, _JK5 = 17006880, _JK6 = 17006881, _JK7 = 17006882, _JK8 = 17006883, _JK9 = 17006884, _JKA = 17006885, _JKB = 17006886, _JKC = 17006887, _JKD = 17006888, _JKE = 17006889, _JKF = 17006890, _JKG = 17006891, _JKH = 17006892, _JKI = 17006893, _JKJ = 17006894, _JKK = 17006895, _JKL = 17006896, _JKM = 17006897, _JKN = 17006898, _JKO = 17006899, } }
gpl-3.0
blackman1380/antispam
plugins/plugins.lua
4
5891
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 = '|Disable|' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '|Enable|' 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..'\nBot Version > 6.7' 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 = '|Disable|' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '|Enable|' 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..'\nBot Version > 6.7' 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 '*Error 404\n> (Plugin #'..plugin_name..' Not Found)' 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 "Error 404 (#Plugin_Not_Found)" 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 '' 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] == '+' 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] == '+' 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] == '-' and matches[3] == 'chat' then local plugin = matches[2] local receiver = get_receiver(msg) print(" ") return disable_plugin_on_chat(receiver, plugin) end -- Disable a plugin if matches[1] == '-' 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] == '?' 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 = { "plug - [plugin] chat : disable plugin only this chat.", "plug + [plugin] chat : enable plugin only this chat.", }, sudo = { "plug : list all plugins.", "plug + [plugin] : enable plugin.", "plug - [plugin] : disable plugin.", "plug ? : reloads all plugins." }, }, patterns = { "^[!/#]plugins$", "^[Pp]lug? (-) ([%w_%.%-]+)", "^[Pp]lug? (+) ([%w_%.%-]+) (chat)", "^[Pp]lug? (+) ([%w_%.%-]+)", "^[Pp]lug? (-) ([%w_%.%-]+) (chat)" }, run = run, moderated = true, -- set to moderator mode --privileged = true } end --Edited By @MehdiHS
gpl-2.0
jamiepg1/MCServer
MCServer/Plugins/APIDump/Hooks/OnChunkUnloading.lua
8
1082
return { HOOK_CHUNK_UNLOADING = { CalledWhen = " A chunk is about to be unloaded from the memory. Plugins may refuse the unload.", DefaultFnName = "OnChunkUnloading", -- also used as pagename Desc = [[ MCServer calls this function when a chunk is about to be unloaded from the memory. A plugin may force MCServer to keep the chunk in memory by returning true.</p> <p> FIXME: The return value should be used only for event propagation stopping, not for the actual decision whether to unload. ]], Params = { { Name = "World", Type = "{{cWorld}}", Notes = "The world from which the chunk is unloading" }, { Name = "ChunkX", Type = "number", Notes = "X-coord of the chunk" }, { Name = "ChunkZ", Type = "number", Notes = "Z-coord of the chunk" }, }, Returns = [[ If the function returns false or no value, the next plugin's callback is called and finally MCServer unloads the chunk. If the function returns true, no other callback is called for this event and the chunk is left in the memory. ]], }, -- HOOK_CHUNK_UNLOADING }
apache-2.0
hvbommel/domoticz
dzVents/runtime/tests/testLodash.lua
9
21814
local scriptPath = '' package.path = ";../?.lua;" .. scriptPath .. '/?.lua;../device-adapters/?.lua;../../../scripts/lua/?.lua;' .. package.path describe('lodash:', function() local _ = require 'lodash' local utils = require('Utils') setup(function() _G.logLevel = 1 _G.log = function() end _G.globalvariables = { Security = 'sec', ['radix_separator'] = '.', ['script_path'] = scriptPath, ['domoticz_listening_port'] = '8080' } end) pprint = function(...) return _.table(...) end showResult = function(...) local t = _.table(...) for i, v in ipairs(t) do t[i] = _.str(t[i]) end return _.args(t) end teardown(function() utils = nil _ = nil end) describe("Section Array", function() it('should have function _.chunk.', function() assert.is_true(_.isEqual(_.chunk({'x', 'y', 'z', 1, 2, 3, 4, true , false}, 4), {{"x", "y", "z", 1}, {2, 3, 4, true}, {false}})) end) it('should have function _.compact.', function() assert.is_same(showResult(_.compact({'x', 'y', nil, 1, 2, 3, false, true , false})),'{"x", "y", 1, 2, 3, true}') end) it('should have function _.difference.', function() assert.is_same(showResult(_.difference({3, 1, 2, 9, 5, 9}, {4, 5}, {9, 1})),'{3, 2}') end) it('should have function _.drop.', function() assert.is_same(showResult(_.drop({1, 2, 3, 4, 5, 6}, 2)),'{3, 4, 5, 6}') end) it('should have function _.dropRight.', function() assert.is_same(showResult(_.dropRight({1, 2, 3, 4, 5, 6}, 2)),'{1, 2, 3, 4}') end) it('should have function _.dropRightWhile.', function() assert.is_same(showResult(_.dropRightWhile({1, 5, 2, 3, 4, 5, 4, 4})),'{}') end) it('should have function _.dropWhile.', function() assert.is_same(showResult(_.dropWhile({1, 2, 2, 3, 4, 5, 4, 4, 2})),'{}') end) it('should have function _.enqueue.', function() t = {1, 2, 2, 3, 4, 5, 4, 4, 2} _.enqueue(t, 12) assert.is_same(showResult(t),'{12, 1, 2, 2, 3, 4, 5, 4, 4, 2}') end) it('should have function _.fill.', function() t = {1, 2, 3, 4} _.fill(t,'x', 2, 3) assert.is_same(showResult(t),'{1, "x", "x", 4}') end) it('should have function _.findIndex.', function() assert.is_same(showResult(_.findIndex({{a = 1}, {a = 2}, {a = 3}, {a = 2}, {a = 3}})),'1') end) it('should have function _.findLastIndex.', function() assert.is_same(showResult(_.findLastIndex({{a = 1}, {a = 2}, {a = 3}, {a = 2}, {a = 3}})),'5') end) it('should have function _.first.', function() assert.is_same(showResult(_.first({'w', 'x', 'y', 'z'})),'w') end) it('should have function _.flatten.', function() assert.is_same(showResult(_.flatten({1, 2, {3, 4, {5, 6}}})),'{1, 2, 3, 4, {5, 6}}') end) it('should have function _.flattenDeep.', function() assert.is_same(showResult(_.flattenDeep({1, 2, {3, 4, {5, 6}}})),'{1, 2, 3, 4, 5, 6}') end) it('should have function _.indexOf.', function() assert.is_same(showResult(_.indexOf({2, 3, 'x', 4}, 'x')),'3') end) it('should have function _.initial.', function() assert.is_same(showResult(_.initial({1, 2, 3, 'a'})),'{1, 2, 3}') end) it('should have function _.intersection.', function() assert.is_same(showResult(_.intersection({1, 2}, {4, 2}, {2, 1})),'{2}') end) it('should have function _.last.', function() assert.is_same(showResult(_.last({'w', 'x', 'y', 'z'})),'z') end) it('should have function _.lastIndexOf.', function() assert.is_same(showResult(_.lastIndexOf({2, 3, 'x', 4, 'x', 5}, 'x')),'5') end) it('should have function _.pull.', function() local t = {1, 2, 3, 4, 5, 4, 1, 2, 3} _.pull(t, 2, 3) assert.is_same(showResult(t,'{1, 4, 5, 4, 1}')) end) it('should have function _.pullAt.', function() local t = {1, 2, 4} _.pullAt(t, 3) assert.is_same(showResult(t,'{1, 2}')) end) it('should have function _.push.', function() local t = {1, 2, 3} _.push(t, 4) assert.is_same(showResult(t,'{1, 2, 3, 4}')) end) it('should have function _.remove.', function() local t = {1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 1, 2, 3, 5, 4} local removed = _.remove(t, function(value) return value > 4 end) assert.is_same(showResult(t, '{1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4}' )) assert.is_same(showResult(removed, '{5, 6, 7, 5, 6, 5}')) end) it('should have function _.rest.', function() assert.is_same(showResult(_.rest({1, 2, 3, 'a'})),'{2, 3, "a"}') end) it('should have function _.reverse.', function() assert.is_same(showResult(_.reverse({1, 2, 3, 'a', 'b'})),'{"b", "a", 3, 2, 1}') end) it('should have function _.slice.', function() assert.is_same(showResult(_.slice({1, 2, 3, 4, 5, 6}, 2, 3)),'{2, 3}') end) it('should have function _.take.', function() assert.is_same(showResult(_.take({1, 2, 3, 4, 5}, 3)),'{1, 2, 3}') end) it('should have function _.takeRight.', function() assert.is_same(showResult(_.takeRight({1, 2, 3, 4, 5}, 3)),'{3, 4, 5}') end) it('should have function _.takeRightWhile.', function() assert.is_same(showResult(_.takeRightWhile({1, 2, 3, 4, 5, 6, 7, 8})),'{1, 2, 3, 4, 5, 6, 7, 8}') end) it('should have function _.takeWhile.', function() assert.is_same(showResult(_.takeWhile({1, 2, 3, 4, 5, 6, 7, 8})),'{1, 2, 3, 4, 5, 6, 7, 8}') end) it('should have function _.union.', function() assert.is_same(showResult(_.union({1, 2}, {4, 2}, {2, 1})),'{1, 2, 4}') end) it('should have function _.uniq.', function() assert.is_same(showResult(_.uniq({1, 3, 2, 2})),'{1, 3, 2}') end) it('should have function _.unzip.', function() local t = _.zip({'a', 'b', 'c'}, {1, 2, 3}, {10, 20, 30}) assert.is_same(showResult(_.unzip(t), '{{"a", "b", "c"}, {1, 2, 3}, {10, 20, 30}}')) end) it('should have function _.without.', function() assert.is_same(showResult(_.without({1, 1, 2, 3, 2, 3, 5, 5, 1, 2}, 5, 1)),'{2, 3, 2, 3, 2}' ) end) it('should have function _.zip.', function() local t = _.zip({'a', 'b', 'c'}, {1, 2, 3}, {10, 20, 30}) assert.is_same(showResult(t), '{{"a", 1, 10}, {"b", 2, 20}, {"c", 3, 30}}') end) it('should have function _.zipObject.', function() local t = {{'fred', 30}, {'alex', 20}} local t = _.zipObject(t) assert.is_same(showResult(t.fred),'30') assert.is_same(showResult(t.alex),'20') end) end) describe("Section Collection", function() it('should have function _.at', function() assert.is_same(showResult(_.at({'1', '2', '3', '4', a='a', b='b'}, {1, 2}, 'b')), '{"1", "2", "b"}' ) end) it('should have function _.countBy.', function() assert.is_same(showResult(_.countBy({'dzVents' , 'dzVents', 4.3, 6.1, 6.4, 6.1}).dzVents,'2')) end) it('should have function _.indexBy.', function() local keyData = { {dir='l', a=1}, {dir='r', a=2}} local t = _.indexBy(keyData, function(n) return n.dir end) assert.is_same(showResult(t.r.a,'2')) end) it('should have function _.every.', function() _.every({1, 2, 3, 4, '5', 6}, _.isNumber) assert.is_false(_.every({1, 2, 3, 4, '5', 6}, _.isNumber)) assert.is_true(_.every({1, 2, 3, 4, 5, 6.2}, _.isNumber)) end) it('should have function _.filter.', function() assert.is_same(showResult(_.filter({1, 2, 3, 4, '5', 6, '7'}, _.isNumber),'{1, 2, 3, 4, 6}')) end) it('should have function _.find.', function() local t = {{a = 1}, {a = 2}, {a = 3}, {a = 2}, {a = 3}} assert.is_true(_.isEqual(_.find(t, function(v) return v.a == 3 end ), { a = 3 })) end) it('should have function _.findLast.', function() local t = {{a = 1}, {a = 2}, {a = 3, x = 1}, {a = 2}, {a = 3, x = 2}} assert.is_true(_.isEqual(_.findLast(t, function(v) return v.a == 3 end ), {x = 2, a = 3})) end) it('should have function _.forEach.', function() assert.is_same(showResult(_.forEach({1, 2, 3, 4, '5', 6, '7'}),'{1, 2, 3, 4, "5", 6, "7"}')) end) it('should have function _.forEachRight.', function() assert.is_same(showResult(_.forEachRight({1, 2, 3, 4, '5', 6, '7'}),'{1, 2, 3, 4, "5", 6, "7"}')) end) it('should have function _.groupBy.', function() local t = _.groupBy({4.3, 6.1, 6.4}, function(n) return math.floor(n) end) assert.is_true(_.isEqual(t, {["4"]={4.3}, ["6"]={6.1, 6.4}})) end) it('should have function _.includes.', function() assert.is_true(_.includes({1, 2, 'x', 3, ['5']=4, x=3, 5}, 'x')) assert.is_false(_.includes({1, 2, 'x', 3, ['5']=4, x=3, 5}, 'z')) end) it('should have function _.invoke.', function() assert.is_same(showResult(_.invoke({'1.first', '2.second', '3.third'}, string.sub, 1, 1),'{"1", "2", "3"}')) end) it('should have function _.map.', function() local t = _.map({1, 2, 3, 4, 5, 6, 7, 8, 9}, function(n) return n * n end) assert.is_same(showResult(t,'{1, 4, 9, 16, 25, 36, 49, 64, 81}')) end) it('should have function _.partition.', function() local t = _.partition({1, 2, 3, 4, 5, 6, 7}, function (n) return n > 3 end) assert.is_same(showResult(t,'{{4, 5, 6, 7}, {1, 2, 3}}')) end) it('should have function _.pluck.', function() local users = {{ user = 'barney', age = 36, child = {age = 5}}, { user = 'fred', age = 40, child = {age = 6} }} assert.is_same(showResult(_.pluck(users, {'user'})),'{"barney", "fred"}') assert.is_same(showResult(_.pluck(users, {'user'})),'{"barney", "fred"}') end) it('should have function _.reduce.', function() assert.is_same(showResult(_.reduce({1, 2, 3}, function(total, n) return n + total end), '6')) local expectedResult = { b = 6, a = 3} assert.is_true(_.isEqual(_.reduce({a = 1, b = 2}, function(result, n, key) result[key] = n * 3 return result end, {}), expectedResult )) end) it('should have function _.reduceRight.', function() assert.is_same(showResult(_.reduceRight({0, 1, 2, 3, 4, 5}, function(str, other) return str .. other end ), '543210')) end) it('should have function _.reject.', function() assert.is_same(showResult(_.reject({1, 2, 3, 4, '5', 6, '7'}, _.isNumber),'{"5", "7"}')) end) it('should have function _.sample', function() local t = {1, 2, 3, a=4, b='x', 5, 23, 24} local sample = _.sample(t, 98) assert.is_same(#sample, 98) local sample = _.sample(t) assert.is_true(_.includes(t, sample)) end) it('should have function _.size.', function() assert.is_equal(_.size({'abc', 'def'}), 2) assert.is_equal(_.size('abcdefg'), 7) assert.is_equal(_.size({a=1, b=2, c=3}), 3) end) it('should have function _.some.', function() assert.is_false(_.some({1, 2, 3, 4, 5, 6}, _.isString)) assert.is_true(_.some({1, 2, '3', 4, 5, 6}, _.isString)) end) it('should have function _.sortBy.', function() local t = {1, 2, 3} assert.is_true(_.isEqual(_.sortBy(t, function (a) return math.sin(a) end), {1, 3, 2})) local users = { { user='fred'} , { user='alex' }, { user='zoee' }, { user='john' }} assert.is_same(_.sortBy(users, function (a) return a.user end), { { user='alex'}, { user='fred' }, { user='john' }, { user='zoee' }}) end) end) describe("Section Function", function() it('should have function _.after', function() local out = {} local function pprint(str) out[#out+1] = str end local printAfter3 = _.after(3, pprint) for i = 1, 5 do printAfter3('done ' .. i) end assert.is_same(showResult( out , '{"done 4", "done 5"}')) assert.is_same(out , { [1] = "done 4" , [2] = "done 5" }) end) it('should have function _.ary', function() local printOnly3 = _.ary(pprint, 3) assert.is_same( _.slice(printOnly3('a', 3, 'x', 'y', 6), 1, 3) , {'a', 3, 'x' }) end) it('should have function _.before', function() local out = {} local function pprint(...) local t = _.table(...) for i, v in ipairs(t) do out[#out + 1] = _.str(t[i]) end end local printBefore3 = _.before(3, pprint) for i = 1, 10 do printBefore3(i .. ' OK') end assert.is_same(out, { [1] = '1 OK', [2] = '2 OK', [3] = '3 OK' }) end) it('should have function _.modArgs', function() local out = {} local function pprint(...) local t = _.table(...) for i, v in ipairs(t) do out[#out + 1] = _.str(t[i]) end end local increment = function(...) return _.args(_.map(_.table(...), function(n) return n + 1 end)) end local pow = function(...) return _.args(_.map(_.table(...), function(n) return n * n end)) end local modded = _.modArgs(function(...) pprint(...) end, {pow, increment, increment}, { pow, increment }, increment, increment) modded(0, 1, 2) assert.is_same(out, { [1] = '7', [2] = '12', [3] = '39' }) end) it('should have function _.negate', function() local isEven = function (n) return n % 2 == 0 end local isOdd = _.negate(isEven) assert.is_same(_.filter({1, 2, 3, 4, 5, 6}, isEven), {2, 4, 6 }) assert.is_same(_.filter({1, 2, 3, 4, 5, 6}, isOdd), {1, 3, 5}) end) it('should have function _.once', function() local out = {} local function pprint(...) local t = _.table(...) for i, v in ipairs(t) do out[#out + 1] = _.str(t[i]) end end local createApp = function(version) pprint('App created with version '.. version) return version end local initialize = _.once(createApp) initialize(1.1) out[#out+1] = initialize(1.1) assert.is_same(out[1], 'App created with version 1.1' ) assert.is_same(out[2], 1.1 ) end) it('should have function _.rearg', function() local rearged = _.rearg(function(a, b, c) return {a, b, c}; end, 2, 1, 3) assert.is_same(showResult(rearged('a', 'b', 'c'), '{"b", "a", "c"}' )) end) end) describe("Section Language specific", function() it('should have function _.args', function() assert.is_same({_.args({1, 2, 3, 'a', })}, {[1] = 1, [2] = 2, [3] = 3 , [4] = 'a'}) end) it('should have function _.bool', function() assert.is_false(_.bool({1, 2, 3})) assert.is_true(_.bool("123")) assert.is_false(_.bool(0)) assert.is_false(_.bool(nil)) assert.is_true(_.bool(function(a) return a end, "555" )) end) it('should have function _.func', function() local f = _.func(1, 2, 3) assert.is_same({ f() }, {[1] = 1, [2] = 2, [3] = 3}) end) it('should have function _.gt', function() assert.is_false(_.gt(1, 3)) assert.is_false(_.gt(3, 3)) assert.is_true(_.gt(3.1, 3)) end) it('should have function _.gte', function() assert.is_false(_.gte(1, 3)) assert.is_true(_.gte(3, 3)) assert.is_true(_.gte(3.1, 3)) end) it('should have function _.isBoolean', function() assert.is_true(_.isBoolean(false)) assert.is_true(_.isBoolean(true)) assert.is_false(_.isBoolean({})) assert.is_false(_.isBoolean(a)) assert.is_false(_.isBoolean('a')) assert.is_false(_.isBoolean(math.pi)) end) it('should have function _.isEmpty', function() assert.is_true(_.isEmpty(true)) assert.is_true(_.isEmpty(1)) assert.is_false(_.isEmpty({1})) assert.is_false(_.isEmpty({1, 2, 3})) assert.is_false(_.isEmpty({a = 1 })) end) it('should have function _.isFunction', function() assert.is_true(_.isFunction(function() end)) assert.is_false(_.isFunction(1)) end) it('should have function _.isNil', function() assert.is_true(_.isNil(var)) local var = 1 assert.is_false(_.isNil(var)) end) it('should have function _.isNumber', function() assert.is_true(_.isNumber(1)) assert.is_true(_.isNumber(1.12e3)) assert.is_true(_.isNumber(1.1234)) assert.is_false(_.isNumber('1')) end) it('should have function _.isString', function() assert.is_true(_.isString( '1' )) assert.is_false(_.isString( 1 )) assert.is_false(_.isString( {1} )) assert.is_false(_.isString( 1.12e4 )) assert.is_false(_.isString( true )) assert.is_false(_.isString( function() end )) end) it('should have function _.isTable', function() assert.is_true(_.isTable( {} )) assert.is_true(_.isTable( {1} )) assert.is_false(_.isTable( 'a' )) assert.is_false(_.isTable( 1 )) assert.is_false(_.isTable( true )) assert.is_false(_.isTable( function() end )) end) it('should have function _.lt', function() assert.is_true(_.lt(1, 3)) assert.is_false(_.lt(3, 3)) assert.is_false(_.lt(3.1, 3)) end) it('should have function _.lte', function() assert.is_true(_.lte(1, 3)) assert.is_true(_.lte(3, 3)) assert.is_false(_.lte(3.1, 3)) end) it('should have function _.num', function() assert.is_same(_.num({1, 2, 3}), 0) assert.is_same(_.num("123"), 123) assert.is_same(_.num(true), 1) assert.is_same(_.num(function(a) return a end, "555"), 555) end) it('should have function _.str', function() assert.is_same(_.str({1, 2, 3, 4, {k=2, {'x', 'y'}}}),'{1, 2, 3, 4, {{"x", "y"}, ["k"]=2}}') assert.is_same(_.str({1, 2, 3, 4, function(a) return a end}, 5),'{1, 2, 3, 4, 5}') end) it('should have function _.table', function() assert.is_true(_.isEqual(_.slice(_.table(1, 2, 3), 1, 3) , {[1] = 1, [2] = 2, [3] = 3})) assert.is_true(_.isEqual(_.slice(_.table("123"), 1, 1), { [1] = "123"})) end) end) describe("Section Number", function() it('should have function _.inRange', function() assert.is_true(_.inRange(-3, -4, 8)) assert.is_true(_.inRange(-3.5, -4.32, 8)) assert.is_true(_.inRange(-3, -3, 8)) assert.is_false(_.inRange(-4.5, -3, 8)) end) it('should have function _.random', function() assert.is_true(_.inRange(_.random(), 0, 1.1)) assert.is_true(_.inRange(_.random(5), 0, 5.1)) assert.is_true(_.inRange(_.random(4, 5, true), 4, 6)) end) it('should have function _.round', function() assert.is_same(_.round(math.pi), 3 ) assert.is_same(_.round(math.pi, 2), 3.14 ) assert.is_same(_.round(math.pi, 16), 3.1415926535897931170 ) end) end) describe("Section Object", function() it('should have function _.findKey', function() local key = _.findKey({a={a = 1}, b={a = 2}, c={a = 3, x = 1}}, function(v) return v.a == 3 end) assert.is_same(key,'c') end) it('should have function _.findLastKey', function() local lastKey = _.findLastKey({a={a=3}, b={a = 2}, c={a=3, x = 1}}, function(v) return v.a == 2 end) assert.is_same(lastKey,'b') end) it('should have function _.functions', function() assert.is_same(_.functions(debug), { "debug", "gethook", "getinfo", "getlocal", "getmetatable", "getregistry", "getupvalue", "getuservalue", "sethook", "setlocal", "setmetatable", "setupvalue", "setuservalue", "traceback", "upvalueid", "upvaluejoin"} ) assert.is_same(_.functions(string), { "byte", "char", "dump", "find", "format", "gmatch", "gsub", "len", "lower", "match", "pack", "packsize", "rep", "reverse","sMatch", "sub", "unpack", "upper"}) assert.is_same(_.functions(math), { "abs", "acos", "asin", "atan", "atan2", "ceil", "cos", "cosh", "deg", "exp", "floor", "fmod", "frexp", "ldexp", "log", "log10", "max", "min", "modf", "pow", "rad", "random", "randomseed", "sin", "sinh", "sqrt", "tan", "tanh", "tointeger", "type", "ult"}) assert.is_same(_.functions(io), { "close", "flush", "input", "lines", "open", "output", "popen", "read", "tmpfile", "type", "write"}) assert.is_same(_.functions(os), { "clock", "date", "difftime", "execute", "exit", "getenv", "remove", "rename", "setlocale", "time", "tmpname"}) assert.is_same(_.functions(package),{ "loadlib", "searchpath"}) assert.is_same(_.functions(table), { "concat", "insert", "move", "pack", "remove", "sort", "unpack"}) assert.is_same(_.functions(utf8), { "char", "codepoint", "codes", "len", "offset"}) end) it('should have function _.get', function() local object = {a={b={c={d=5}}}} assert.is_same(_.get(object, {'a', 'b', 'c'}), {["d"] = 5}) end) it('should have function _.has', function() local object = {a={b={c={d}}}} assert.is_true(_.has(object, {'a', 'b', 'c'})) assert.is_false(_.has(object, {'a', 'b', 'd'})) end) it('should have function _.invert', function() assert.is_same(_.invert({a='1', b='2', c='3', d='3'}), {["3"]="d", ["2"]="b", ["1"]="a"} ) assert.is_same(_.invert({a= 1, b= 2 , c = 3, d = 4 }), {[3] = "c", [2] = "b", [1] = "a", [4] = "d"} ) end) it('should have function _.keys', function() assert.is_same(_.keys("test"), {1, 2, 3, 4}) assert.is_same(_.keys({ a = 1, b = 2, c = 3} ), {'a', 'b', 'c'}) end) it('should have function _.pairs', function() assert.is_same(_.pairs({1, 2, 'x', a='b'}), {{1, 1}, {2, 2}, {3, 'x'}, {'a', 'b'}}) end) it('should have function _.result', function() local object = {a=5, b={c=function(a) return(a) end}} assert.is_same(_.result(object, {'b', 'c'}, nil, 5), 5) end) it('should have function _.values', function() assert.is_same(_.values("test"), {'t','e','s','t'}) assert.is_same(_.values({a=1, b=3, c=2}), {1, 3, 2}) assert.is_same(_.values({a= { b=3, c=2}}), {{ b = 3 , c = 2}}) end) end) describe("Section Utility", function() it('should have function _.constant', function() local object = {x=5} local getter = _.constant(object) assert.is_true(getter() == object) end) it('should have function _.identitiy', function() local object = {x=5} assert.is_true(_.identity(object) == object) end) it('should have function _.noop', function() local object = {x=5} assert.is_nil(_.noop(object)) end) it('should have function _.range', function() assert.is_same(_.range(4, 36, 4),{4, 8, 12, 16, 20, 24, 28, 32, 36}) end) end) describe("Section Should come last", function() it('should have function _.print', function() _.print('') end) end) end)
gpl-3.0
Ninjistix/darkstar
scripts/zones/Windurst_Waters/npcs/Machitata.lua
5
1336
----------------------------------- -- Area: Windurst Waters -- NPC: Machitata -- Involved in Quest: Hat in Hand -- !pos 163 0 -22 238 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Windurst_Waters/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/titles"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) function testflag(set,flag) return (set % (2*flag) >= flag) end hatstatus = player:getQuestStatus(WINDURST,HAT_IN_HAND); if ((hatstatus == 1 or player:getVar("QuestHatInHand_var2") == 1) and testflag(tonumber(player:getVar("QuestHatInHand_var")),1) == false) then player:messageSpecial(7121); -- Show Off Hat player:setVar("QuestHatInHand_var",player:getVar("QuestHatInHand_var")+1); player:setVar("QuestHatInHand_count",player:getVar("QuestHatInHand_count")+1); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Xagul/forgottenserver
data/creaturescripts/scripts/droploot.lua
19
1207
function onDeath(player, corpse, killer, mostDamage, unjustified, mostDamage_unjustified) if getPlayerFlagValue(player, PlayerFlag_NotGenerateLoot) or player:getVocation():getId() == VOCATION_NONE then return true end local amulet = player:getSlotItem(CONST_SLOT_NECKLACE) if amulet and amulet.itemid == ITEM_AMULETOFLOSS and not isInArray({SKULL_RED, SKULL_BLACK}, player:getSkull()) then local isPlayer = false if killer then if killer:isPlayer() then isPlayer = true else local master = killer:getMaster() if master and master:isPlayer() then isPlayer = true end end end if not isPlayer or not player:hasBlessing(6) then player:removeItem(ITEM_AMULETOFLOSS, 1, -1, false) end else for i = CONST_SLOT_HEAD, CONST_SLOT_AMMO do local item = player:getSlotItem(i) if item then if isInArray({SKULL_RED, SKULL_BLACK}, player:getSkull()) or math.random(item:isContainer() and 100 or 1000) <= player:getLossPercent() then if not item:moveTo(corpse) then item:remove() end end end end end if not player:getSlotItem(CONST_SLOT_BACKPACK) then player:addItem(ITEM_BAG, 1, false, CONST_SLOT_BACKPACK) end return true end
gpl-2.0
Ninjistix/darkstar
scripts/globals/mobskills/guillotine.lua
4
1026
--------------------------------------------- -- Guillotine -- -- Description: Delivers a four-hit attack. Silences enemy. Duration of effect varies with TP. -- Type: Physical -- Number of hits -- Range: Melee --------------------------------------------- require("scripts/globals/monstertpmoves"); require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/msg"); function onMobSkillCheck(target,mob,skill) mob:messageBasic(msgBasic.READIES_WS, 0, 689+256); return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 4; local accmod = 1; local dmgmod = 1.2; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded); MobStatusEffectMove(mob, target, EFFECT_SILENCE, 1, 0, (skill:getTP()*30/1000)+30); -- 242 to a NIN, but shadows ate some hits... target:delHP(dmg); return dmg; end;
gpl-3.0
carnalis/Urho3D
bin/Data/LuaScripts/07_Billboards.lua
24
11790
-- Billboard example. -- This sample demonstrates: -- - Populating a 3D scene with billboard sets and several shadow casting spotlights -- - Parenting scene nodes to allow more intuitive creation of groups of objects -- - Examining rendering performance with a somewhat large object and light count require "LuaScripts/Utilities/Sample" local lightNodes = {} local billboardNodes = {} function Start() -- Execute the common startup for samples SampleStart() -- Create the scene content CreateScene() -- Create the UI content CreateInstructions() -- Setup the viewport for displaying the scene SetupViewport() -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_RELATIVE) -- Hook up to the frame update and render post-update events SubscribeToEvents() end function CreateScene() scene_ = Scene() -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000) -- Also create a DebugRenderer component so that we can draw debug geometry scene_:CreateComponent("Octree") scene_:CreateComponent("DebugRenderer") -- Create a Zone component for ambient lighting & fog control local zoneNode = scene_:CreateChild("Zone") local zone = zoneNode:CreateComponent("Zone") zone.boundingBox = BoundingBox(-1000.0, 1000.0) zone.ambientColor = Color(0.1, 0.1, 0.1) zone.fogStart = 100.0 zone.fogEnd = 300.0 -- Create a directional light without shadows local lightNode = scene_:CreateChild("DirectionalLight") lightNode.direction = Vector3(0.5, -1.0, 0.5) local light = lightNode:CreateComponent("Light") light.lightType = LIGHT_DIRECTIONAL light.color = Color(0.2, 0.2, 0.2) light.specularIntensity = 1.0 -- Create a "floor" consisting of several tiles for y = -5, 5 do for x = -5, 5 do local floorNode = scene_:CreateChild("FloorTile") floorNode.position = Vector3(x * 20.5, -0.5, y * 20.5) floorNode.scale = Vector3(20.0, 1.0, 20.0) local floorObject = floorNode:CreateComponent("StaticModel") floorObject.model = cache:GetResource("Model", "Models/Box.mdl") floorObject.material = cache:GetResource("Material", "Materials/Stone.xml") end end -- Create groups of mushrooms, which act as shadow casters local NUM_MUSHROOMGROUPS = 25 local NUM_MUSHROOMS = 25 for i = 1, NUM_MUSHROOMGROUPS do -- First create a scene node for the group. The individual mushrooms nodes will be created as children local groupNode = scene_:CreateChild("MushroomGroup") groupNode.position = Vector3(Random(190.0) - 95.0, 0.0, Random(190.0) - 95.0) for j = 1, NUM_MUSHROOMS do local mushroomNode = groupNode:CreateChild("Mushroom") mushroomNode.position = Vector3(Random(25.0) - 12.5, 0.0, Random(25.0) - 12.5) mushroomNode.rotation = Quaternion(0.0, Random() * 360.0, 0.0) mushroomNode:SetScale(1.0 + Random() * 4.0) local mushroomObject = mushroomNode:CreateComponent("StaticModel") mushroomObject.model = cache:GetResource("Model", "Models/Mushroom.mdl") mushroomObject.material = cache:GetResource("Material", "Materials/Mushroom.xml") mushroomObject.castShadows = true end end -- Create billboard sets (floating smoke) local NUM_BILLBOARDNODES = 25 local NUM_BILLBOARDS = 10 for i = 1, NUM_BILLBOARDNODES do local smokeNode = scene_:CreateChild("Smoke") smokeNode.position = Vector3(Random(200.0) - 100.0, Random(20.0) + 10.0, Random(200.0) - 100.0) local billboardObject = smokeNode:CreateComponent("BillboardSet") billboardObject.numBillboards = NUM_BILLBOARDS billboardObject.material = cache:GetResource("Material", "Materials/LitSmoke.xml") billboardObject.sorted = true for j = 1, NUM_BILLBOARDS do local bb = billboardObject:GetBillboard(j - 1) bb.position = Vector3(Random(12.0) - 6.0, Random(8.0) - 4.0, Random(12.0) - 6.0) bb.size = Vector2(Random(2.0) + 3.0, Random(2.0) + 3.0) bb.rotation = Random() * 360.0 bb.enabled = true end -- After modifying the billboards, they need to be "committed" so that the BillboardSet updates its internals billboardObject:Commit() table.insert(billboardNodes, smokeNode) end -- Create shadow casting spotlights local NUM_LIGHTS = 9 for i = 0, NUM_LIGHTS - 1 do local lightNode = scene_:CreateChild("SpotLight") local light = lightNode:CreateComponent("Light") local angle = 0.0 local position = Vector3((i % 3) * 60.0 - 60.0, 45.0, math.floor(i / 3) * 60.0 - 60.0) local color = Color(((i + 1) % 2) * 0.5 + 0.5, (math.floor((i + 1) / 2) % 2) * 0.5 + 0.5, (math.floor((i + 1) / 4) % 2) * 0.5 + 0.5) lightNode.position = position lightNode.direction = Vector3(math.sin(M_DEGTORAD * angle), -1.5, math.cos(M_DEGTORAD * angle)) light.lightType = LIGHT_SPOT light.range = 90.0 light.rampTexture = cache:GetResource("Texture2D", "Textures/RampExtreme.png") light.fov = 45.0 light.color = color light.specularIntensity = 1.0 light.castShadows = true light.shadowBias = BiasParameters(0.00002, 0.0) -- Configure shadow fading for the lights. When they are far away enough, the lights eventually become unshadowed for -- better GPU performance. Note that we could also set the maximum distance for each object to cast shadows light.shadowFadeDistance = 100.0 -- Fade start distance light.shadowDistance = 125.0 -- Fade end distance, shadows are disabled -- Set half resolution for the shadow maps for increased performance light.shadowResolution = 0.5 -- The spot lights will not have anything near them, so move the near plane of the shadow camera farther -- for better shadow depth resolution light.shadowNearFarRatio = 0.01 table.insert(lightNodes, lightNode) end -- Create the camera. Limit far clip distance to match the fog cameraNode = scene_:CreateChild("Camera") local camera = cameraNode:CreateComponent("Camera") camera.farClip = 300.0 -- Set an initial position for the camera scene node above the plane cameraNode.position = Vector3(0.0, 5.0, 0.0) end function CreateInstructions() -- Construct new Text object, set string to display and font to use local instructionText = ui.root:CreateChild("Text") instructionText.text = "Use WASD keys and mouse to move\n".. "Space to toggle debug geometry" instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) -- The text has multiple rows. Center them in relation to each other instructionText.textAlignment = HA_CENTER -- Position the text relative to the screen center instructionText.horizontalAlignment = HA_CENTER instructionText.verticalAlignment = VA_CENTER instructionText:SetPosition(0, ui.root.height / 4) end function SetupViewport() -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera")) renderer:SetViewport(0, viewport) end function SubscribeToEvents() -- Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate") -- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request -- debug geometry SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate") end function MoveCamera(timeStep) -- Do not move if the UI has a focused element (the console) if ui.focusElement ~= nil then return end -- Movement speed as world units per second local MOVE_SPEED = 20.0 -- Mouse sensitivity as degrees per pixel local MOUSE_SENSITIVITY = 0.1 -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees local mouseMove = input.mouseMove yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y pitch = Clamp(pitch, -90.0, 90.0) -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero cameraNode.rotation = Quaternion(pitch, yaw, 0.0) -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed if input:GetKeyDown(KEY_W) then cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_S) then cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_A) then cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_D) then cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end -- Toggle debug geometry with space if input:GetKeyPress(KEY_SPACE) then drawDebug = not drawDebug end end function AnimateScene(timeStep) local LIGHT_ROTATION_SPEED = 20.0 local BILLBOARD_ROTATION_SPEED = 50.0 -- Rotate the lights around the world Y-axis for i, v in ipairs(lightNodes) do v:Rotate(Quaternion(0.0, LIGHT_ROTATION_SPEED * timeStep, 0.0), TS_WORLD) end -- Rotate the individual billboards within the billboard sets, then recommit to make the changes visible for i, v in ipairs(billboardNodes) do local billboardObject = v:GetComponent("BillboardSet") for j = 1, billboardObject.numBillboards do local bb = billboardObject:GetBillboard(j - 1) bb.rotation = bb.rotation + BILLBOARD_ROTATION_SPEED * timeStep end billboardObject:Commit() end end function HandleUpdate(eventType, eventData) -- Take the frame time step, which is stored as a float local timeStep = eventData["TimeStep"]:GetFloat() -- Move the camera and animate the scene, scale movement with time step MoveCamera(timeStep) AnimateScene(timeStep) end function HandlePostRenderUpdate(eventType, eventData) -- If draw debug mode is enabled, draw viewport debug geometry. This time use depth test, as otherwise the result becomes -- hard to interpret due to large object count if drawDebug then renderer:DrawDebugGeometry(true) end end -- Create XML patch instructions for screen joystick layout specific to this sample app function GetScreenJoystickPatchString() return "<patch>" .. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" .. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"KeyBinding\" />" .. " <attribute name=\"Text\" value=\"SPACE\" />" .. " </element>" .. " </add>" .. "</patch>" end
mit
dan-cleinmark/nodemcu-firmware
lua_examples/make_phone_call.lua
75
3145
--[[ 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. ]]-- -- Your access point's SSID and password local SSID = "xxxxxx" local SSID_PASSWORD = "xxxxxx" -- configure ESP as a station wifi.setmode(wifi.STATION) wifi.sta.config(SSID,SSID_PASSWORD) wifi.sta.autoconnect(1) local TWILIO_ACCOUNT_SID = "xxxxxx" local TWILIO_TOKEN = "xxxxxx" local HOST = "iot-https-relay.appspot.com" -- visit http://iot-https-relay.appspot.com/ to learn more about this service -- Please be sure to understand the security issues of using this relay app and use at your own risk. local URI = "/twilio/Calls.json" function build_post_request(host, uri, data_table) local data = "" for param,value in pairs(data_table) do data = data .. param.."="..value.."&" end request = "POST "..uri.." HTTP/1.1\r\n".. "Host: "..host.."\r\n".. "Connection: close\r\n".. "Content-Type: application/x-www-form-urlencoded\r\n".. "Content-Length: "..string.len(data).."\r\n".. "\r\n".. data print(request) return request end local function display(sck,response) print(response) end -- When using send_sms: the "from" number HAS to be your twilio number. -- If you have a free twilio account the "to" number HAS to be your twilio verified number. local function make_call(from,to,body) local data = { sid = TWILIO_ACCOUNT_SID, token = TWILIO_TOKEN, Body = string.gsub(body," ","+"), From = from, To = to } socket = net.createConnection(net.TCP,0) socket:on("receive",display) socket:connect(80,HOST) socket:on("connection",function(sck) local post_request = build_post_request(HOST,URI,data) sck:send(post_request) end) end function check_wifi() local ip = wifi.sta.getip() if(ip==nil) then print("Connecting...") else tmr.stop(0) print("Connected to AP!") print(ip) -- make a call with a voice message "your house is on fire" make_call("15558976687","1334856679","Your house is on fire!") end end tmr.alarm(0,2000,1,check_wifi)
mit
eugenesan/openwrt-luci
contrib/luasrcdiet/lua/optparser.lua
122
23598
--[[-------------------------------------------------------------------- optparser.lua: does parser-based optimizations This file is part of LuaSrcDiet. Copyright (c) 2008 Kein-Hong Man <khman@users.sf.net> The COPYRIGHT file describes the conditions under which this software may be distributed. See the ChangeLog for more information. ----------------------------------------------------------------------]] --[[-------------------------------------------------------------------- -- NOTES: -- * For more parser-based optimization ideas, see the TODO items or -- look at technotes.txt. -- * The processing load is quite significant, but since this is an -- off-line text processor, I believe we can wait a few seconds. -- * TODO: might process "local a,a,a" wrongly... need tests! -- * TODO: remove position handling if overlapped locals (rem < 0) -- needs more study, to check behaviour -- * TODO: there are probably better ways to do allocation, e.g. by -- choosing better methods to sort and pick locals... -- * TODO: we don't need 53*63 two-letter identifiers; we can make -- do with significantly less depending on how many that are really -- needed and improve entropy; e.g. 13 needed -> choose 4*4 instead ----------------------------------------------------------------------]] local base = _G local string = require "string" local table = require "table" module "optparser" ---------------------------------------------------------------------- -- Letter frequencies for reducing symbol entropy (fixed version) -- * Might help a wee bit when the output file is compressed -- * See Wikipedia: http://en.wikipedia.org/wiki/Letter_frequencies -- * We use letter frequencies according to a Linotype keyboard, plus -- the underscore, and both lower case and upper case letters. -- * The arrangement below (LC, underscore, %d, UC) is arbitrary. -- * This is certainly not optimal, but is quick-and-dirty and the -- process has no significant overhead ---------------------------------------------------------------------- local LETTERS = "etaoinshrdlucmfwypvbgkqjxz_ETAOINSHRDLUCMFWYPVBGKQJXZ" local ALPHANUM = "etaoinshrdlucmfwypvbgkqjxz_0123456789ETAOINSHRDLUCMFWYPVBGKQJXZ" -- names or identifiers that must be skipped -- * the first two lines are for keywords local SKIP_NAME = {} for v in string.gmatch([[ and break do else elseif end false for function if in local nil not or repeat return then true until while self]], "%S+") do SKIP_NAME[v] = true end ------------------------------------------------------------------------ -- variables and data structures ------------------------------------------------------------------------ local toklist, seminfolist, -- token lists globalinfo, localinfo, -- variable information tables globaluniq, localuniq, -- unique name tables var_new, -- index of new variable names varlist -- list of output variables ---------------------------------------------------------------------- -- preprocess information table to get lists of unique names ---------------------------------------------------------------------- local function preprocess(infotable) local uniqtable = {} for i = 1, #infotable do -- enumerate info table local obj = infotable[i] local name = obj.name -------------------------------------------------------------------- if not uniqtable[name] then -- not found, start an entry uniqtable[name] = { decl = 0, token = 0, size = 0, } end -------------------------------------------------------------------- local uniq = uniqtable[name] -- count declarations, tokens, size uniq.decl = uniq.decl + 1 local xref = obj.xref local xcount = #xref uniq.token = uniq.token + xcount uniq.size = uniq.size + xcount * #name -------------------------------------------------------------------- if obj.decl then -- if local table, create first,last pairs obj.id = i obj.xcount = xcount if xcount > 1 then -- if ==1, means local never accessed obj.first = xref[2] obj.last = xref[xcount] end -------------------------------------------------------------------- else -- if global table, add a back ref uniq.id = i end -------------------------------------------------------------------- end--for return uniqtable end ---------------------------------------------------------------------- -- calculate actual symbol frequencies, in order to reduce entropy -- * this may help further reduce the size of compressed sources -- * note that since parsing optimizations is put before lexing -- optimizations, the frequency table is not exact! -- * yes, this will miss --keep block comments too... ---------------------------------------------------------------------- local function recalc_for_entropy(option) local byte = string.byte local char = string.char -- table of token classes to accept in calculating symbol frequency local ACCEPT = { TK_KEYWORD = true, TK_NAME = true, TK_NUMBER = true, TK_STRING = true, TK_LSTRING = true, } if not option["opt-comments"] then ACCEPT.TK_COMMENT = true ACCEPT.TK_LCOMMENT = true end -------------------------------------------------------------------- -- create a new table and remove any original locals by filtering -------------------------------------------------------------------- local filtered = {} for i = 1, #toklist do filtered[i] = seminfolist[i] end for i = 1, #localinfo do -- enumerate local info table local obj = localinfo[i] local xref = obj.xref for j = 1, obj.xcount do local p = xref[j] filtered[p] = "" -- remove locals end end -------------------------------------------------------------------- local freq = {} -- reset symbol frequency table for i = 0, 255 do freq[i] = 0 end for i = 1, #toklist do -- gather symbol frequency local tok, info = toklist[i], filtered[i] if ACCEPT[tok] then for j = 1, #info do local c = byte(info, j) freq[c] = freq[c] + 1 end end--if end--for -------------------------------------------------------------------- -- function to re-sort symbols according to actual frequencies -------------------------------------------------------------------- local function resort(symbols) local symlist = {} for i = 1, #symbols do -- prepare table to sort local c = byte(symbols, i) symlist[i] = { c = c, freq = freq[c], } end table.sort(symlist, -- sort selected symbols function(v1, v2) return v1.freq > v2.freq end ) local charlist = {} -- reconstitute the string for i = 1, #symlist do charlist[i] = char(symlist[i].c) end return table.concat(charlist) end -------------------------------------------------------------------- LETTERS = resort(LETTERS) -- change letter arrangement ALPHANUM = resort(ALPHANUM) end ---------------------------------------------------------------------- -- returns a string containing a new local variable name to use, and -- a flag indicating whether it collides with a global variable -- * trapping keywords and other names like 'self' is done elsewhere ---------------------------------------------------------------------- local function new_var_name() local var local cletters, calphanum = #LETTERS, #ALPHANUM local v = var_new if v < cletters then -- single char v = v + 1 var = string.sub(LETTERS, v, v) else -- longer names local range, sz = cletters, 1 -- calculate # chars fit repeat v = v - range range = range * calphanum sz = sz + 1 until range > v local n = v % cletters -- left side cycles faster v = (v - n) / cletters -- do first char first n = n + 1 var = string.sub(LETTERS, n, n) while sz > 1 do local m = v % calphanum v = (v - m) / calphanum m = m + 1 var = var..string.sub(ALPHANUM, m, m) sz = sz - 1 end end var_new = var_new + 1 return var, globaluniq[var] ~= nil end ---------------------------------------------------------------------- -- calculate and print some statistics -- * probably better in main source, put here for now ---------------------------------------------------------------------- local function stats_summary(globaluniq, localuniq, afteruniq, option) local print = print or base.print local fmt = string.format local opt_details = option.DETAILS local uniq_g , uniq_li, uniq_lo, uniq_ti, uniq_to, -- stats needed decl_g, decl_li, decl_lo, decl_ti, decl_to, token_g, token_li, token_lo, token_ti, token_to, size_g, size_li, size_lo, size_ti, size_to = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 local function avg(c, l) -- safe average function if c == 0 then return 0 end return l / c end -------------------------------------------------------------------- -- collect statistics (note: globals do not have declarations!) -------------------------------------------------------------------- for name, uniq in base.pairs(globaluniq) do uniq_g = uniq_g + 1 token_g = token_g + uniq.token size_g = size_g + uniq.size end for name, uniq in base.pairs(localuniq) do uniq_li = uniq_li + 1 decl_li = decl_li + uniq.decl token_li = token_li + uniq.token size_li = size_li + uniq.size end for name, uniq in base.pairs(afteruniq) do uniq_lo = uniq_lo + 1 decl_lo = decl_lo + uniq.decl token_lo = token_lo + uniq.token size_lo = size_lo + uniq.size end uniq_ti = uniq_g + uniq_li decl_ti = decl_g + decl_li token_ti = token_g + token_li size_ti = size_g + size_li uniq_to = uniq_g + uniq_lo decl_to = decl_g + decl_lo token_to = token_g + token_lo size_to = size_g + size_lo -------------------------------------------------------------------- -- detailed stats: global list -------------------------------------------------------------------- if opt_details then local sorted = {} -- sort table of unique global names by size for name, uniq in base.pairs(globaluniq) do uniq.name = name sorted[#sorted + 1] = uniq end table.sort(sorted, function(v1, v2) return v1.size > v2.size end ) local tabf1, tabf2 = "%8s%8s%10s %s", "%8d%8d%10.2f %s" local hl = string.rep("-", 44) print("*** global variable list (sorted by size) ***\n"..hl) print(fmt(tabf1, "Token", "Input", "Input", "Global")) print(fmt(tabf1, "Count", "Bytes", "Average", "Name")) print(hl) for i = 1, #sorted do local uniq = sorted[i] print(fmt(tabf2, uniq.token, uniq.size, avg(uniq.token, uniq.size), uniq.name)) end print(hl) print(fmt(tabf2, token_g, size_g, avg(token_g, size_g), "TOTAL")) print(hl.."\n") -------------------------------------------------------------------- -- detailed stats: local list -------------------------------------------------------------------- local tabf1, tabf2 = "%8s%8s%8s%10s%8s%10s %s", "%8d%8d%8d%10.2f%8d%10.2f %s" local hl = string.rep("-", 70) print("*** local variable list (sorted by allocation order) ***\n"..hl) print(fmt(tabf1, "Decl.", "Token", "Input", "Input", "Output", "Output", "Global")) print(fmt(tabf1, "Count", "Count", "Bytes", "Average", "Bytes", "Average", "Name")) print(hl) for i = 1, #varlist do -- iterate according to order assigned local name = varlist[i] local uniq = afteruniq[name] local old_t, old_s = 0, 0 for j = 1, #localinfo do -- find corresponding old names and calculate local obj = localinfo[j] if obj.name == name then old_t = old_t + obj.xcount old_s = old_s + obj.xcount * #obj.oldname end end print(fmt(tabf2, uniq.decl, uniq.token, old_s, avg(old_t, old_s), uniq.size, avg(uniq.token, uniq.size), name)) end print(hl) print(fmt(tabf2, decl_lo, token_lo, size_li, avg(token_li, size_li), size_lo, avg(token_lo, size_lo), "TOTAL")) print(hl.."\n") end--if opt_details -------------------------------------------------------------------- -- display output -------------------------------------------------------------------- local tabf1, tabf2 = "%-16s%8s%8s%8s%8s%10s", "%-16s%8d%8d%8d%8d%10.2f" local hl = string.rep("-", 58) print("*** local variable optimization summary ***\n"..hl) print(fmt(tabf1, "Variable", "Unique", "Decl.", "Token", "Size", "Average")) print(fmt(tabf1, "Types", "Names", "Count", "Count", "Bytes", "Bytes")) print(hl) print(fmt(tabf2, "Global", uniq_g, decl_g, token_g, size_g, avg(token_g, size_g))) print(hl) print(fmt(tabf2, "Local (in)", uniq_li, decl_li, token_li, size_li, avg(token_li, size_li))) print(fmt(tabf2, "TOTAL (in)", uniq_ti, decl_ti, token_ti, size_ti, avg(token_ti, size_ti))) print(hl) print(fmt(tabf2, "Local (out)", uniq_lo, decl_lo, token_lo, size_lo, avg(token_lo, size_lo))) print(fmt(tabf2, "TOTAL (out)", uniq_to, decl_to, token_to, size_to, avg(token_to, size_to))) print(hl.."\n") end ---------------------------------------------------------------------- -- main entry point -- * does only local variable optimization for now ---------------------------------------------------------------------- function optimize(option, _toklist, _seminfolist, _globalinfo, _localinfo) -- set tables toklist, seminfolist, globalinfo, localinfo = _toklist, _seminfolist, _globalinfo, _localinfo var_new = 0 -- reset variable name allocator varlist = {} ------------------------------------------------------------------ -- preprocess global/local tables, handle entropy reduction ------------------------------------------------------------------ globaluniq = preprocess(globalinfo) localuniq = preprocess(localinfo) if option["opt-entropy"] then -- for entropy improvement recalc_for_entropy(option) end ------------------------------------------------------------------ -- build initial declared object table, then sort according to -- token count, this might help assign more tokens to more common -- variable names such as 'e' thus possibly reducing entropy -- * an object knows its localinfo index via its 'id' field -- * special handling for "self" special local (parameter) here ------------------------------------------------------------------ local object = {} for i = 1, #localinfo do object[i] = localinfo[i] end table.sort(object, -- sort largest first function(v1, v2) return v1.xcount > v2.xcount end ) ------------------------------------------------------------------ -- the special "self" function parameters must be preserved -- * the allocator below will never use "self", so it is safe to -- keep those implicit declarations as-is ------------------------------------------------------------------ local temp, j, gotself = {}, 1, false for i = 1, #object do local obj = object[i] if not obj.isself then temp[j] = obj j = j + 1 else gotself = true end end object = temp ------------------------------------------------------------------ -- a simple first-come first-served heuristic name allocator, -- note that this is in no way optimal... -- * each object is a local variable declaration plus existence -- * the aim is to assign short names to as many tokens as possible, -- so the following tries to maximize name reuse -- * note that we preserve sort order ------------------------------------------------------------------ local nobject = #object while nobject > 0 do local varname, gcollide repeat varname, gcollide = new_var_name() -- collect a variable name until not SKIP_NAME[varname] -- skip all special names varlist[#varlist + 1] = varname -- keep a list local oleft = nobject ------------------------------------------------------------------ -- if variable name collides with an existing global, the name -- cannot be used by a local when the name is accessed as a global -- during which the local is alive (between 'act' to 'rem'), so -- we drop objects that collides with the corresponding global ------------------------------------------------------------------ if gcollide then -- find the xref table of the global local gref = globalinfo[globaluniq[varname].id].xref local ngref = #gref -- enumerate for all current objects; all are valid at this point for i = 1, nobject do local obj = object[i] local act, rem = obj.act, obj.rem -- 'live' range of local -- if rem < 0, it is a -id to a local that had the same name -- so follow rem to extend it; does this make sense? while rem < 0 do rem = localinfo[-rem].rem end local drop for j = 1, ngref do local p = gref[j] if p >= act and p <= rem then drop = true end -- in range? end if drop then obj.skip = true oleft = oleft - 1 end end--for end--if gcollide ------------------------------------------------------------------ -- now the first unassigned local (since it's sorted) will be the -- one with the most tokens to rename, so we set this one and then -- eliminate all others that collides, then any locals that left -- can then reuse the same variable name; this is repeated until -- all local declaration that can use this name is assigned -- * the criteria for local-local reuse/collision is: -- A is the local with a name already assigned -- B is the unassigned local under consideration -- => anytime A is accessed, it cannot be when B is 'live' -- => to speed up things, we have first/last accesses noted ------------------------------------------------------------------ while oleft > 0 do local i = 1 while object[i].skip do -- scan for first object i = i + 1 end ------------------------------------------------------------------ -- first object is free for assignment of the variable name -- [first,last] gives the access range for collision checking ------------------------------------------------------------------ oleft = oleft - 1 local obja = object[i] i = i + 1 obja.newname = varname obja.skip = true obja.done = true local first, last = obja.first, obja.last local xref = obja.xref ------------------------------------------------------------------ -- then, scan all the rest and drop those colliding -- if A was never accessed then it'll never collide with anything -- otherwise trivial skip if: -- * B was activated after A's last access (last < act) -- * B was removed before A's first access (first > rem) -- if not, see detailed skip below... ------------------------------------------------------------------ if first and oleft > 0 then -- must have at least 1 access local scanleft = oleft while scanleft > 0 do while object[i].skip do -- next valid object i = i + 1 end scanleft = scanleft - 1 local objb = object[i] i = i + 1 local act, rem = objb.act, objb.rem -- live range of B -- if rem < 0, extend range of rem thru' following local while rem < 0 do rem = localinfo[-rem].rem end -------------------------------------------------------- if not(last < act or first > rem) then -- possible collision -------------------------------------------------------- -- B is activated later than A or at the same statement, -- this means for no collision, A cannot be accessed when B -- is alive, since B overrides A (or is a peer) -------------------------------------------------------- if act >= obja.act then for j = 1, obja.xcount do -- ... then check every access local p = xref[j] if p >= act and p <= rem then -- A accessed when B live! oleft = oleft - 1 objb.skip = true break end end--for -------------------------------------------------------- -- A is activated later than B, this means for no collision, -- A's access is okay since it overrides B, but B's last -- access need to be earlier than A's activation time -------------------------------------------------------- else if objb.last and objb.last >= obja.act then oleft = oleft - 1 objb.skip = true end end end -------------------------------------------------------- if oleft == 0 then break end end end--if first ------------------------------------------------------------------ end--while ------------------------------------------------------------------ -- after assigning all possible locals to one variable name, the -- unassigned locals/objects have the skip field reset and the table -- is compacted, to hopefully reduce iteration time ------------------------------------------------------------------ local temp, j = {}, 1 for i = 1, nobject do local obj = object[i] if not obj.done then obj.skip = false temp[j] = obj j = j + 1 end end object = temp -- new compacted object table nobject = #object -- objects left to process ------------------------------------------------------------------ end--while ------------------------------------------------------------------ -- after assigning all locals with new variable names, we can -- patch in the new names, and reprocess to get 'after' stats ------------------------------------------------------------------ for i = 1, #localinfo do -- enumerate all locals local obj = localinfo[i] local xref = obj.xref if obj.newname then -- if got new name, patch it in for j = 1, obj.xcount do local p = xref[j] -- xrefs indexes the token list seminfolist[p] = obj.newname end obj.name, obj.oldname -- adjust names = obj.newname, obj.name else obj.oldname = obj.name -- for cases like 'self' end end ------------------------------------------------------------------ -- deal with statistics output ------------------------------------------------------------------ if gotself then -- add 'self' to end of list varlist[#varlist + 1] = "self" end local afteruniq = preprocess(localinfo) stats_summary(globaluniq, localuniq, afteruniq, option) ------------------------------------------------------------------ end
apache-2.0
Ninjistix/darkstar
scripts/globals/spells/poison_ii.lua
3
1555
----------------------------------------- -- Spell: Poison ----------------------------------------- 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) local effect = EFFECT_POISON; local duration = 120; if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then duration = duration * 2; end local pINT = caster:getStat(MOD_INT); local mINT = target:getStat(MOD_INT); local dINT = (pINT - mINT); local power = caster:getSkillLevel(ENFEEBLING_MAGIC_SKILL) / 20 + 1; if power > 10 then power = 10; end if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then power = power * 2; end caster:delStatusEffect(EFFECT_SABOTEUR); local params = {}; params.diff = nil; params.attribute = MOD_INT; params.skillType = ENFEEBLING_MAGIC_SKILL; params.bonus = 0; params.effect = effect; local resist = applyResistanceEffect(caster, target, spell, params); if (resist == 1 or resist == 0.5) then -- effect taken duration = duration * resist; if (target:addStatusEffect(effect,power,3,duration)) then spell:setMsg(msgBasic.MAGIC_ENFEEB_IS); else spell:setMsg(msgBasic.MAGIC_NO_EFFECT); end else -- resist entirely. spell:setMsg(msgBasic.MAGIC_RESIST); end return effect; end;
gpl-3.0
mt246/mt24679
plugins/exchange.lua
352
2076
local ltn12 = require "ltn12" local https = require "ssl.https" -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local function comma_value(n) -- credit http://richard.warburton.it local left,num,right = string.match(n,'^([^%d]*%d)(%d*)(.-)$') return left..(num:reverse():gsub('(%d%d%d)','%1,'):reverse())..right end local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local function request(value, from, to) local api = "https://currency-exchange.p.mashape.com/exchange?" local par1 = "from="..from local par2 = "&q="..value local par3 = "&to="..to local url = api..par1..par2..par3 local api_key = mashape.api_key if api_key:isempty() then return 'Configure your Mashape API Key' end local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "text/plain" } local respbody = {} local body, code = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return code end local body = table.concat(respbody) local curr = comma_value(value).." "..from.." = "..to.." "..comma_value(body) return curr end local function run(msg, matches) if tonumber(matches[1]) and not matches[2] then local from = "USD" local to = "IDR" local value = matches[1] return request(value, from, to) elseif matches[2] and matches[3] then local from = string.upper(matches[2]) or "USD" local to = string.upper(matches[3]) or "IDR" local value = matches[1] or "1" return request(value, from, to, value) end end return { description = "Currency Exchange", usage = { "!exchange [value] : Exchange value from USD to IDR (default).", "!exchange [value] [from] [to] : Get Currency Exchange by specifying the value of source (from) and destination (to).", }, patterns = { "^!exchange (%d+) (%a+) (%a+)$", "^!exchange (%d+)", }, run = run }
gpl-2.0
mamad-ali/xilibot
plugins/exchange.lua
352
2076
local ltn12 = require "ltn12" local https = require "ssl.https" -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local function comma_value(n) -- credit http://richard.warburton.it local left,num,right = string.match(n,'^([^%d]*%d)(%d*)(.-)$') return left..(num:reverse():gsub('(%d%d%d)','%1,'):reverse())..right end local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local function request(value, from, to) local api = "https://currency-exchange.p.mashape.com/exchange?" local par1 = "from="..from local par2 = "&q="..value local par3 = "&to="..to local url = api..par1..par2..par3 local api_key = mashape.api_key if api_key:isempty() then return 'Configure your Mashape API Key' end local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "text/plain" } local respbody = {} local body, code = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return code end local body = table.concat(respbody) local curr = comma_value(value).." "..from.." = "..to.." "..comma_value(body) return curr end local function run(msg, matches) if tonumber(matches[1]) and not matches[2] then local from = "USD" local to = "IDR" local value = matches[1] return request(value, from, to) elseif matches[2] and matches[3] then local from = string.upper(matches[2]) or "USD" local to = string.upper(matches[3]) or "IDR" local value = matches[1] or "1" return request(value, from, to, value) end end return { description = "Currency Exchange", usage = { "!exchange [value] : Exchange value from USD to IDR (default).", "!exchange [value] [from] [to] : Get Currency Exchange by specifying the value of source (from) and destination (to).", }, patterns = { "^!exchange (%d+) (%a+) (%a+)$", "^!exchange (%d+)", }, run = run }
gpl-2.0
disslove85/NOVA-BOT
plugins/anti_bot.lua
369
3064
local function isBotAllowed (userId, chatId) local hash = 'anti-bot:allowed:'..chatId..':'..userId local banned = redis:get(hash) return banned end local function allowBot (userId, chatId) local hash = 'anti-bot:allowed:'..chatId..':'..userId redis:set(hash, true) end local function disallowBot (userId, chatId) local hash = 'anti-bot:allowed:'..chatId..':'..userId redis:del(hash) end -- Is anti-bot enabled on chat local function isAntiBotEnabled (chatId) local hash = 'anti-bot:enabled:'..chatId local enabled = redis:get(hash) return enabled end local function enableAntiBot (chatId) local hash = 'anti-bot:enabled:'..chatId redis:set(hash, true) end local function disableAntiBot (chatId) local hash = 'anti-bot:enabled:'..chatId redis:del(hash) end local function isABot (user) -- Flag its a bot 0001000000000000 local binFlagIsBot = 4096 local result = bit32.band(user.flags, binFlagIsBot) return result == binFlagIsBot end local function kickUser(userId, chatId) local chat = 'chat#id'..chatId local user = 'user#id'..userId chat_del_user(chat, user, function (data, success, result) if success ~= 1 then print('I can\'t kick '..data.user..' but should be kicked') end end, {chat=chat, user=user}) end local function run (msg, matches) -- We wont return text if is a service msg if matches[1] ~= 'chat_add_user' and matches[1] ~= 'chat_add_user_link' then if msg.to.type ~= 'chat' then return 'Anti-flood works only on channels' end end local chatId = msg.to.id if matches[1] == 'enable' then enableAntiBot(chatId) return 'Anti-bot enabled on this chat' end if matches[1] == 'disable' then disableAntiBot(chatId) return 'Anti-bot disabled on this chat' end if matches[1] == 'allow' then local userId = matches[2] allowBot(userId, chatId) return 'Bot '..userId..' allowed' end if matches[1] == 'disallow' then local userId = matches[2] disallowBot(userId, chatId) return 'Bot '..userId..' disallowed' end if matches[1] == 'chat_add_user' or matches[1] == 'chat_add_user_link' then local user = msg.action.user or msg.from if isABot(user) then print('It\'s a bot!') if isAntiBotEnabled(chatId) then print('Anti bot is enabled') local userId = user.id if not isBotAllowed(userId, chatId) then kickUser(userId, chatId) else print('This bot is allowed') end end end end end return { description = 'When bot enters group kick it.', usage = { '!antibot enable: Enable Anti-bot on current chat', '!antibot disable: Disable Anti-bot on current chat', '!antibot allow <botId>: Allow <botId> on this chat', '!antibot disallow <botId>: Disallow <botId> on this chat' }, patterns = { '^!antibot (allow) (%d+)$', '^!antibot (disallow) (%d+)$', '^!antibot (enable)$', '^!antibot (disable)$', '^!!tgservice (chat_add_user)$', '^!!tgservice (chat_add_user_link)$' }, run = run }
gpl-2.0
RedeMinas/portal
main.lua
1
1941
--- Portal Institucional Rede Minas -- @author: Carlos Henrique G. Paulino -- @copyright: Aphero GPL - Fundação TV Minas Cultural e Educativa -- ginga - ncl / lua --- reads functions dofile("lib_main.lua") dofile("lib_icon.lua") dofile("lib_tables.lua") dofile("lib_menu.lua") m=MainMenu:new{} countMetric() --- deal with keys -- Some description, can be over several lines. -- @param evt first parameter -- @return nil function handler (evt) if (evt.class == 'key' and evt.type == 'press') then -- icon if (not MENUON and not PGMON) then if (evt.key == "ENTER") then MENUON = true coroutine.resume(comainIcon) m:iconDraw(m.icons) m:menuItem() -- realocate icon elseif (evt.key == "CURSOR_UP")then ICON.pos=shift(ICON.pos,1,4) elseif (evt.key == "CURSOR_DOWN") then ICON.pos=shift(ICON.pos,-1,4) elseif (evt.key == "CURSOR_LEFT") then ICON.pos=shift(ICON.pos,-1,4) elseif ( evt.key == "CURSOR_RIGHT") then ICON.pos=shift(ICON.pos,1,4) --- main menu end elseif (MENUON ==true and PGMON == false ) then m:input(evt) ---pgms elseif( MENUON and PGMON) then if ( evt.key=="EXIT") then PGMON = false m:iconDraw() m:menuItem() elseif (m.list[m.spos]["img"]==1) then --browse on agenda agenda:input(evt) elseif (m.list[m.spos]["img"]==2) then --browse on agenda af:input(evt) elseif (m.list[m.spos]["img"]==8) then --browse on harmonia countMetric("harmonia") harmonia:input(evt) elseif (m.list[m.spos]["img"]==13) then --browse on mulherese mse:input(evt) elseif (m.list[m.spos]["img"]==18) then --browse on ribalta ribalta:input(evt) end end elseif (evt.action == "start") then mainIconUpdate() end end event.register(handler)
agpl-3.0
eugenesan/openwrt-luci
applications/luci-firewall/luasrc/tools/firewall.lua
59
6016
--[[ LuCI - Lua Configuration Interface Copyright 2011-2012 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- module("luci.tools.firewall", package.seeall) local ut = require "luci.util" local ip = require "luci.ip" local nx = require "nixio" local translate, translatef = luci.i18n.translate, luci.i18n.translatef local function tr(...) return tostring(translate(...)) end function fmt_neg(x) if type(x) == "string" then local v, neg = x:gsub("^ *! *", "") if neg > 0 then return v, "%s " % tr("not") else return x, "" end end return x, "" end function fmt_mac(x) if x and #x > 0 then local m, n local l = { tr("MAC"), " " } for m in ut.imatch(x) do m, n = fmt_neg(m) l[#l+1] = "<var>%s%s</var>" %{ n, m } l[#l+1] = ", " end if #l > 1 then l[#l] = nil if #l > 3 then l[1] = tr("MACs") end return table.concat(l, "") end end end function fmt_port(x, d) if x and #x > 0 then local p, n local l = { tr("port"), " " } for p in ut.imatch(x) do p, n = fmt_neg(p) local a, b = p:match("(%d+)%D+(%d+)") if a and b then l[1] = tr("ports") l[#l+1] = "<var>%s%d-%d</var>" %{ n, a, b } else l[#l+1] = "<var>%s%d</var>" %{ n, p } end l[#l+1] = ", " end if #l > 1 then l[#l] = nil if #l > 3 then l[1] = tr("ports") end return table.concat(l, "") end end return d and "<var>%s</var>" % d end function fmt_ip(x, d) if x and #x > 0 then local l = { tr("IP"), " " } local v, a, n for v in ut.imatch(x) do v, n = fmt_neg(v) a, m = v:match("(%S+)/(%d+%.%S+)") a = a or v a = a:match(":") and ip.IPv6(a, m) or ip.IPv4(a, m) if a and (a:is6() and a:prefix() < 128 or a:prefix() < 32) then l[1] = tr("IP range") l[#l+1] = "<var title='%s - %s'>%s%s</var>" %{ a:minhost():string(), a:maxhost():string(), n, a:string() } else l[#l+1] = "<var>%s%s</var>" %{ n, a and a:string() or v } end l[#l+1] = ", " end if #l > 1 then l[#l] = nil if #l > 3 then l[1] = tr("IPs") end return table.concat(l, "") end end return d and "<var>%s</var>" % d end function fmt_zone(x, d) if x == "*" then return "<var>%s</var>" % tr("any zone") elseif x and #x > 0 then return "<var>%s</var>" % x elseif d then return "<var>%s</var>" % d end end function fmt_icmp_type(x) if x and #x > 0 then local t, v, n local l = { tr("type"), " " } for v in ut.imatch(x) do v, n = fmt_neg(v) l[#l+1] = "<var>%s%s</var>" %{ n, v } l[#l+1] = ", " end if #l > 1 then l[#l] = nil if #l > 3 then l[1] = tr("types") end return table.concat(l, "") end end end function fmt_proto(x, icmp_types) if x and #x > 0 then local v, n local l = { } local t = fmt_icmp_type(icmp_types) for v in ut.imatch(x) do v, n = fmt_neg(v) if v == "tcpudp" then l[#l+1] = "TCP" l[#l+1] = ", " l[#l+1] = "UDP" l[#l+1] = ", " elseif v ~= "all" then local p = nx.getproto(v) if p then -- ICMP if (p.proto == 1 or p.proto == 58) and t then l[#l+1] = translatef( "%s%s with %s", n, p.aliases[1] or p.name, t ) else l[#l+1] = "%s%s" %{ n, p.aliases[1] or p.name } end l[#l+1] = ", " end end end if #l > 0 then l[#l] = nil return table.concat(l, "") end end end function fmt_limit(limit, burst) burst = tonumber(burst) if limit and #limit > 0 then local l, u = limit:match("(%d+)/(%w+)") l = tonumber(l or limit) u = u or "second" if l then if u:match("^s") then u = tr("second") elseif u:match("^m") then u = tr("minute") elseif u:match("^h") then u = tr("hour") elseif u:match("^d") then u = tr("day") end if burst and burst > 0 then return translatef("<var>%d</var> pkts. per <var>%s</var>, \ burst <var>%d</var> pkts.", l, u, burst) else return translatef("<var>%d</var> pkts. per <var>%s</var>", l, u) end end end end function fmt_target(x, dest) if dest and #dest > 0 then if x == "ACCEPT" then return tr("Accept forward") elseif x == "REJECT" then return tr("Refuse forward") elseif x == "NOTRACK" then return tr("Do not track forward") else --if x == "DROP" then return tr("Discard forward") end else if x == "ACCEPT" then return tr("Accept input") elseif x == "REJECT" then return tr("Refuse input") elseif x == "NOTRACK" then return tr("Do not track input") else --if x == "DROP" then return tr("Discard input") end end end function opt_enabled(s, t, ...) if t == luci.cbi.Button then local o = s:option(t, "__enabled") function o.render(self, section) if self.map:get(section, "enabled") ~= "0" then self.title = tr("Rule is enabled") self.inputtitle = tr("Disable") self.inputstyle = "reset" else self.title = tr("Rule is disabled") self.inputtitle = tr("Enable") self.inputstyle = "apply" end t.render(self, section) end function o.write(self, section, value) if self.map:get(section, "enabled") ~= "0" then self.map:set(section, "enabled", "0") else self.map:del(section, "enabled") end end return o else local o = s:option(t, "enabled", ...) o.default = "1" return o end end function opt_name(s, t, ...) local o = s:option(t, "name", ...) function o.cfgvalue(self, section) return self.map:get(section, "name") or self.map:get(section, "_name") or "-" end function o.write(self, section, value) if value ~= "-" then self.map:set(section, "name", value) self.map:del(section, "_name") else self:remove(section) end end function o.remove(self, section) self.map:del(section, "name") self.map:del(section, "_name") end return o end
apache-2.0
Ninjistix/darkstar
scripts/globals/mobskills/gravitic_horn.lua
6
1626
--------------------------------------------------- -- Gravitic Horn -- Family: Antlion (Only used by Formiceros subspecies) -- Description: Heavy wind, Throat Stab-like damage in a fan-shaped area of effect. Resets enmity. -- Type: Magical -- Can be dispelled: N/A -- Utsusemi/Blink absorb: Ignores shadows -- Range: Conal AoE -- Notes: If Orcus uses this, it gains an aura which inflicts Weight & Defense Down to targets in range. -- Shell lowers the damage of this, and items like Jelly Ring can get you killed. --------------------------------------------------- require("scripts/globals/monstertpmoves"); require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); --------------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local currentHP = target:getHP(); -- remove all by 5% local damage = 0; -- estimation based on "Throat Stab-like damage" if (currentHP / target:getMaxHP() > 0.2) then baseDamage = currentHP * .95; else baseDamage = currentHP; end -- Because shell matters, but we don't want to calculate damage normally via MobMagicalMove since this is a % attack local damage = baseDamage * getElementalDamageReduction(target, ELE_WIND); -- we still need final adjustments to handle stoneskin etc though damage = MobFinalAdjustments(damage,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WIND,MOBPARAM_WIPE_SHADOWS); target:delHP(finalDamage); mob:resetEnmity(target); return finalDamage; end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Arrapago_Reef/npcs/Runic_Portal.lua
5
1428
----------------------------------- -- Area: Arrapago Reef -- NPC: Runic Portal -- Arrapago Reef Teleporter Back to Aht Urgan Whitegate -- !pos 15 -7 627 54 ----------------------------------- package.loaded["scripts/zones/Arrapago_Reef/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Arrapago_Reef/TextIDs"); require("scripts/globals/besieged"); require("scripts/globals/teleports"); require("scripts/globals/missions"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) if (player:getCurrentMission(TOAU) == IMMORTAL_SENTRIES and player:getVar("AhtUrganStatus") == 1) then player:startEvent(111); elseif (player:getCurrentMission(TOAU) > IMMORTAL_SENTRIES) then if (hasRunicPortal(player,5) == 1) then player:startEvent(109); else player:startEvent(111); end else player:messageSpecial(RESPONSE); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 111 and option == 1) then player:addNationTeleport(AHTURHGAN,32); toChamberOfPassage(player); elseif (csid == 109 and option == 1) then toChamberOfPassage(player); end end;
gpl-3.0
ehrenbrav/FCEUX_Learning_Environment
output/luaScripts/luabot_framework.lua
9
22517
-- LuaBot, concept bot for FCEU and snes9x and any other emu that has compatible Lua engine -- qFox, 2 August 2008 -- version 1.07 -- Botscript data following: -- Rom: -- ROMNAME -- Comment: -- COMMENT -- Version: -- VERSION local maxvalue = 100; -- always "true", yes, pressed local minvalue = 0; -- always "false", no, released -- the bot kind of works like this function. for every option, a value is requested from the programmer. -- if that value is higher then a random value 0-99, this function returns true, else false. -- the idea is that keys are pressed based on a heuristic value. if you want absolute values, simply -- return values like minvalue or maxvalue, or their syntactic equals yes/no and press/release (to make -- the sourcecode easier to read). you can use the variable maybe for 50% chance. -- this function also reduces a lot of calls to random() if the user uses absolute values. local function rand_if(n) if (n <= minvalue) then return false; end; if (n >= maxvalue) then return true; end; if (n > math.random(minvalue, maxvalue-1)) then return true; end; return false; end; local loopcounter = 0; -- counts the main loop local key1 = {}; -- holds the to be pressed keys this frame for player 1 local key2 = {}; -- holds the to be pressed keys this frame for player 2 local key3 = {}; -- holds the to be pressed keys this frame for player 3 local key4 = {}; -- holds the to be pressed keys this frame for player 4 local lastkey1 = {}; -- keys pressed in previous frame for player 1 local lastkey2 = {}; -- keys pressed in previous frame for player 2 local lastkey3 = {}; -- keys pressed in previous frame for player 1 local lastkey4 = {}; -- keys pressed in previous frame for player 2 local frame = 0; -- number of frames (current value is current frame count, incremented at the start of a new frame) local attempt = 1; -- number of attempts (current value is current attempt, incremented after the end of an attempt) local segment = 1; -- number of segments (current value is current segment, incremented after the end of a segment) local okattempts = 0; -- number of successfull attempts (including rollback) local failattempts = 0; -- number of failed attempts (including rollback) local segments = {}; -- table that holds every segment, each segment is another table that consists of the score, ties, savestate (begin of segment), lastkeys, keys pressed, etc. segments[1] = {}; -- initialize the first segment, we initialize the savestate right after the before code has ran -- these dont have to be used, but it makes it easier to control here local maxframes = 400; local maxattempts = 200; local maxsegments = 100; local playingbest = false; -- when going to the next segment, we need to play the best segment to record, this indicates when we're doing so local keyrecording1 = {}; -- every key pressed for player 1 is put in here local keyrecording2 = {}; -- every key pressed for player 2 is put in here local keyrecording3 = {}; -- every key pressed for player 3 is put in here local keyrecording4 = {}; -- every key pressed for player 4 is put in here -- some constants/macro's/whatever to make source easier to read local press = maxvalue; local release = minvalue; local yes = maxvalue; local maybe = maxvalue/2; -- 50% local no = minvalue; -- static constants, will be used by the frontend later local X = 95; local Y = 30; local Z = 0; local P = 0; local Q = 0; local vars = {}; -- variable table. each cell holds a variable. variables are remembered accross segments -- user defined functions local function getScore() -- score of current attempt local result = no; -- SCORE return result; end; local function getTie1() -- tie breaker of current attempt in case score is equal local result = no; -- TIE1 return result; end; local function getTie2() -- second tie breaker local result = no; -- TIE2 return result; end; local function getTie3() -- third tie breaker local result = no; -- TIE3 return result; end; local function getTie4() -- fourth tie breaker local result = no; -- TIE4 return result; end; local function isRunEnd() -- gets called 3x! twice in the main loop (every frame). determines whether the bot should quit. local result = no; -- ISRUNEND return result; end; local function mustRollBack() -- drop back to previous segment? called at the end of a segment local result = no; -- MUSTROLLBACK return result; end; local function isSegmentEnd() -- end of current segment? (usually just x frames or being really stuck (to rollback)) local result = no; -- ISSEGMENTEND return result; end; local function isAttemptOk() -- is current run ok? like, did you die? (then the run is NOT ok... :). return no for no and yes for yes or be left by chance. local result = yes; -- ISATTEMPTOK return result; end; local function isAttemptEnd() -- end of current attempt? (like when you die or reach a goal) local result = no; -- ISATTEMPTEND return result; end; -- the next 2x8 functions determine whether a button should be pressed for player 1 and 2 -- return yes or no for absolute values, return anything between minvalue and maxvalue -- to set a chance of pressing that button. local function pressKeyA1() local result = no; -- bA1 return result; end; local function pressKeyB1() local result = no; -- bB1 return result; end; local function pressKeyStart1() local result = no; -- START1 return result; end; local function pressKeySelect1() local result = no; -- SELECT1 return result; end; local function pressKeyUp1() local result = no; -- UP1 return result; end; local function pressKeyDown1() local result = no; -- DOWN1 return result; end; local function pressKeyLeft1() local result = no; -- LEFT1 return result; end; local function pressKeyRight1() local result = no; -- RIGHT1 return result; end; local function pressKeyA2() local result = no; -- bA2 return result; end; local function pressKeyB2() local result = no; -- bB2 return result; end; local function pressKeyStart2() local result = no; -- START2 return result; end; local function pressKeySelect2() local result = no; -- SELECT2 return result; end; local function pressKeyUp2() local result = no; -- UP2 return result; end; local function pressKeyDown2() local result = no; -- DOWN2 return result; end; local function pressKeyLeft2() local result = no; -- LEFT2 return result; end; local function pressKeyRight2() local result = no; -- RIGHT2 return result; end; local function pressKeyA3() local result = no; -- bA3 return result; end; local function pressKeyB3() local result = no; -- bB3 return result; end; local function pressKeyStart3() local result = no; -- START3 return result; end; local function pressKeySelect3() local result = no; -- SELECT3 return result; end; local function pressKeyUp3() local result = no; -- UP3 return result; end; local function pressKeyDown3() local result = no; -- DOWN3 return result; end; local function pressKeyLeft3() local result = no; -- LEFT3 return result; end; local function pressKeyRight3() local result = no; -- RIGHT3 return result; end; local function pressKeyA4() local result = no; -- bA4 return result; end; local function pressKeyB4() local result = no; -- bB4 return result; end; local function pressKeyStart4() local result = no; -- START4 return result; end; local function pressKeySelect4() local result = no; -- SELECT4 return result; end; local function pressKeyUp4() local result = no; -- UP4 return result; end; local function pressKeyDown4() local result = no; -- DOWN4 return result; end; local function pressKeyLeft4() local result = no; -- LEFT4 return result; end; local function pressKeyRight4() local result = no; -- RIGHT4 return result; end; -- now follow the "events", one for the start and end of a frame, attempt, segment and whole bot. none of them need to return anything local function onStart() -- this code should run before the bot starts, for instance to start the game from power on and get setup the game -- ONSTART end; local function onFinish() -- code ran after the bot finishes -- ONFINISH end; local function onSegmentStart() -- code ran after initializing a new segment, before onAttemptStart(). framecount is always one fewer then actual frame! -- ONSEGMENTSTART end; local function onSegmentEnd() -- code ran after a segment finishes, before cleanup of segment vars -- ONSEGMENTEND end; local function onAttemptStart() -- code ran after initalizing a new attempt, before onInputStart(). not ran when playing back. framecount is always one fewer then actual frame! -- ONATTEMPTSTART end; local function onAttemptEnd(wasOk) -- code ran after an attempt ends before cleanup code, argument is boolean true when attempt was ok, boolean false otherwise. not ran when playing back -- ONATTEMPTEND end; local function onInputStart() -- code ran prior to getting input (keys are empty). not ran when playing back -- ONINPUTSTART end; local function onInputEnd() -- code ran after getting input (lastkey are still valid) (last function before frame ends, you can still manipulate the input here!). not ran when playing back -- ONINPUTEND end; -- the bot starts here.. (nothing is added from the user from this point onwards) onStart(); -- run this code first segments[segment].savestate = savestate.create(); -- create anonymous savestate obj for start of first segment savestate.save(segments[segment].savestate); -- save current state to it, it will be reloaded at the start of each frame local startkey1 = key1; -- save the last key pressed in the onStart. serves as an anchor for the first segment local startkey2 = key2; local startkey3 = key3; -- save the last key pressed in the onStart. serves as an anchor for the first segment local startkey4 = key4; local startvars = vars; -- save the vars array (it might have been used by the onStart) lastkey1 = key1; -- to enter the loop... lastkey2 = key2; lastkey3 = key3; lastkey4 = key4; --FCEU.speedmode("maximum"); -- uncomment this line to make the bot run faster ("normal","turbo","maximum") onSegmentStart(); onAttemptStart(); collectgarbage(); -- just in case... -- This will loops for each frame, at the end of the while -- the frameadvance is called, causing it to advance while (rand_if(isRunEnd())) do loopcounter = loopcounter + 1; -- count the number of botloops --gui.text(200,10,loopcounter); -- print it on the right side if you want to see the number of total frames if (not playingbest and rand_if(isAttemptEnd())) then -- load save state, continue with next attempt (disabled when playing back best) -- record this attempt as the last attempt if (not segments[segment].prev) then segments[segment].prev = {}; end; segments[segment].prev.frames = frame; segments[segment].prev.attempt = attempt; segments[segment].prev.score = getScore(); segments[segment].prev.tie1 = getTie1(); segments[segment].prev.tie2 = getTie2(); segments[segment].prev.tie3 = getTie3(); segments[segment].prev.tie4 = getTie4(); segments[segment].prev.ok = rand_if(isAttemptOk()); -- this is the check whether this attempt was valid or not. if not, it cannot become the best attempt. -- update ok/failed attempt counters if (segments[segment].prev.ok) then okattempts = okattempts + 1; onAttemptEnd(true); else failattempts = failattempts + 1; onAttemptEnd(false); end; -- if this attempt was better then the previous one, replace it -- its a long IF, but all it checks (lazy eval) is whether the current -- score is better then the previous one, or if its equal and the tie1 -- is better then the previous tie1 or if the tie1 is equal to the prev -- etc... for all four ties. Only tie4 actually needs to be better, tie1 -- through tie3 can be equal as well, as long as the next tie breaks the -- same tie of the previous attempt :) if (segments[segment].prev.ok and (not segments[segment].best or (getScore() > segments[segment].best.score or (getScore() == segments[segment].best.score and (getTie1() > segments[segment].best.tie1 or (getTie1() == segments[segment].best.tie1 and (getTie1() > segments[segment].best.tie1 or (getTie1() == segments[segment].best.tie1 and (getTie1() > segments[segment].best.tie1 or (getTie1() == segments[segment].best.tie1 and getTie1() > segments[segment].best.tie1)))))))))) then -- previous attempt was better then current best (or no current best -- exists), so we (re)place it. if (not segments[segment].best) then segments[segment].best = {}; end; segments[segment].best.frames = segments[segment].prev.frames; segments[segment].best.attempt = segments[segment].prev.attempt; segments[segment].best.score = segments[segment].prev.score; segments[segment].best.tie1 = segments[segment].prev.tie1; segments[segment].best.tie2 = segments[segment].prev.tie2; segments[segment].best.tie3 = segments[segment].prev.tie3; segments[segment].best.tie4 = segments[segment].prev.tie4; segments[segment].best.keys1 = keyrecording1; -- backup the recorded keys segments[segment].best.keys2 = keyrecording2; -- backup the recorded keys player 2 segments[segment].best.keys3 = keyrecording3; -- backup the recorded keys segments[segment].best.keys4 = keyrecording4; -- backup the recorded keys player 2 segments[segment].best.lastkey1 = lastkey1; -- backup the lastkey segments[segment].best.lastkey2 = lastkey2; -- backup the lastkey segments[segment].best.lastkey3 = lastkey3; -- backup the lastkey segments[segment].best.lastkey4 = lastkey4; -- backup the lastkey segments[segment].best.vars = vars; -- backup the vars table end if (rand_if(isSegmentEnd())) then -- the current segment ends, replay the best attempt and continue from there onwards... onSegmentEnd(); if (rand_if(mustRollBack())) then -- rollback to previous segment gui.text(50,50,"Rolling back to segment "..(segment-1)); segments[segment] = nil; -- remove current segment data attempt = 0; -- will be incremented in a few lines to be 1 segment = segment - 1; segments[segment].best = nil; segments[segment].prev = nil; collectgarbage(); -- collect the removed segment please else playingbest = true; -- this will start playing back the best attempt in this frame end; end; -- reset vars attempt = attempt + 1; frame = 0; keyrecording1 = {}; -- reset the recordings :) keyrecording2 = {}; keyrecording3 = {}; keyrecording4 = {}; -- set lastkey to lastkey of previous segment (or start, if first segment) -- also set the vars table to the table of the previous segment if (segment == 1) then lastkey1 = startkey1; lastkey2 = startkey2; lastkey3 = startkey3; lastkey4 = startkey4; vars = startvars; else lastkey1 = segments[segment-1].best.lastkey1; lastkey2 = segments[segment-1].best.lastkey2; lastkey3 = segments[segment-1].best.lastkey3; lastkey4 = segments[segment-1].best.lastkey4; vars = segments[segment-1].best.vars; end; -- load the segment savestate to go back to the start of this segment if (segments[segment].savestate) then -- load segment savestate and try again :) savestate.load(segments[segment].savestate); else fceu.crash(); -- this crashes because fceu is a nil table :) as long as gui.popup() doesnt work... we're crashing because no save state exists..? it should never happen. end; if (rand_if(isRunEnd())) then break; end; -- if end of run, break out of main loop and run in end loop. if (not playingbest) then onAttemptStart(); end; -- only call this when not playing back best attempt. has decreased frame counter! end; -- continues with (new) attempt -- increase framecounter _after_ processing attempt-end frame = frame + 1; -- inrease the frame count (++frame?) if (playingbest and segments[segment].best) then -- press keys from memory (if there are any) gui.text(10,150,"frame "..frame.." of "..segments[segment].best.frames); if (frame >= segments[segment].best.frames) then -- end of playback, start new segment playingbest = false; lastkey1 = segments[segment].best.lastkey1; lastkey2 = segments[segment].best.lastkey2; lastkey3 = segments[segment].best.lastkey3; lastkey4 = segments[segment].best.lastkey4; vars = segments[segment].best.vars; segment = segment + 1; segments[segment] = {}; -- create a new savestate for the start of this segment segments[segment].savestate = savestate.create(); savestate.save(segments[segment].savestate); -- reset vars frame = 0; -- onSegmentStart and onAttemptStart expect this to be one fewer... attempt = 1; keyrecording1 = {}; -- reset recordings :) keyrecording2 = {}; keyrecording3 = {}; keyrecording4 = {}; -- after this, the next segment starts because playingbest is no longer true onSegmentStart(); onAttemptStart(); frame = 1; -- now set it to 1 else key1 = segments[segment].best.keys1[frame]; -- fill keys with that of the best attempt key2 = segments[segment].best.keys2[frame]; key3 = segments[segment].best.keys3[frame]; key4 = segments[segment].best.keys4[frame]; gui.text(10,10,"Playback best of segment "..segment.."\nFrame: "..frame); end; end; if (rand_if(isRunEnd())) then break; end; -- if end of run, break out of main loop -- note this is the middle, this is where an attempt or segment has ended if it would and started if it would! -- now comes the input part for this frame if (not playingbest) then -- when playing best, the keys have been filled above. -- press keys from bot gui.text(10,10,"Attempt: "..attempt.." / "..maxattempts.."\nFrame: "..frame.." / "..maxframes); if (segments[segment] and segments[segment].best and segments[segment].prev) then gui.text(10,30,"Last score: "..segments[segment].prev.score.." ok="..okattempts..", fail="..failattempts.."\nBest score: "..segments[segment].best.score); elseif (segments[segment] and segments[segment].prev) then gui.text(10,30,"Last score: "..segments[segment].prev.score.."\nBest score: none, fails="..failattempts); end; gui.text(10,50,"Segment: "..segment); key1 = {}; key2 = {}; key3 = {}; key4 = {}; onInputStart(); -- player 1 if (rand_if(pressKeyUp1()) ) then key1.up = 1; end; if (rand_if(pressKeyDown1())) then key1.down = 1; end; if (rand_if(pressKeyLeft1())) then key1.left = 1; end; if (rand_if(pressKeyRight1())) then key1.right = 1; end; if (rand_if(pressKeyA1())) then key1.A = 1; end; if (rand_if(pressKeyB1())) then key1.B = 1; end; if (rand_if(pressKeySelect1())) then key1.select = 1; end; if (rand_if(pressKeyStart1())) then key1.start = 1; end; -- player 2 if (rand_if(pressKeyUp2()) ) then key2.up = 1; end; if (rand_if(pressKeyDown2())) then key2.down = 1; end; if (rand_if(pressKeyLeft2())) then key2.left = 1; end; if (rand_if(pressKeyRight2())) then key2.right = 1; end; if (rand_if(pressKeyA2())) then key2.A = 1; end; if (rand_if(pressKeyB2())) then key2.B = 1; end; if (rand_if(pressKeySelect2())) then key2.select = 1; end; if (rand_if(pressKeyStart2())) then key2.start = 1; end; -- player 3 if (rand_if(pressKeyUp3()) ) then key3.up = 1; end; if (rand_if(pressKeyDown3())) then key3.down = 1; end; if (rand_if(pressKeyLeft3())) then key3.left = 1; end; if (rand_if(pressKeyRight3())) then key3.right = 1; end; if (rand_if(pressKeyA3())) then key3.A = 1; end; if (rand_if(pressKeyB3())) then key3.B = 1; end; if (rand_if(pressKeySelect3())) then key3.select = 1; end; if (rand_if(pressKeyStart3())) then key3.start = 1; end; -- player 2 if (rand_if(pressKeyUp4()) ) then key4.up = 1; end; if (rand_if(pressKeyDown4())) then key4.down = 1; end; if (rand_if(pressKeyLeft4())) then key4.left = 1; end; if (rand_if(pressKeyRight4())) then key4.right = 1; end; if (rand_if(pressKeyA4())) then key4.A = 1; end; if (rand_if(pressKeyB4())) then key4.B = 1; end; if (rand_if(pressKeySelect4())) then key4.select = 1; end; if (rand_if(pressKeyStart4())) then key4.start = 1; end; onInputEnd(); lastkey1 = key1; lastkey2 = key2; lastkey3 = key3; lastkey4 = key4; keyrecording1[frame] = key1; -- record these keys keyrecording2[frame] = key2; -- record these keys keyrecording3[frame] = key3; -- record these keys keyrecording4[frame] = key4; -- record these keys end; -- actually set the keys here. joypad.set(1, key1); joypad.set(2, key2); joypad.set(3, key3); joypad.set(4, key4); -- next frame FCEU.frameadvance(); end; onFinish(); -- allow user cleanup before starting the final botloop -- now enter an endless loop displaying the results of this run. while (true) do if (segments[segment].best) then gui.text(30,100,"end: max attempt ["..segment.."] had score = "..segments[segment].best.score); elseif (segment > 1 and segments[segment-1].best) then gui.text(30,100,"end: no best attempt ["..segment.."]\nPrevious best score: "..segments[segment-1].best.score); else gui.text(30,100,"end: no best attempt ["..segment.."] ..."); end; FCEU.frameadvance(); end; -- i dont think it ever reaches this place... perhaps it should, or some event or whatever... segments = nil; collectgarbage(); -- collect the segment data... anything else is probably not worth it...
gpl-2.0