content
stringlengths 5
1.05M
|
|---|
toolchain("arm-himix100-linux")
set_kind("standalone")
set_sdkdir("/opt/hisi-linux/x86-arm/arm-himix100-linux")
set_bindir("/opt/hisi-linux/x86-arm/arm-himix100-linux/bin")
toolchain_end()
|
local telescope = require('telescope')
telescope.setup {
defaults = {
vimgrep_arguments = {
"rg",
"--ignore"
"--color=never",
"--no-heading",
"--with-filename",
"--line-number",
"--column",
"--smart-case"
},
prompt_position = "bottom",
prompt_prefix = "> ",
selection_caret = "> ",
entry_prefix = " ",
initial_mode = "insert",
selection_strategy = "reset",
sorting_strategy = "descending",
layout_strategy = "horizontal",
layout_defaults = {
horizontal = {
mirror = false,
preview_width = 0.5
},
vertical = {
mirror = false
}
},
file_sorter = require "telescope.sorters".get_fuzzy_file,
file_ignore_patterns = { "node_modules" },
generic_sorter = require "telescope.sorters".get_generic_fuzzy_sorter,
shorten_path = true,
winblend = 0,
width = 0.75,
preview_cutoff = 120,
results_height = 1,
results_width = 0.8,
border = {},
borderchars = {"─", "│", "─", "│", "╭", "╮", "╯", "╰"},
color_devicons = true,
use_less = true,
set_env = {["COLORTERM"] = "truecolor"},
file_previewer = require "telescope.previewers".vim_buffer_cat.new,
grep_previewer = require "telescope.previewers".vim_buffer_vimgrep.new,
qflist_previewer = require "telescope.previewers".vim_buffer_qflist.new,
buffer_previewer_maker = require "telescope.previewers".buffer_previewer_maker
}
}
|
vim.opt.termguicolors = true
vim.g.encoding = "UTF-8"
vim.o.fileencoding = 'utf-8'
vim.o.encoding = "utf-8"
vim.wo.number = true
vim.wo.relativenumber = true
vim.wo.cursorline = true
vim.wo.signcolumn = "yes"
-- 缩进2个空格等于一个Tab
vim.o.tabstop = 4
vim.bo.tabstop = 4
vim.o.softtabstop = 4
vim.o.shiftround = true
-- >> << 时移动长度
vim.o.shiftwidth = 4
vim.bo.shiftwidth = 4
-- 新行对齐当前行,空格替代tab
vim.o.expandtab = true
vim.bo.expandtab = true
vim.o.autoindent = true
vim.bo.autoindent = true
vim.o.smartindent = true
-- 搜索大小写不敏感,除非包含大写
vim.o.ignorecase = true
vim.o.smartcase = true
-- 搜索高亮
vim.o.hlsearch = true
-- 边输入边搜索
vim.o.incsearch = true
-- 使用增强状态栏后不再需要 vim 的模式提示
vim.o.showmode = false
vim.o.showcmd = true
-- 是否开启代码折叠
vim.o.foldenable = true
-- 指定代码折叠的策略是按照缩进进行的
vim.o.foldmethod = "indent"
-- 指定代码折叠的最高层级为 100
vim.o.foldlevel = 100
-- 命令行高为2,提供足够的显示空间
vim.o.cmdheight = 1
-- 当文件被外部程序修改时,自动加载
vim.o.autoread = true
vim.bo.autoread = true
-- 禁止折行
vim.o.wrap = false
vim.wo.wrap = false
-- 行结尾可以跳到下一行
vim.o.whichwrap = 'b,s,<,>,[,],h,l'
-- 允许隐藏被修改过的buffer
vim.o.hidden = true
-- 鼠标支持
vim.o.mouse = "a"
-- 禁止创建备份文件
vim.o.backup = false
vim.o.writebackup = false
vim.o.swapfile = false
-- smaller updatetime
vim.o.updatetime = 300
-- 等待mappings
vim.o.timeoutlen = 500
-- split window 从下边和右边出现
vim.o.splitbelow = true
vim.o.splitright = true
-- 自动补全不自动选中
vim.g.completeopt = "menu,menuone,noselect,noinsert"
-- 不可见字符的显示,这里只把空格显示为一个点
-- vim.o.list = true
vim.o.listchars = "space:·"
-- 补全增强
vim.o.wildmenu = true
-- Dont' pass messages to |ins-completin menu|
vim.o.shortmess = vim.o.shortmess .. 'Sc'
vim.o.pumheight = 10
-- always show tabline
vim.o.showtabline = 2
vim.g.asyncrun_open = 10
vim.g.asynctasks_term_pos = "tab"
vim.g.asynctasks_extra_config = {"~/.config/nvim/AsyncTasks.ini"}
|
for i, v in string.gmatch('odoasndoqew', 'o') do
print(i, v)
end
print('----')
for each in string.gmatch('odoasndoqew', '[oa]') do
print(each)
end
print('----')
for each in string.gmatch('odoasndoqew', '[oa]?') do
print(each)
end
print('----')
for each in string.gmatch('(abc),(def),ghui,()', ',?%(([^()]*)%)') do
print(each)
end
print('----')
for each in string.gmatch('(abc),(d(wqc)ef),ghui,()', ',?%(([^()]*)%)') do
print(each)
end
print('----')
for each in string.gmatch('%%(abc)%%,%%(d(wqc)ef)%%,%%ghui%%,%%()%%', '%%%((.*)%)%%') do
print(each)
end
print('----')
for each in string.gmatch('%%(abc)%%,%%(d(wqc)ef)%%,%%ghui%%,%%()%%,%%%%', '%%%((.-)%)%%') do
print(each)
end
print('----')
-- https://www.cnblogs.com/xdao/p/lua_pattern.html
for each in string.gmatch('(abc),(d(wqc)ef),ghui,()', ',?(%b())') do
print(each)
end
print('----')
--for each in string.gmatch('((abc)),((d(wqc)ef)),ghui,(())', ',?(%b(()))') do
-- print(each)
--end
--print('----')
|
require "gui/flag_editor"
local toggles = require "gui/toggles"
local list = iup.list{visiblecolumns = 8, visiblelines = 15, expand = "VERTICAL"}
local vertices, triangles, materials, ClearFields, active_pos
local v = {}
for i = 1, 3 do
v[i] = {
x = iup.text{visiblecolumns = 6, readonly = "YES"},
y = iup.text{visiblecolumns = 6, readonly = "YES"},
z = iup.text{visiblecolumns = 6, readonly = "YES"},
}
end
local function l(text)
return iup.label{title = text}
end
local grid = iup.gridbox{
l"Vertex A ", l"X", v[1].x, l"Y", v[1].y, l"Z", v[1].z,
l"Vertex B ", l"X", v[2].x, l"Y", v[2].y, l"Z", v[2].z,
l"Vertex C ", l"X", v[3].x, l"Y", v[3].y, l"Z", v[3].z,
numdiv = 7, orientation = "HORIZONTAL", homogeneouslin = "YES",
gapcol = 10, gaplin = 8, alignmentlin = "ACENTER", sizelin = 0
}
local mat_field = iup.text{visiblecolumns = 16, readonly = "YES"}
local flag_field = iup.text{visiblecolumns = 16, mask = iup.MASK_UINT}
local grid2 = iup.gridbox{
l"Material", mat_field,
l"Flag", flag_field,
numdiv = 2, orientation = "HORIZONTAL", homogeneouslin = "YES",
gapcol = 10, gaplin = 8, alignmentlin = "ACENTER", sizelin = 0
}
local tog
local function SaveFlag()
local n = tonumber(flag_field.value) or 0
if triangles and active_pos then
if triangles.binary then
util.SetTriangleFlag(triangles, active_pos - 1, n)
else
triangles[active_pos].flag = n
end
end
end
local function SetFlag()
flag_field.value = tog:GetBinaryValue()
SaveFlag()
end
tog = toggles.new(SetFlag)
function flag_field:valuechanged_cb()
local n = tonumber(self.value) or 0
tog:SetBinaryValue(n)
SaveFlag()
end
l = nil
local function ReadBinaryVertex(pos, i)
local x, y, z = util.GetVertex(vertices, pos)
v[i].x.value = string.format("%.3f", x)
v[i].y.value = string.format("%.3f", y)
v[i].z.value = string.format("%.3f", z)
end
local function ReadVertex(vert, i)
v[i].x.value = string.format("%.3f", vert.x)
v[i].y.value = string.format("%.3f", vert.y)
v[i].z.value = string.format("%.3f", vert.z)
end
function list:action(str, pos, state)
if state == 1 and triangles and vertices and materials then
active_pos = pos
local v1, v2, v3, mat, flag
if triangles.binary then
v1, v2, v3, mat, flag = util.GetTriangle(triangles, pos - 1)
else
local tri = triangles[pos]
v1 = tri[1]
v2 = tri[2]
v3 = tri[3]
mat = tri.material
flag = tri.flag
end
if mat >= 0 then
mat = materials[mat + 1]
mat_field.value = mat.name
else
mat_field.value = "<none>"
end
flag_field.value = flag
tog:SetBinaryValue(flag)
if vertices.binary then
ReadBinaryVertex(v1, 1)
ReadBinaryVertex(v2, 2)
ReadBinaryVertex(v3, 3)
else
ReadVertex(vertices[v1 + 1], 1)
ReadVertex(vertices[v2 + 1], 2)
ReadVertex(vertices[v3 + 1], 3)
end
end
end
local loaded
local function read(ter_data)
loaded = false
active_pos = nil
ClearFields()
triangles = ter_data.triangles
vertices = ter_data.vertices
materials = ter_data.materials
end
local function load()
if not loaded and triangles then
ft = io.open(zone_name .. "_triangles.txt", 'w')
loaded = true
local count = triangles.binary and triangles.count or #triangles
local progress = iup.progressdlg{count = 0, totalcount = count, description = "Loading Triangle data..."}
progress:show()
list.autoredraw = "NO"
list[1] = nil
for i = 1, count do
list[i] = i
progress.inc = 1
local v1, v2, v3, mat, flag
if triangles.binary then
v1, v2, v3, mat, flag = util.GetTriangle(triangles, i - 1)
else
local tri = triangles[i]
v1 = tri[1]
v2 = tri[2]
v3 = tri[3]
mat = tri.material
flag = tri.flag
end
mat = materials[mat + 1]
matName = "NONE"
if mat then
matName = mat.name
end
local x,y,z = 0
if vertices.binary then
x,y,z = util.GetVertex(vertices, v1)
else
x = string.format("%.3f", vertices[v1 + 1].x)
y = string.format("%.3f", vertices[v1 + 1].y)
z = string.format("%.3f", vertices[v1 + 1].z)
end
ft:write(i .. " " .. matName .. " " .. flag .. " " .. string.format("%.3f", x) .. " " .. string.format("%.3f", y) .. " " .. string.format("%.3f", z) .. "\n")
ft:flush()
end
list.autoredraw = "YES"
progress:hide()
ft:close()
iup.Destroy(progress)
end
end
function ClearFields()
for i, f in ipairs(v) do
f.x.value = ""
f.y.value = ""
f.z.value = ""
end
mat_field.value = ""
flag_field.value = ""
tog:Clear()
end
local flag_editor_button = iup.button{title = "Flag Editor", padding = "10x0",
action = function()
if triangles and materials then
StartFlagEditor(triangles, materials)
end
end,
}
return {
name = "Triangles",
display = iup.hbox{list, iup.vbox{
grid, grid2, iup.hbox{
tog.grid, flag_editor_button; gap = 30, alignment = "ACENTER",
}; gap = 20};
nmargin = "10x10", gap = 10},
read = read,
load = load,
}
|
-- Kong runloop
--
-- This consists of local_events that need to
-- be ran at the very beginning and very end of the lua-nginx-module contexts.
-- It mainly carries information related to a request from one context to the next one,
-- through the `ngx.ctx` table.
--
-- In the `access_by_lua` phase, it is responsible for retrieving the route being proxied by
-- a consumer. Then it is responsible for loading the plugins to execute on this request.
local ck = require "resty.cookie"
local meta = require "kong.meta"
local utils = require "kong.tools.utils"
local Router = require "kong.router"
local reports = require "kong.reports"
local balancer = require "kong.runloop.balancer"
local mesh = require "kong.runloop.mesh"
local constants = require "kong.constants"
local semaphore = require "ngx.semaphore"
local singletons = require "kong.singletons"
local certificate = require "kong.runloop.certificate"
local kong = kong
local tostring = tostring
local tonumber = tonumber
local sub = string.sub
local lower = string.lower
local fmt = string.format
local sort = table.sort
local ngx = ngx
local log = ngx.log
local ngx_now = ngx.now
local update_time = ngx.update_time
local subsystem = ngx.config.subsystem
local unpack = unpack
local ERR = ngx.ERR
local WARN = ngx.WARN
local DEBUG = ngx.DEBUG
local CACHE_ROUTER_OPTS = { ttl = 0 }
local EMPTY_T = {}
local get_router, build_router
local server_header = meta._SERVER_TOKENS
local _set_check_router_rebuild
local build_router_semaphore
local function get_now()
update_time()
return ngx_now() * 1000 -- time is kept in seconds with millisecond resolution.
end
do
-- Given a protocol, return the subsystem that handles it
local protocol_subsystem = {
http = "http",
https = "http",
tcp = "stream",
tls = "stream",
}
local router
local router_version
build_router = function(db, version)
local routes, i = {}, 0
for route, err in db.routes:each(1000) do
if err then
return nil, "could not load routes: " .. err
end
local service_pk = route.service
if not service_pk then
return nil, "route (" .. route.id .. ") is not associated with service"
end
local service, err = db.services:select(service_pk)
if not service then
return nil, "could not find service for route (" .. route.id .. "): " ..
err
end
local stype = protocol_subsystem[service.protocol]
if subsystem == stype then
local r = {
route = route,
service = service,
}
if stype == "http" and route.hosts then
-- TODO: headers should probably be moved to route
r.headers = {
host = route.hosts,
}
end
i = i + 1
routes[i] = r
end
end
sort(routes, function(r1, r2)
r1, r2 = r1.route, r2.route
if r1.regex_priority == r2.regex_priority then
return r1.created_at < r2.created_at
end
return r1.regex_priority > r2.regex_priority
end)
local err
router, err = Router.new(routes)
if not router then
return nil, "could not create router: " .. err
end
if version then
router_version = version
end
singletons.router = router
return true
end
local function check_router_rebuild()
-- we might not need to rebuild the router (if we were not
-- the first request in this process to enter this code path)
-- check again and rebuild only if necessary
local version, err = singletons.cache:get("router:version",
CACHE_ROUTER_OPTS,
utils.uuid)
if err then
log(ngx.CRIT, "could not ensure router is up to date: ", err)
return nil, err
end
if version == router_version then
return true
end
-- router needs to be rebuilt in this worker
log(DEBUG, "rebuilding router")
local ok, err = build_router(singletons.db, version)
if not ok then
log(ngx.CRIT, "could not rebuild router: ", err)
return nil, err
end
return true
end
-- for unit-testing purposes only
_set_check_router_rebuild = function(f)
check_router_rebuild = f
end
get_router = function()
local version, err = singletons.cache:get("router:version",
CACHE_ROUTER_OPTS,
utils.uuid)
if err then
log(ngx.CRIT, "could not ensure router is up to date: ", err)
return nil, err
end
if version == router_version then
return router
end
-- wrap router rebuilds in a per-worker mutex (via ngx.semaphore)
-- this prevents dogpiling the database during rebuilds in
-- high-concurrency traffic patterns
-- requests that arrive on this process during a router rebuild will be
-- queued. once the semaphore resource is acquired we re-check the
-- router version again to prevent unnecessary subsequent rebuilds
local timeout = 60
if singletons.configuration.database == "cassandra" then
-- cassandra_timeout is defined in ms
timeout = singletons.configuration.cassandra_timeout / 1000
elseif singletons.configuration.database == "postgres" then
-- pg_timeout is defined in ms
timeout = singletons.configuration.pg_timeout / 1000
end
-- acquire lock
local lok, err = build_router_semaphore:wait(timeout)
if not lok then
if err ~= "timeout" then
return nil, "error attempting to acquire build_router lock: " .. err
end
log(WARN, "bypassing build_router lock: timeout")
end
local pok, ok, err = pcall(check_router_rebuild)
if lok then
-- release lock
build_router_semaphore:post(1)
end
if not pok then
return nil, ok
end
if not ok then
return nil, err
end
return router
end
end
local function balancer_setup_stage1(ctx, scheme, host_type, host, port,
service, route)
local balancer_data = {
scheme = scheme, -- scheme for balancer: http, https
type = host_type, -- type of 'host': ipv4, ipv6, name
host = host, -- target host per `upstream_url`
port = port, -- final target port
try_count = 0, -- retry counter
tries = {}, -- stores info per try
ssl_ctx = kong.default_client_ssl_ctx, -- SSL_CTX* to use
-- ip = nil, -- final target IP address
-- balancer = nil, -- the balancer object, if any
-- hostname = nil, -- hostname of the final target IP
-- hash_cookie = nil, -- if Upstream sets hash_on_cookie
}
-- TODO: this is probably not optimal
do
local retries = service.retries
if retries then
balancer_data.retries = retries
else
balancer_data.retries = 5
end
local connect_timeout = service.connect_timeout
if connect_timeout then
balancer_data.connect_timeout = connect_timeout
else
balancer_data.connect_timeout = 60000
end
local send_timeout = service.write_timeout
if send_timeout then
balancer_data.send_timeout = send_timeout
else
balancer_data.send_timeout = 60000
end
local read_timeout = service.read_timeout
if read_timeout then
balancer_data.read_timeout = read_timeout
else
balancer_data.read_timeout = 60000
end
end
ctx.service = service
ctx.route = route
ctx.balancer_data = balancer_data
ctx.balancer_address = balancer_data -- for plugin backward compatibility
end
local function balancer_setup_stage2(ctx)
local balancer_data = ctx.balancer_data
do -- Check for KONG_ORIGINS override
local origin_key = balancer_data.scheme .. "://" ..
utils.format_host(balancer_data)
local origin = singletons.origins[origin_key]
if origin then
balancer_data.scheme = origin.scheme
balancer_data.type = origin.type
balancer_data.host = origin.host
balancer_data.port = origin.port
end
end
local ok, err, errcode = balancer.execute(balancer_data, ctx)
if not ok and errcode == 500 then
err = "failed the initial dns/balancer resolve for '" ..
balancer_data.host .. "' with: " .. tostring(err)
end
return ok, err, errcode
end
-- in the table below the `before` and `after` is to indicate when they run:
-- before or after the plugins
return {
build_router = build_router,
-- exported for unit-testing purposes only
_set_check_router_rebuild = _set_check_router_rebuild,
init_worker = {
before = function()
reports.init_worker()
-- initialize local local_events hooks
local db = singletons.db
local cache = singletons.cache
local worker_events = singletons.worker_events
local cluster_events = singletons.cluster_events
-- events dispatcher
worker_events.register(function(data)
if not data.schema then
log(ngx.ERR, "[events] missing schema in crud subscriber")
return
end
if not data.entity then
log(ngx.ERR, "[events] missing entity in crud subscriber")
return
end
-- invalidate this entity anywhere it is cached if it has a
-- caching key
local cache_key = db[data.schema.name]:cache_key(data.entity)
if cache_key then
cache:invalidate(cache_key)
end
-- if we had an update, but the cache key was part of what was updated,
-- we need to invalidate the previous entity as well
if data.old_entity then
cache_key = db[data.schema.name]:cache_key(data.old_entity)
if cache_key then
cache:invalidate(cache_key)
end
end
if not data.operation then
log(ngx.ERR, "[events] missing operation in crud subscriber")
return
end
-- public worker events propagation
local entity_channel = data.schema.table or data.schema.name
local entity_operation_channel = fmt("%s:%s", entity_channel,
data.operation)
-- crud:routes
local _, err = worker_events.post_local("crud", entity_channel, data)
if err then
log(ngx.ERR, "[events] could not broadcast crud event: ", err)
return
end
-- crud:routes:create
_, err = worker_events.post_local("crud", entity_operation_channel, data)
if err then
log(ngx.ERR, "[events] could not broadcast crud event: ", err)
return
end
end, "dao:crud")
-- local events (same worker)
worker_events.register(function()
log(DEBUG, "[events] Route updated, invalidating router")
cache:invalidate("router:version")
end, "crud", "routes")
worker_events.register(function(data)
if data.operation ~= "create" and
data.operation ~= "delete"
then
-- no need to rebuild the router if we just added a Service
-- since no Route is pointing to that Service yet.
-- ditto for deletion: if a Service if being deleted, it is
-- only allowed because no Route is pointing to it anymore.
log(DEBUG, "[events] Service updated, invalidating router")
cache:invalidate("router:version")
end
end, "crud", "services")
worker_events.register(function(data)
log(DEBUG, "[events] Plugin updated, invalidating plugins map")
cache:invalidate("plugins_map:version")
end, "crud", "plugins")
-- SSL certs / SNIs invalidations
worker_events.register(function(data)
log(DEBUG, "[events] SNI updated, invalidating cached certificates")
local sn = data.entity
cache:invalidate("certificates:" .. sn.name)
end, "crud", "snis")
worker_events.register(function(data)
log(DEBUG, "[events] SSL cert updated, invalidating cached certificates")
local certificate = data.entity
for sn, err in db.snis:each_for_certificate({ id = certificate.id }, 1000) do
if err then
log(ERR, "[events] could not find associated snis for certificate: ",
err)
break
end
cache:invalidate("certificates:" .. sn.name)
end
end, "crud", "certificates")
-- target updates
-- worker_events local handler: event received from DAO
worker_events.register(function(data)
local operation = data.operation
local target = data.entity
-- => to worker_events node handler
local ok, err = worker_events.post("balancer", "targets", {
operation = data.operation,
entity = data.entity,
})
if not ok then
log(ERR, "failed broadcasting target ",
operation, " to workers: ", err)
end
-- => to cluster_events handler
local key = fmt("%s:%s", operation, target.upstream.id)
ok, err = cluster_events:broadcast("balancer:targets", key)
if not ok then
log(ERR, "failed broadcasting target ", operation, " to cluster: ", err)
end
end, "crud", "targets")
-- worker_events node handler
worker_events.register(function(data)
local operation = data.operation
local target = data.entity
-- => to balancer update
balancer.on_target_event(operation, target)
end, "balancer", "targets")
-- cluster_events handler
cluster_events:subscribe("balancer:targets", function(data)
local operation, key = unpack(utils.split(data, ":"))
-- => to worker_events node handler
local ok, err = worker_events.post("balancer", "targets", {
operation = operation,
entity = {
upstream = { id = key },
}
})
if not ok then
log(ERR, "failed broadcasting target ", operation, " to workers: ", err)
end
end)
-- manual health updates
cluster_events:subscribe("balancer:post_health", function(data)
local pattern = "([^|]+)|([^|]+)|([^|]+)|([^|]+)|(.*)"
local ip, port, health, id, name = data:match(pattern)
port = tonumber(port)
local upstream = { id = id, name = name }
local ok, err = balancer.post_health(upstream, ip, port, health == "1")
if not ok then
log(ERR, "failed posting health of ", name, " to workers: ", err)
end
end)
-- upstream updates
-- worker_events local handler: event received from DAO
worker_events.register(function(data)
local operation = data.operation
local upstream = data.entity
-- => to worker_events node handler
local ok, err = worker_events.post("balancer", "upstreams", {
operation = data.operation,
entity = data.entity,
})
if not ok then
log(ERR, "failed broadcasting upstream ",
operation, " to workers: ", err)
end
-- => to cluster_events handler
local key = fmt("%s:%s:%s", operation, upstream.id, upstream.name)
ok, err = cluster_events:broadcast("balancer:upstreams", key)
if not ok then
log(ERR, "failed broadcasting upstream ", operation, " to cluster: ", err)
end
end, "crud", "upstreams")
-- worker_events node handler
worker_events.register(function(data)
local operation = data.operation
local upstream = data.entity
-- => to balancer update
balancer.on_upstream_event(operation, upstream)
end, "balancer", "upstreams")
cluster_events:subscribe("balancer:upstreams", function(data)
local operation, id, name = unpack(utils.split(data, ":"))
-- => to worker_events node handler
local ok, err = worker_events.post("balancer", "upstreams", {
operation = operation,
entity = {
id = id,
name = name,
}
})
if not ok then
log(ERR, "failed broadcasting upstream ", operation, " to workers: ", err)
end
end)
-- initialize balancers for active healthchecks
ngx.timer.at(0, function()
balancer.init()
end)
do
local err
build_router_semaphore, err = semaphore.new()
if err then
log(ngx.CRIT, "failed to create build_router_semaphore: ", err)
end
build_router_semaphore:post(1)
end
end
},
certificate = {
before = function(_)
certificate.execute()
end
},
rewrite = {
before = function(ctx)
ctx.KONG_REWRITE_START = get_now()
mesh.rewrite(ctx)
end,
after = function(ctx)
ctx.KONG_REWRITE_TIME = get_now() - ctx.KONG_REWRITE_START -- time spent in Kong's rewrite_by_lua
end
},
preread = {
before = function(ctx)
local router, err = get_router()
if not router then
log(ERR, "no router to route connection (reason: " .. err .. ")")
return ngx.exit(500)
end
local match_t = router.exec(ngx)
if not match_t then
log(ERR, "no Route found with those values")
return ngx.exit(500)
end
local var = ngx.var
local ssl_termination_ctx -- OpenSSL SSL_CTX to use for termination
local ssl_preread_alpn_protocols = var.ssl_preread_alpn_protocols
-- ssl_preread_alpn_protocols is a comma separated list
-- see https://trac.nginx.org/nginx/ticket/1616
if ssl_preread_alpn_protocols and
ssl_preread_alpn_protocols:find(mesh.get_mesh_alpn(), 1, true) then
-- Is probably an incoming service mesh connection
-- terminate service-mesh Mutual TLS
ssl_termination_ctx = mesh.mesh_server_ssl_ctx
ctx.is_service_mesh_request = true
else
-- TODO: stream router should decide if TLS is terminated or not
-- XXX: for now, use presence of SNI to terminate.
local sni = var.ssl_preread_server_name
if sni then
ngx.log(ngx.DEBUG, "SNI: ", sni)
local err
ssl_termination_ctx, err = certificate.find_certificate(sni)
if not ssl_termination_ctx then
ngx.log(ngx.ERR, err)
return ngx.exit(ngx.ERROR)
end
-- TODO Fake certificate phase?
ngx.log(ngx.INFO, "attempting to terminate TLS")
end
end
-- Terminate TLS
if ssl_termination_ctx and not ngx.req.starttls(ssl_termination_ctx) then -- luacheck: ignore
-- errors are logged by nginx core
return ngx.exit(ngx.ERROR)
end
ctx.KONG_PREREAD_START = get_now()
local api = match_t.api or EMPTY_T
local route = match_t.route or EMPTY_T
local service = match_t.service or EMPTY_T
local upstream_url_t = match_t.upstream_url_t
balancer_setup_stage1(ctx, match_t.upstream_scheme,
upstream_url_t.type,
upstream_url_t.host,
upstream_url_t.port,
service, route, api)
end,
after = function(ctx)
local ok, err, errcode = balancer_setup_stage2(ctx)
if not ok then
local body = utils.get_default_exit_body(errcode, err)
return kong.response.exit(errcode, body)
end
local now = get_now()
-- time spent in Kong's preread_by_lua
ctx.KONG_PREREAD_TIME = now - ctx.KONG_PREREAD_START
ctx.KONG_PREREAD_ENDED_AT = now
-- time spent in Kong before sending the request to upstream
-- ngx.req.start_time() is kept in seconds with millisecond resolution.
ctx.KONG_PROXY_LATENCY = now - ngx.req.start_time() * 1000
ctx.KONG_PROXIED = true
end
},
access = {
before = function(ctx)
-- router for Routes/Services
local router, err = get_router()
if not router then
kong.log.err("no router to route request (reason: " .. tostring(err) .. ")")
return kong.response.exit(500, { message = "An unexpected error occurred" })
end
-- routing request
local var = ngx.var
ctx.KONG_ACCESS_START = get_now()
local match_t = router.exec(ngx)
if not match_t then
return kong.response.exit(404, { message = "no Route matched with those values" })
end
local route = match_t.route or EMPTY_T
local service = match_t.service or EMPTY_T
local upstream_url_t = match_t.upstream_url_t
local realip_remote_addr = var.realip_remote_addr
local forwarded_proto
local forwarded_host
local forwarded_port
-- X-Forwarded-* Headers Parsing
--
-- We could use $proxy_add_x_forwarded_for, but it does not work properly
-- with the realip module. The realip module overrides $remote_addr and it
-- is okay for us to use it in case no X-Forwarded-For header was present.
-- But in case it was given, we will append the $realip_remote_addr that
-- contains the IP that was originally in $remote_addr before realip
-- module overrode that (aka the client that connected us).
local trusted_ip = kong.ip.is_trusted(realip_remote_addr)
if trusted_ip then
forwarded_proto = var.http_x_forwarded_proto or var.scheme
forwarded_host = var.http_x_forwarded_host or var.host
forwarded_port = var.http_x_forwarded_port or var.server_port
else
forwarded_proto = var.scheme
forwarded_host = var.host
forwarded_port = var.server_port
end
local protocols = route.protocols
if (protocols and
protocols.https and not protocols.http and forwarded_proto ~= "https")
then
ngx.header["connection"] = "Upgrade"
ngx.header["upgrade"] = "TLS/1.2, HTTP/1.1"
return kong.response.exit(426, { message = "Please use HTTPS protocol" })
end
balancer_setup_stage1(ctx, match_t.upstream_scheme,
upstream_url_t.type,
upstream_url_t.host,
upstream_url_t.port,
service, route)
ctx.router_matches = match_t.matches
-- `uri` is the URI with which to call upstream, as returned by the
-- router, which might have truncated it (`strip_uri`).
-- `host` is the original header to be preserved if set.
var.upstream_scheme = match_t.upstream_scheme -- COMPAT: pdk
var.upstream_uri = match_t.upstream_uri
var.upstream_host = match_t.upstream_host
-- Keep-Alive and WebSocket Protocol Upgrade Headers
if var.http_upgrade and lower(var.http_upgrade) == "websocket" then
var.upstream_connection = "upgrade"
var.upstream_upgrade = "websocket"
else
var.upstream_connection = "keep-alive"
end
-- X-Forwarded-* Headers
local http_x_forwarded_for = var.http_x_forwarded_for
if http_x_forwarded_for then
var.upstream_x_forwarded_for = http_x_forwarded_for .. ", " ..
realip_remote_addr
else
var.upstream_x_forwarded_for = var.remote_addr
end
var.upstream_x_forwarded_proto = forwarded_proto
var.upstream_x_forwarded_host = forwarded_host
var.upstream_x_forwarded_port = forwarded_port
end,
-- Only executed if the `router` module found a route and allows nginx to proxy it.
after = function(ctx)
local var = ngx.var
do
-- Nginx's behavior when proxying a request with an empty querystring
-- `/foo?` is to keep `$is_args` an empty string, hence effectively
-- stripping the empty querystring.
-- We overcome this behavior with our own logic, to preserve user
-- desired semantics.
local upstream_uri = var.upstream_uri
if var.is_args == "?" or sub(var.request_uri, -1) == "?" then
var.upstream_uri = upstream_uri .. "?" .. (var.args or "")
end
end
local balancer_data = ctx.balancer_data
balancer_data.scheme = var.upstream_scheme -- COMPAT: pdk
local ok, err, errcode = balancer_setup_stage2(ctx)
if not ok then
local body = utils.get_default_exit_body(errcode, err)
return kong.response.exit(errcode, body)
end
var.upstream_scheme = balancer_data.scheme
do
-- set the upstream host header if not `preserve_host`
local upstream_host = var.upstream_host
if not upstream_host or upstream_host == "" then
upstream_host = balancer_data.hostname
local upstream_scheme = var.upstream_scheme
if upstream_scheme == "http" and balancer_data.port ~= 80 or
upstream_scheme == "https" and balancer_data.port ~= 443
then
upstream_host = upstream_host .. ":" .. balancer_data.port
end
var.upstream_host = upstream_host
end
end
local now = get_now()
-- time spent in Kong's access_by_lua
ctx.KONG_ACCESS_TIME = now - ctx.KONG_ACCESS_START
ctx.KONG_ACCESS_ENDED_AT = now
-- time spent in Kong before sending the request to upstream
-- ngx.req.start_time() is kept in seconds with millisecond resolution.
ctx.KONG_PROXY_LATENCY = now - ngx.req.start_time() * 1000
ctx.KONG_PROXIED = true
end
},
balancer = {
before = function(ctx)
local balancer_data = ctx.balancer_data
local current_try = balancer_data.tries[balancer_data.try_count]
current_try.balancer_start = get_now()
end,
after = function(ctx)
local balancer_data = ctx.balancer_data
local current_try = balancer_data.tries[balancer_data.try_count]
-- record try-latency
local try_latency = get_now() - current_try.balancer_start
current_try.balancer_latency = try_latency
-- record overall latency
ctx.KONG_BALANCER_TIME = (ctx.KONG_BALANCER_TIME or 0) + try_latency
end
},
header_filter = {
before = function(ctx)
local header = ngx.header
if not ctx.KONG_PROXIED then
return
end
local now = get_now()
-- time spent waiting for a response from upstream
ctx.KONG_WAITING_TIME = now - ctx.KONG_ACCESS_ENDED_AT
ctx.KONG_HEADER_FILTER_STARTED_AT = now
local upstream_status_header = constants.HEADERS.UPSTREAM_STATUS
if singletons.configuration.enabled_headers[upstream_status_header] then
header[upstream_status_header] = tonumber(sub(ngx.var.upstream_status or "", -3))
if not header[upstream_status_header] then
log(ERR, "failed to set ", upstream_status_header, " header")
end
end
local hash_cookie = ctx.balancer_data.hash_cookie
if not hash_cookie then
return
end
local cookie = ck:new()
local ok, err = cookie:set(hash_cookie)
if not ok then
log(ngx.WARN, "failed to set the cookie for hash-based load balancing: ", err,
" (key=", hash_cookie.key,
", path=", hash_cookie.path, ")")
end
end,
after = function(ctx)
local header = ngx.header
if ctx.KONG_PROXIED then
if singletons.configuration.enabled_headers[constants.HEADERS.UPSTREAM_LATENCY] then
header[constants.HEADERS.UPSTREAM_LATENCY] = ctx.KONG_WAITING_TIME
end
if singletons.configuration.enabled_headers[constants.HEADERS.PROXY_LATENCY] then
header[constants.HEADERS.PROXY_LATENCY] = ctx.KONG_PROXY_LATENCY
end
if singletons.configuration.enabled_headers[constants.HEADERS.VIA] then
header[constants.HEADERS.VIA] = server_header
end
else
if singletons.configuration.enabled_headers[constants.HEADERS.SERVER] then
header[constants.HEADERS.SERVER] = server_header
else
header[constants.HEADERS.SERVER] = nil
end
end
end
},
body_filter = {
after = function(ctx)
if not ngx.arg[2] then
return
end
local now = get_now()
ctx.KONG_BODY_FILTER_ENDED_AT = now
if ctx.KONG_PROXIED then
-- time spent receiving the response (header_filter + body_filter)
-- we could use $upstream_response_time but we need to distinguish the waiting time
-- from the receiving time in our logging plugins (especially ALF serializer).
ctx.KONG_RECEIVE_TIME = now - ctx.KONG_HEADER_FILTER_STARTED_AT
end
end
},
log = {
after = function(ctx)
reports.log()
if not ctx.KONG_PROXIED then
return
end
-- If response was produced by an upstream (ie, not by a Kong plugin)
-- Report HTTP status for health checks
local balancer_data = ctx.balancer_data
if balancer_data and balancer_data.balancer and balancer_data.ip then
local ip, port = balancer_data.ip, balancer_data.port
local status = ngx.status
if status == 504 then
balancer_data.balancer.report_timeout(ip, port)
else
balancer_data.balancer.report_http_status(ip, port, status)
end
end
end
}
}
|
return {
version = "1.4",
luaversion = "5.1",
tiledversion = "1.4.3",
orientation = "orthogonal",
renderorder = "right-down",
width = 32,
height = 22,
tilewidth = 8,
tileheight = 8,
nextlayerid = 5,
nextobjectid = 678,
properties = {},
tilesets = {
{
name = "tiles-overworld",
firstgid = 1,
filename = "../../../../../tiled/new_tilesets/tiles-overworld.tsx",
tilewidth = 8,
tileheight = 8,
spacing = 0,
margin = 0,
columns = 36,
image = "../../graphics/tiles-overworld.png",
imagewidth = 288,
imageheight = 128,
objectalignment = "unspecified",
tileoffset = {
x = 0,
y = 0
},
grid = {
orientation = "orthogonal",
width = 8,
height = 8
},
properties = {},
terrains = {},
tilecount = 576,
tiles = {}
},
{
name = "collide8",
firstgid = 577,
filename = "../../../../../tiled/new_tilesets/collide8.tsx",
tilewidth = 8,
tileheight = 8,
spacing = 0,
margin = 0,
columns = 1,
image = "../../graphics/collider8.png",
imagewidth = 8,
imageheight = 8,
objectalignment = "unspecified",
tileoffset = {
x = 0,
y = 0
},
grid = {
orientation = "orthogonal",
width = 8,
height = 8
},
properties = {},
terrains = {},
tilecount = 1,
tiles = {}
}
},
layers = {
{
type = "tilelayer",
x = 0,
y = 0,
width = 32,
height = 22,
id = 2,
name = "Water_layer",
visible = true,
opacity = 1,
offsetx = 0,
offsety = 0,
properties = {},
encoding = "lua",
data = {
338, 339, 338, 339, 338, 339, 338, 339, 338, 339, 338, 339, 338, 414, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
374, 375, 374, 375, 374, 375, 374, 375, 374, 375, 374, 375, 374, 378, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
338, 339, 338, 339, 338, 339, 338, 339, 338, 339, 338, 339, 338, 414, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
374, 375, 374, 375, 374, 375, 374, 375, 374, 375, 374, 375, 374, 378, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
338, 339, 338, 339, 338, 339, 338, 339, 338, 339, 338, 339, 338, 414, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
374, 375, 374, 375, 374, 375, 374, 375, 374, 375, 374, 375, 374, 378, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
338, 339, 338, 339, 338, 339, 338, 339, 338, 339, 338, 339, 338, 414, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
374, 375, 374, 375, 374, 375, 374, 375, 374, 375, 374, 375, 374, 378, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
338, 339, 338, 339, 338, 339, 338, 339, 338, 339, 338, 339, 338, 414, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
483, 484, 483, 484, 483, 484, 483, 484, 483, 484, 483, 484, 483, 486, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 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",
x = 0,
y = 0,
width = 32,
height = 22,
id = 1,
name = "Ground_layer",
visible = true,
opacity = 1,
offsetx = 0,
offsety = 0,
properties = {},
encoding = "lua",
data = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
}
},
{
type = "tilelayer",
x = 0,
y = 0,
width = 32,
height = 22,
id = 3,
name = "Collision_layer",
visible = true,
opacity = 1,
offsetx = 0,
offsety = 0,
properties = {},
encoding = "lua",
data = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 87, 88, 87, 88, 87, 88, 87, 88, 87, 88, 87, 88, 87, 88,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 123, 124, 123, 124, 123, 124, 123, 124, 123, 124, 123, 124, 123, 124,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 87, 88, 87, 88, 87, 88, 87, 88, 87, 88, 87, 88, 87, 88,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 123, 124, 123, 124, 123, 124, 123, 124, 123, 124, 123, 124, 123, 124,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 87, 88, 87, 88, 87, 88,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 123, 124, 123, 124, 123, 124,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 87, 88, 87, 88, 87, 88,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 123, 124, 123, 124, 123, 124,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 87, 88, 87, 88, 87, 88,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 123, 124, 123, 124, 123, 124,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 87, 88, 87, 88, 87, 88,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 123, 124, 123, 124, 123, 124,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 87, 88, 87, 88, 87, 88,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 123, 124, 123, 124, 123, 124,
87, 88, 87, 88, 87, 88, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 87, 88, 87, 88, 87, 88,
123, 124, 123, 124, 123, 124, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 123, 124, 123, 124, 123, 124,
87, 88, 87, 88, 87, 88, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 87, 88, 87, 88, 87, 88, 87, 88, 87, 88, 87, 88, 87, 88,
123, 124, 123, 124, 123, 124, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 123, 124, 123, 124, 123, 124, 123, 124, 123, 124, 123, 124, 123, 124,
87, 88, 87, 88, 87, 88, 87, 88, 87, 88, 87, 88, 87, 88, 0, 0, 0, 0, 87, 88, 87, 88, 87, 88, 87, 88, 87, 88, 87, 88, 87, 88,
123, 124, 123, 124, 123, 124, 123, 124, 123, 124, 123, 124, 123, 124, 0, 0, 0, 0, 123, 124, 123, 124, 123, 124, 123, 124, 123, 124, 123, 124, 123, 124,
87, 88, 87, 88, 87, 88, 87, 88, 87, 88, 87, 88, 87, 88, 0, 0, 0, 0, 87, 88, 87, 88, 87, 88, 87, 88, 87, 88, 87, 88, 87, 88,
123, 124, 123, 124, 123, 124, 123, 124, 123, 124, 123, 124, 123, 124, 0, 0, 0, 0, 123, 124, 123, 124, 123, 124, 123, 124, 123, 124, 123, 124, 123, 124
}
},
{
type = "objectgroup",
draworder = "topdown",
id = 4,
name = "Collide",
visible = false,
opacity = 0.5,
offsetx = 0,
offsety = 0,
properties = {},
objects = {
{
id = 573,
name = "",
type = "",
shape = "rectangle",
x = 0,
y = 80,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 574,
name = "",
type = "",
shape = "rectangle",
x = 8,
y = 80,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 575,
name = "",
type = "",
shape = "rectangle",
x = 16,
y = 80,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 576,
name = "",
type = "",
shape = "rectangle",
x = 24,
y = 80,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 577,
name = "",
type = "",
shape = "rectangle",
x = 32,
y = 80,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 578,
name = "",
type = "",
shape = "rectangle",
x = 40,
y = 80,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 579,
name = "",
type = "",
shape = "rectangle",
x = 48,
y = 80,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 580,
name = "",
type = "",
shape = "rectangle",
x = 56,
y = 80,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 581,
name = "",
type = "",
shape = "rectangle",
x = 64,
y = 80,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 582,
name = "",
type = "",
shape = "rectangle",
x = 72,
y = 80,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 583,
name = "",
type = "",
shape = "rectangle",
x = 80,
y = 80,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 584,
name = "",
type = "",
shape = "rectangle",
x = 88,
y = 80,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 585,
name = "",
type = "",
shape = "rectangle",
x = 96,
y = 80,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 586,
name = "",
type = "",
shape = "rectangle",
x = 40,
y = 128,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 587,
name = "",
type = "",
shape = "rectangle",
x = 40,
y = 136,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 588,
name = "",
type = "",
shape = "rectangle",
x = 40,
y = 144,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 590,
name = "",
type = "",
shape = "rectangle",
x = 112,
y = 184,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 591,
name = "",
type = "",
shape = "rectangle",
x = 120,
y = 184,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 592,
name = "",
type = "",
shape = "rectangle",
x = 128,
y = 184,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 593,
name = "",
type = "",
shape = "rectangle",
x = 136,
y = 184,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 599,
name = "",
type = "",
shape = "rectangle",
x = 104,
y = 80,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 600,
name = "",
type = "",
shape = "rectangle",
x = 40,
y = 120,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 601,
name = "",
type = "",
shape = "rectangle",
x = 32,
y = 120,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 602,
name = "",
type = "",
shape = "rectangle",
x = 24,
y = 120,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 603,
name = "",
type = "",
shape = "rectangle",
x = 16,
y = 120,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 604,
name = "",
type = "",
shape = "rectangle",
x = 8,
y = 120,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 605,
name = "",
type = "",
shape = "rectangle",
x = 0,
y = 120,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 606,
name = "",
type = "",
shape = "rectangle",
x = -8,
y = 96,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 607,
name = "",
type = "",
shape = "rectangle",
x = -8,
y = 88,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 610,
name = "",
type = "",
shape = "rectangle",
x = 144,
y = 136,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 611,
name = "",
type = "",
shape = "rectangle",
x = 152,
y = 136,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 612,
name = "",
type = "",
shape = "rectangle",
x = 160,
y = 136,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 613,
name = "",
type = "",
shape = "rectangle",
x = 168,
y = 136,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 614,
name = "",
type = "",
shape = "rectangle",
x = 176,
y = 136,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 615,
name = "",
type = "",
shape = "rectangle",
x = 184,
y = 136,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 616,
name = "",
type = "",
shape = "rectangle",
x = 192,
y = 136,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 617,
name = "",
type = "",
shape = "rectangle",
x = 200,
y = 136,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 623,
name = "",
type = "",
shape = "rectangle",
x = 48,
y = 152,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 624,
name = "",
type = "",
shape = "rectangle",
x = 56,
y = 152,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 625,
name = "",
type = "",
shape = "rectangle",
x = 64,
y = 152,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 626,
name = "",
type = "",
shape = "rectangle",
x = 72,
y = 152,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 627,
name = "",
type = "",
shape = "rectangle",
x = 80,
y = 152,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 628,
name = "",
type = "",
shape = "rectangle",
x = 88,
y = 152,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 629,
name = "",
type = "",
shape = "rectangle",
x = 96,
y = 152,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 630,
name = "",
type = "",
shape = "rectangle",
x = 104,
y = 152,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 631,
name = "",
type = "",
shape = "rectangle",
x = 104,
y = 176,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 632,
name = "",
type = "",
shape = "rectangle",
x = 104,
y = 168,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 633,
name = "",
type = "",
shape = "rectangle",
x = 104,
y = 160,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 634,
name = "",
type = "",
shape = "rectangle",
x = 144,
y = 176,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 635,
name = "",
type = "",
shape = "rectangle",
x = 144,
y = 168,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 636,
name = "",
type = "",
shape = "rectangle",
x = 144,
y = 160,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 637,
name = "",
type = "",
shape = "rectangle",
x = 144,
y = 152,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 638,
name = "",
type = "",
shape = "rectangle",
x = 144,
y = 144,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 639,
name = "",
type = "",
shape = "rectangle",
x = 208,
y = 128,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 640,
name = "",
type = "",
shape = "rectangle",
x = 208,
y = 120,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 641,
name = "",
type = "",
shape = "rectangle",
x = 208,
y = 112,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 642,
name = "",
type = "",
shape = "rectangle",
x = 208,
y = 104,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 643,
name = "",
type = "",
shape = "rectangle",
x = 208,
y = 96,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 644,
name = "",
type = "",
shape = "rectangle",
x = 208,
y = 88,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 645,
name = "",
type = "",
shape = "rectangle",
x = 208,
y = 80,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 646,
name = "",
type = "",
shape = "rectangle",
x = 208,
y = 72,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 647,
name = "",
type = "",
shape = "rectangle",
x = 208,
y = 64,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 648,
name = "",
type = "",
shape = "rectangle",
x = 208,
y = 56,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 649,
name = "",
type = "",
shape = "rectangle",
x = 208,
y = 48,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 650,
name = "",
type = "",
shape = "rectangle",
x = 208,
y = 40,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 651,
name = "",
type = "",
shape = "rectangle",
x = 208,
y = 32,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 652,
name = "",
type = "",
shape = "rectangle",
x = 200,
y = 32,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 653,
name = "",
type = "",
shape = "rectangle",
x = 192,
y = 32,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 654,
name = "",
type = "",
shape = "rectangle",
x = 184,
y = 32,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 655,
name = "",
type = "",
shape = "rectangle",
x = 176,
y = 32,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 656,
name = "",
type = "",
shape = "rectangle",
x = 168,
y = 32,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 657,
name = "",
type = "",
shape = "rectangle",
x = 160,
y = 32,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 658,
name = "",
type = "",
shape = "rectangle",
x = 152,
y = 32,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 659,
name = "",
type = "",
shape = "rectangle",
x = 144,
y = 32,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 660,
name = "",
type = "",
shape = "rectangle",
x = 144,
y = 24,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 661,
name = "",
type = "",
shape = "rectangle",
x = 144,
y = 16,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 662,
name = "",
type = "",
shape = "rectangle",
x = 144,
y = 8,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 663,
name = "",
type = "",
shape = "rectangle",
x = 136,
y = 0,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 664,
name = "",
type = "",
shape = "rectangle",
x = 128,
y = 0,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 665,
name = "",
type = "",
shape = "rectangle",
x = 120,
y = 0,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 666,
name = "",
type = "",
shape = "rectangle",
x = 112,
y = 0,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 667,
name = "",
type = "",
shape = "rectangle",
x = 104,
y = 8,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 668,
name = "",
type = "",
shape = "rectangle",
x = 104,
y = 16,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 669,
name = "",
type = "",
shape = "rectangle",
x = 104,
y = 24,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 670,
name = "",
type = "",
shape = "rectangle",
x = 104,
y = 32,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 671,
name = "",
type = "",
shape = "rectangle",
x = 104,
y = 40,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 672,
name = "",
type = "",
shape = "rectangle",
x = 104,
y = 48,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 673,
name = "",
type = "",
shape = "rectangle",
x = 104,
y = 56,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 674,
name = "",
type = "",
shape = "rectangle",
x = 104,
y = 64,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 675,
name = "",
type = "",
shape = "rectangle",
x = 104,
y = 72,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 676,
name = "",
type = "",
shape = "rectangle",
x = -8,
y = 104,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
},
{
id = 677,
name = "",
type = "",
shape = "rectangle",
x = -8,
y = 112,
width = 8,
height = 8,
rotation = 0,
gid = 577,
visible = true,
properties = {}
}
}
}
}
}
|
local module = {}
--[[
When allocating push stack marker
which is assigned to the variable
If the variable is needed then just
calculate the diff between the var
marker and current stack marker
which will be the offset for rsp
!!
THIS IS JUST AN EXPERIMENT IN HOW TO HANDLE OUTPUT
!!
]]
local instru = {
["alloc8"] = {asm="sub rsp, 8", type="alloc", size=8},
["alloc16"] = {asm="sub rsp, 16", type="alloc", size=16},
["alloc32"] = {asm="sub rsp, 32", type="alloc", size=32},
["alloc64"] = {asm="sub rsp, 64", type="alloc", size=64}
}
local function init_IR()
local tmp = {}
tmp.stack_pointer = 0
tmp.instructions = {}
return tmp
end
local function alloc_stack(IR, size, note)
local emit = {}
emit.asm = instru[size].asm
emit.type = instru[size].type
emit.size = instru[size].size
-- local emit = instru[size]
if note ~= nil then
emit.asm = emit.asm .. "; "..tostring(note)
end
table.insert(IR.instructions, emit)
IR.stack_pointer = IR.stack_pointer + instru[size].size
return IR.stack_pointer
end
local function alloc_stack_int64(IR,variable)
local stack_addr = alloc_stack(IR, "alloc64", "int64")
variable.address = stack_addr
return stack_addr
end
local function emit_instructions(f, IR)
for k,v in pairs(IR.instructions) do
f:write(" ")
f:write(v.asm)
f:write("\n")
end
end
local function emit_header(f)
f:write("extern printf\n")
f:write("extern ExitProcess\n")
f:write("; END OF HEADER\n")
f:write("section .text\n")
f:write(" global main\n")
f:write("main:\n")
f:write(" mov rdx, -1\n")
end
local function emit_footer(f)
f:write(" mov rcx, msg\n")
f:write(" call printf\n")
f:write(" xor ecx,ecx\n")
f:write(" call ExitProcess\n")
f:write("section .data\n")
f:write("msg db \"End of program %i\",0\n")
f:write("section .bss\n")
end
local function emit_IR(IR)
local f = io.open("build.asm", "w")
emit_header(f)
emit_instructions(f, IR)
emit_footer(f)
f:close()
end
local function emit_assign(IR, s, var)
-- mov
local instruction = {}
instruction.asm = "mov rdx, qword "
instruction.asm = instruction.asm .. tostring(s.right.value)
table.insert(IR.instructions, instruction)
instruction = {}
instruction.asm = "mov [rsp-"
instruction.asm = instruction.asm .. tostring(IR.stack_pointer - var.address)
instruction.asm = instruction.asm .. "], rdx"
table.insert(IR.instructions, instruction)
end
module.compile = function(ast, outname)
-- ast.nodes contains all statements
-- ast.variables for all variables used
-- ast.constants for all constant values (currently only numbers)
-- step through all statements
-- for each one, break them down to single operations
-- output said operations as assembly
local IR = init_IR()
local vars = {}
for v in pairs(ast.variables) do
local tmp = {}
tmp.name = v
tmp.address = "nil"
alloc_stack_int64(IR, tmp)
vars[v] = tmp
end
for k,s in pairs(ast.nodes) do
if s.type == "operator" and s.op_type == "binary" and s.op == "=" then
emit_assign(IR, s, vars[s.left.name])
end
end
emit_IR(IR)
end
return module
|
--wall-clock time, monotonic time and sleeping for Windows, Linux and OSX.
--Written by Cosmin Apreutesei. Public Domain.
local ffi = require'ffi'
local M = {}
local C = ffi.C
if ffi.os == 'Windows' then
ffi.cdef[[
void time_GetSystemTimeAsFileTime(uint64_t*) asm("GetSystemTimeAsFileTime");
int time_QueryPerformanceCounter(int64_t*) asm("QueryPerformanceCounter");
int time_QueryPerformanceFrequency(int64_t*) asm("QueryPerformanceFrequency");
void time_Sleep(uint32_t ms) asm("Sleep");
]]
local t = ffi.new'uint64_t[1]'
local DELTA_EPOCH_IN_100NS = 116444736000000000ULL
function M.time()
C.time_GetSystemTimeAsFileTime(t)
return tonumber(t[0] - DELTA_EPOCH_IN_100NS) * 1e-7
end
assert(C.time_QueryPerformanceFrequency(t) ~= 0)
local inv_qpf = 1 / tonumber(t[0]) --precision loss in e-10
function M.clock()
assert(C.time_QueryPerformanceCounter(t) ~= 0)
return tonumber(t[0]) * inv_qpf
end
function M.sleep(s)
C.time_Sleep(s * 1000)
end
elseif ffi.os == 'Linux' or ffi.os == 'OSX' then
ffi.cdef[[
typedef struct {
long s;
long ns;
} time_timespec;
int time_nanosleep(time_timespec*, time_timespec *) asm("nanosleep");
]]
local EINTR = 4
local t = ffi.new'time_timespec'
function M.sleep(s)
local int, frac = math.modf(s)
t.s = int
t.ns = frac * 1e9
local ret = C.time_nanosleep(t, t)
while ret == -1 and ffi.errno() == EINTR do --interrupted
ret = C.time_nanosleep(t, t)
end
assert(ret == 0)
end
if ffi.os == 'Linux' then
ffi.cdef[[
int time_clock_gettime(int clock_id, time_timespec *tp) asm("clock_gettime");
]]
local CLOCK_REALTIME = 0
local CLOCK_MONOTONIC = 1
local ok, rt_C = pcall(ffi.load, 'rt')
local clock_gettime = (ok and rt_C or C).time_clock_gettime
local function tos(t)
return tonumber(t.s) + tonumber(t.ns) / 1e9
end
function M.time()
assert(clock_gettime(CLOCK_REALTIME, t) == 0)
return tos(t)
end
function M.clock()
assert(clock_gettime(CLOCK_MONOTONIC, t) == 0)
return tos(t)
end
elseif ffi.os == 'OSX' then
ffi.cdef[[
typedef struct {
long s;
int32_t us;
} time_timeval;
typedef struct {
uint32_t numer;
uint32_t denom;
} time_mach_timebase_info_data_t;
int time_gettimeofday(time_timeval*, void*) asm("gettimeofday");
int time_mach_timebase_info(time_mach_timebase_info_data_t* info) asm("mach_timebase_info");
uint64_t time_mach_absolute_time(void) asm("mach_absolute_time");
]]
local t = ffi.new'time_timeval'
function M.time()
assert(C.time_gettimeofday(t, nil) == 0)
return tonumber(t.s) + tonumber(t.us) * 1e-6
end
--NOTE: this appears to be pointless on Intel Macs. The timebase fraction
--is always 1/1 and mach_absolute_time() does dynamic scaling internally.
local timebase = ffi.new'time_mach_timebase_info_data_t'
assert(C.time_mach_timebase_info(timebase) == 0)
local scale = tonumber(timebase.numer) / tonumber(timebase.denom) / 1e9
function M.clock()
return tonumber(C.time_mach_absolute_time()) * scale
end
end --OSX
end --Linux or OSX
function M.install()
--replace os.time() with a more accurate version...
--glue.time() will also benefit.
local os_time = os.time
local time = M.time
function os.time(t)
if not t then return time() end
return os_time(t)
end
--replace os.date() with a more accurate version...
local os_date = os.date
local time = M.time
function os.date(fmt, t)
t = t or time()
local d = os_date(fmt, t)
if type(d) == 'table' then
d.sec = d.sec + t - floor(t) --increase accuracy in d.sec
end
return d
end
--replace os.clock() with a more accurate version...
local clock = M.clock
local t0 = clock()
function os.clock()
return clock() - t0
end
end
if not ... then
io.stdout:setvbuf'no'
local time = M
print('time ', time.time())
print('clock', time.clock())
local function test_sleep(s, ss)
local t0 = time.clock()
local times = math.floor(s*1/ss)
s = times * ss
print(string.format('sleeping %gms in %gms increments (%d times)...', s * 1000, ss * 1000, times))
for i=1,times do
time.sleep(ss)
end
local t1 = time.clock()
print(string.format(' missed by: %0.2fms', (t1 - t0 - s) / times * 1000))
end
test_sleep(0.001, 0.001)
test_sleep(0.2, 0.02)
test_sleep(2, 0.2)
end
return M
|
-- Dialogue for NPC "npc_lola"
loadDialogue = function(DL)
if (not DL:isConditionFulfilled("npc_mona", "sex_romantic")) then
DL:setRoot(1)
elseif (not DL:isConditionFulfilled("npc_lola", "talk")) then
DL:setRoot(2)
elseif (not DL:isConditionFulfilled("npc_lola", "question_1")) then
DL:setRoot(4)
elseif (not DL:isConditionFulfilled("npc_lola", "question_2")) then
DL:setRoot(11)
elseif (not DL:isConditionFulfilled("npc_lola", "question_3")) then
DL:setRoot(17)
elseif (not DL:isConditionFulfilled("npc_lola", "sex")) then
DL:setRoot(25)
elseif (not DL:isConditionFulfilled("npc_lola", "after_sex")) then
DL:setRoot(29)
else
DL:setRoot(30)
end
if (not DL:isConditionFulfilled("npc_mona", "sex_romantic")) then
DL:createNPCNode(1, -1, "DL_Lola_NotBought") -- Talk to Mona first if you want to have some fun, cutie.
DL:addNode()
end
if (not DL:isConditionFulfilled("npc_lola", "talk")) then
DL:createChoiceNode(2)
if (not DL:isConditionFulfilled("npc_lola", "sex_lola")) then
DL:addChoice(3, "DL_Choice_Hey") -- Hey...
end
DL:addChoice(-1, "DL_Choice_End") -- See you.
DL:addNode()
if (not DL:isConditionFulfilled("npc_lola", "sex_lola")) then
DL:createNPCNode(3, -2, "DL_Lola_SexyBoy") -- Hey, handsome. Why don't you come in and we and we'll have a little chat?
DL:addConditionProgress("npc_lola", "talk")
DL:addNode()
end
end
if (not DL:isConditionFulfilled("npc_lola", "question_1")) then
DL:createChoiceNode(4)
if (not DL:isConditionFulfilled("npc_lola", "no_talk")) then
DL:addChoice(5, "DL_Choice_NoTalk") -- I'm not here to talk.
end
if (DL:isConditionFulfilled("npc_lola", "no_talk") and not DL:isConditionFulfilled("npc_lola", "angry") ) then
DL:addChoice(7, "DL_Choice_Angry") -- I thought this was a brothel, not a tea party.
end
DL:addChoice(6, "DL_Choice_OkTalk") -- What do you want to talk about?
DL:addChoice(-1, "") --
DL:addNode()
if (not DL:isConditionFulfilled("npc_lola", "no_talk")) then
DL:createNPCNode(5, -1, "DL_Lola_NoTalk") -- You are in the wrong room then. Come back if you change your mind.
DL:addConditionProgress("npc_lola", "no_talk")
DL:addNode()
end
if (DL:isConditionFulfilled("npc_lola", "no_talk") and not DL:isConditionFulfilled("npc_lola", "angry") ) then
DL:createNPCNode(7, -2, "DL_Lola_Angry") -- Oh, it is. But love is not always about in-out-in-out, you know.
DL:addConditionProgress("npc_lola", "angry")
DL:addNode()
end
DL:createNPCNode(6, 8, "DL_Lola_OkTalk") -- Let's talk about you. Why are you here?
DL:addConditionProgress("npc_lola", "question_1")
DL:addNode()
DL:createChoiceNode(8)
DL:addChoice(9, "DL_Choice_Curious") -- I was just curious.
DL:addChoice(10, "DL_Choice_IWasHorny") -- Well, to be honest, I'm a bit horny.
DL:addChoice(12, "DL_Choice_LookingForLove") -- I'm looking for love.
DL:addNode()
DL:createNPCNode(9, -2, "DL_Lola_Curious") -- Most of you are. I hope you'll enjoy your stay here. (Smiles)
DL:addNode()
DL:createNPCNode(10, -2, "DL_Lola_IWasHorny") -- You'll get your money's worth, promised. (Winks)
DL:addNode()
DL:createNPCNode(12, -2, "DL_Lola_LookingForLove") -- Maybe you'll find it here. Depends on what kind of love you're looking for. (Smiles)
DL:addNode()
end
if (not DL:isConditionFulfilled("npc_lola", "question_2")) then
DL:createNPCNode(11, 13, "DL_Lola_SecondQuestion") -- Now, another question. Who are you?
DL:addConditionProgress("npc_lola", "question_2")
DL:addNode()
DL:createChoiceNode(13)
DL:addChoice(14, "DL_Choice_NoneOfYourBusiness") -- That's none of your business.
DL:addChoice(15, "DL_Choice_Adventurer") -- I'm a lonesome adventurer.
DL:addChoice(16, "DL_Choice_NoOne") -- I don't really know that myself.
DL:addNode()
DL:createNPCNode(14, -2, "DL_Lola_NoneOfYourBusiness") -- Oh... okay.
DL:addNode()
DL:createNPCNode(15, -2, "DL_Lola_Adventurer") -- Hn. I love these kind of men.
DL:addNode()
DL:createNPCNode(16, -2, "DL_Lola_NoOne") -- Hm. I feel the same from time to time. But finding yourself is just part of life.
DL:addNode()
end
if (not DL:isConditionFulfilled("npc_lola", "question_3")) then
DL:createNPCNode(17, 18, "DL_Lola_FavGirl") -- Okay, last question for you: What makes a girl attractive to you?
DL:addConditionProgress("npc_lola", "question_3")
DL:addNode()
DL:createChoiceNode(18)
DL:addChoice(19, "DL_Choice_GirlAttractive") -- A beautiful body. A nice butt, big boobs, a pretty face.
DL:addChoice(21, "DL_Choice_GirlCook") -- I love it when a girl can cook.
DL:addChoice(20, "DL_Choice_GirlSmart") -- A girl should be smart and speak her mind.
DL:addChoice(22, "DL_Choice_GirlDontCare") -- I don't care. As long as it's a girl.
DL:addChoice(23, "DL_Choice_GirlReallyDontCare") -- I really don't care. I don't think about such things.
DL:addChoice(24, "DL_Choice_Gay") -- Well... actually... I think I'm gay.
DL:addNode()
DL:createNPCNode(19, -2, "DL_Lola_GirlAttractive") -- Mhm. Important, but not everything.
DL:addNode()
DL:createNPCNode(21, -2, "DL_Lola_GirlCook") -- The way to a man's heart is through his stomach.
DL:addNode()
DL:createNPCNode(20, -2, "DL_Lola_GirlSmart") -- Very important for a long-lasting relationship.
DL:addNode()
DL:createNPCNode(22, -2, "DL_Lola_GirlDontCare") -- (Lola giggles) Yes, yes. We don't have guys here, the demand is too low.
DL:addNode()
DL:createNPCNode(23, -2, "DL_Lola_GirlReallyDontCare") -- What a pity.
DL:addNode()
DL:createNPCNode(24, -2, "DL_Lola_Gay") -- Oh... really? Well, we can end this here then. I don't want to force you to anything.
DL:addNode()
end
if (not DL:isConditionFulfilled("npc_lola", "sex")) then
DL:createChoiceNode(25)
DL:addChoice(26, "DL_Choice_QuestionsForYou") -- Can *I* ask you some questions now?
DL:addChoice(27, "DL_Choice_WantSex") -- I want to have some fun with you, now.
DL:addChoice(-1, "DL_Choice_Enough") -- That's enough. I'm out.
DL:addNode()
DL:createNPCNode(26, 32, "DL_Lola_QuestionsForYou") -- Sure. What do you want to know?
DL:addNode()
DL:createChoiceNode(32)
if (not DL:isConditionFulfilled("npc_lola", "room")) then
DL:addChoice(33, "DL_Choice_Room") -- Why is this room full of roses?
end
if (not DL:isConditionFulfilled("npc_lola", "job")) then
DL:addChoice(34, "DL_Choice_Job") -- Are you happy with your job?
end
if (not DL:isConditionFulfilled("npc_lola", "attractive")) then
DL:addChoice(35, "DL_Choice_Attractive") -- Do you think I'm attractive?
end
if (not DL:isConditionFulfilled("npc_lola", "turn_on")) then
DL:addChoice(36, "DL_Choice_TurnOn") -- What turns *you* on?
end
DL:addChoice(-2, "DL_Choice_Back") -- [BACK]
DL:addNode()
if (not DL:isConditionFulfilled("npc_lola", "room")) then
DL:createNPCNode(33, -2, "DL_Lola_Room") -- It's the rose-room. Some guests keep coming back here for a romantic time.
DL:addConditionProgress("npc_lola", "room")
DL:gotoNode(32)
DL:addNode()
end
if (not DL:isConditionFulfilled("npc_lola", "job")) then
DL:createNPCNode(34, -2, "DL_Lola_Job") -- Most of the time, yes. But this is not something I'll do my entire life.
DL:addConditionProgress("npc_lola", "job")
DL:gotoNode(32)
DL:addNode()
end
if (not DL:isConditionFulfilled("npc_lola", "attractive")) then
DL:createNPCNode(35, -2, "DL_Lola_Attractive") -- Yes, of course! I love your hair.
DL:addConditionProgress("npc_lola", "attractive")
DL:gotoNode(32)
DL:addNode()
end
if (not DL:isConditionFulfilled("npc_lola", "turn_on")) then
DL:createNPCNode(36, -2, "DL_Lola_TurnOn") -- Many things. I really love when the guy enjoys it and I can see it.
DL:addConditionProgress("npc_lola", "turn_on")
DL:gotoNode(32)
DL:addNode()
end
DL:createNPCNode(27, 28, "DL_Lola_WantSex") -- I won't make you wait any longer. (Lola pulls you closer...)
DL:addNode()
DL:createNPCNode(28, -1, "") --
DL:startCutscene("sex_lola")
DL:addConditionProgress("npc_lola", "sex")
DL:addNode()
end
if (not DL:isConditionFulfilled("npc_lola", "after_sex")) then
DL:createNPCNode(29, 31, "DL_Lola_AfterSex") -- Mhm... that was good.
DL:addConditionProgress("npc_lola", "after_sex")
DL:addNode()
DL:createNPCNode(31, -2, "DL_Lola_AfterSex2") -- Here, take this rose with you, as a souvenir. (Winks)
DL:addItem("mi_rose", 1)
DL:addNode()
end
DL:createNPCNode(30, -1, "DL_Lola_End") -- Be safe, cutie.
DL:addNode()
end
|
include("shared.lua")
surface.CreateFont( "npc", {
font = "Harry P",
extended = false,
size = ScrW() * 0.07,
weight = 500,
blursize = 0,
scanlines = 0,
antialias = true,
underline = false,
italic = false,
strikeout = false,
symbol = false,
rotary = false,
shadow = false,
additive = false,
outline = true,
})
surface.CreateFont( "npc2", {
font = "Harry P",
extended = false,
size = ScrW() * 0.04,
weight = 500,
blursize = 0,
scanlines = 0,
antialias = true,
underline = false,
italic = false,
strikeout = false,
symbol = false,
rotary = false,
shadow = false,
additive = false,
outline = true,
})
function ENT:Draw()
self:DrawModel()
if ( IsValid( self ) && LocalPlayer():GetPos():Distance( self:GetPos() ) < 500 ) then
local ang = Angle( 0, ( LocalPlayer():GetPos() - self:GetPos() ):Angle()[ "yaw" ], ( LocalPlayer():GetPos() - self:GetPos() ):Angle()[ "pitch" ] ) + Angle( 0, 90, 90 )
cam.IgnoreZ( false )
cam.Start3D2D( self:GetPos() + Vector( -1, 0, 40 ), ang, .1 )
--draw.RoundedBox(12,-80,-20,146,40, Color(17, 162, 223, 200))
draw.SimpleTextOutlined( self:GetNWString( "HeaderText", "Ucuc Tozu" ), "npc", -5, -120, Color( 0,211,61, 255 ), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER, .5, Color( 0,0,0,255 ) )
draw.SimpleTextOutlined( self:GetNWString( "HeaderText2", "'E Tusuna Basarak' Satin Al" ), "npc2", -5, -60, Color( 2361, 666, 650, 255 ), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER, .5, Color( 0,0,0,255 ) )
cam.End3D2D()
end
end
|
--[[
Functions
]]
--[[
Events
]]
|
local audio_file = "_silent"
-- the best way to spread holiday cheer is singing loud for all to hear
if PREFSMAN:GetPreference("EasterEggs") and MonthOfYear()==11 then
audio_file = "jinglebells.ogg"
end
return THEME:GetPathS("", audio_file)
|
require("game.image_structures")
-- Type boxlayout_type
function create_boxlayout_type()
--
local boxlayout_type = {}
-- invis As Byte' if set, box is invisible.
boxlayout_type.invis = 0
--
-- x_loc As Integer
boxlayout_type.x_loc = 0
-- y_loc As Integer
boxlayout_type.y_loc = 0
--
-- speed As Double
boxlayout_type.speed = 0.0
-- _timer As Double
boxlayout_type._timer = 0.0
--
return boxlayout_type
-- End Type
end
--
-- Type boxpointer_type
function create_boxpointer_type()
--
local boxpointer_type = {}
-- box As LLSystem_ImageHeader Ptr' box itself.
boxpointer_type.box = create_LLSystem_ImageHeader()
-- Next As LLSystem_ImageHeader Ptr' the flashy arrow.
boxpointer_type.Next = create_LLSystem_ImageHeader()
--
-- row As String Ptr' the text, broken into formatted lines.
boxpointer_type.row = {}
--
return boxpointer_type
-- End Type
end
--
-- Type boxinternal_type
function create_boxinternal_type()
--
local boxinternal_type = {}
-- state As Integer' state of the box engine (0-3).
boxinternal_type.state = 0
--
-- opcount As Integer' counts total iterations.
boxinternal_type.opcount = 0
-- current_line As uShort' current processed line.
boxinternal_type.current_line = 0
-- jump_switch As Integer' jump off point.
boxinternal_type.jump_switch = 0
-- numoflines As Integer' total number of formatted lines.
boxinternal_type.numoflines = 0
--
-- flashhook As Double' stores hooked node, for flash.
boxinternal_type.flashhook = 0.0
-- flashbox As Byte' actual arrow state.
boxinternal_type.flashbox = 0
--
-- auto As Byte' take keypress or auto.
boxinternal_type.auto = 0
-- autohook As Double' destination node.
boxinternal_type.autohook = 0.0
-- autosleep As Double' how long to actually disply the box before closing.
boxinternal_type.autosleep = 0.0
--
-- hold_box As Double
boxinternal_type.hold_box = 0.0
-- sound As Integer
boxinternal_type.sound = 0
--
-- txtcolor As Integer' hmMmm
boxinternal_type.txtcolor = 0
--
-- confBox as integer
boxinternal_type.confBox = 0
--
-- as integer lastFG', lastBG
boxinternal_type.lastFG = 0
--
return boxinternal_type
-- End Type
end
--
-- Type boxcontrol_type
function create_boxcontrol_type()
--
local boxcontrol_type = {}
-- internal As boxinternal_type
boxcontrol_type.internal = create_boxinternal_type()
-- ptrs As boxpointer_type
boxcontrol_type.ptrs = create_boxpointer_type()
-- layout As boxlayout_type
boxcontrol_type.layout = create_boxlayout_type()
-- activated As Byte 'Ptr
boxcontrol_type.activated = 0
--
-- selected as Ubyte
boxcontrol_type.selected = 0
--
--
return boxcontrol_type
-- End Type
end
--
--
|
-- Create console
if false then
console.CreateConsole()
end
-- Only run if we have the global table
if not _G then
return
end
-- Localise globals
local _G = _G
local io = io
local file = file
-- BLT Global table
_G.BLT = { version = 2.0 }
_G.BLT.Base = {}
_G.print = function(...)
local s = ""
for i, str in ipairs( {...} ) do
if type(str) == "string" then
str = string.gsub(str, "%%", "%%%%%")
end
s = string.format("%s%s%s", s, i > 1 and "\t" or "", tostring(str))
end
log(s)
end
-- Load modules
_G.BLT._PATH = "mods/base/"
function BLT:Require( path )
dofile( string.format("%s%s", BLT._PATH, path .. ".lua") )
end
BLT:Require("req/utils/UtilsClass")
BLT:Require("req/utils/UtilsCore")
BLT:Require("req/utils/UtilsIO")
BLT:Require("req/utils/json-1.0")
BLT:Require("req/utils/json-0.9")
BLT:Require("req/utils/json")
BLT:Require("req/core/Hooks")
BLT:Require("req/BLTMod")
BLT:Require("req/BLTUpdate")
BLT:Require("req/BLTModDependency")
BLT:Require("req/BLTModule")
BLT:Require("req/BLTLogs")
BLT:Require("req/BLTModManager")
BLT:Require("req/BLTDownloadManager")
BLT:Require("req/BLTLocalization")
BLT:Require("req/BLTNotificationsManager")
BLT:Require("req/BLTPersistScripts")
BLT:Require("req/BLTKeybindsManager")
-- BLT base functions
function BLT:Initialize()
-- Create hook tables
self.hook_tables = {
pre = {},
post = {},
wildcards = {}
}
-- Override require and setup self
self:OverrideRequire()
self:Setup()
end
function BLT:Setup()
log("[BLT] Setup...")
-- Setup modules
self.Logs = BLTLogs:new()
self.Mods = BLTModManager:new()
self.Downloads = BLTDownloadManager:new()
self.Keybinds = BLTKeybindsManager:new()
self.PersistScripts = BLTPersistScripts:new()
self.Localization = BLTLocalization:new()
self.Notifications = BLTNotificationsManager:new()
-- Initialization functions
self.Logs:CleanLogs()
self.Mods:SetModsList( self:ProcessModsList( self:FindMods() ) )
-- Some backwards compatibility for v1 mods
local C = self.Mods.Constants
_G.LuaModManager = {}
_G.LuaModManager.Constants = C
_G.LuaModManager.Mods = {} -- No mods are available via old api
rawset(_G, C.logs_path_global, C.mods_directory .. C.logs_directory)
rawset(_G, C.save_path_global, C.mods_directory .. C.saves_directory)
end
function BLT:GetVersion()
return self.version
end
function BLT:GetOS()
return os.getenv("HOME") == nil and "windows" or "linux"
end
function BLT:RunHookTable( hooks_table, path )
if not hooks_table or not hooks_table[path] then
return false
end
for i, hook_data in pairs( hooks_table[path] ) do
self:RunHookFile( path, hook_data )
end
end
function BLT:RunHookFile( path, hook_data )
rawset( _G, BLTModManager.Constants.required_script_global, path or false )
rawset( _G, BLTModManager.Constants.mod_path_global, hook_data.mod:GetPath() or false )
dofile( hook_data.mod:GetPath() .. hook_data.script )
end
function BLT:OverrideRequire()
if self.require then
return false
end
-- Cache original require function
self.require = _G.require
-- Override require function to run hooks
_G.require = function( ... )
local args = { ... }
local path = args[1]
local path_lower = path:lower()
local require_result = nil
self:RunHookTable( self.hook_tables.pre, path_lower )
require_result = self.require( ... )
self:RunHookTable( self.hook_tables.post, path_lower )
for k, v in ipairs( self.hook_tables.wildcards ) do
self:RunHookFile( path, v.mod_path, v.script )
end
return require_result
end
end
function BLT:FindMods()
log("[BLT] Loading mods for state: " .. tostring(_G))
-- Get all folders in mods directory
local mods_list = {}
local folders = file.GetDirectories( BLTModManager.Constants.mods_directory )
-- If we didn't get any folders then return an empty mods list
if not folders then
return {}
end
for index, directory in pairs( folders ) do
-- Check if this directory is excluded from being checked for mods (logs, saves, etc.)
if not self.Mods:IsExcludedDirectory( directory ) then
log("[BLT] Loading mod: " .. tostring(directory))
local mod_path = "mods/" .. directory .. "/"
local mod_defintion = mod_path .. "mod.txt"
-- Attempt to read the mod defintion file
local file = io.open(mod_defintion)
if file then
-- Read the file contents
local file_contents = file:read("*all")
file:close()
-- Convert json data in a pcall so any errors won't crash the game
local mod_content = nil
local json_success = pcall(function()
mod_content = json.decode(file_contents)
end)
-- Create a BLT mod from the loaded data
if json_success and mod_content then
local new_mod = BLTMod:new( directory, mod_content )
table.insert( mods_list, new_mod )
else
log("[BLT] An error occured while loading mod.txt from: " .. tostring(mod_path))
end
else
log("[BLT] Could not read or find mod.txt in " .. tostring(directory))
end
end
end
return mods_list
end
function BLT:ProcessModsList( mods_list )
-- Prioritize mod load order
table.sort( mods_list, function(a, b)
return a:GetPriority() > b:GetPriority()
end)
return mods_list
end
-- Perform startup
BLT:Initialize()
|
--[[
gun_giver by BlockBa5her
Protected under MIT license (C) 2017
CONFIG EXPLAINING:
GUN NAMES: https://wiki.fivem.net/wiki/Weapons
ATTACHEMENT NAMES: https://wiki.fivem.net/wiki/Weapon_Components
Just look below, it should be self-explanatory
]]
config = {
['/officer'] = { -- "/officer" is the command to active the giving, make sure these are in lowercase
skin = 's_m_y_cop_01', -- the skin to change the player to (put nil if you don't want to change the skin)
guns = { -- All of the weapons to give to the player
'WEAPON_NIGHTSTICK', -- This is a weapon name, they can be found on the weapons site listed above
'WEAPON_FLASHLIGHT',
'WEAPON_COMBATPISTOL',
'WEAPON_CARBINERIFLE',
'WEAPON_PUMPSHOTGUN',
'WEAPON_STUNGUN',
'WEAPON_FIREEXTINGUISHER',
'WEAPON_PETROLCAN',
'WEAPON_FLARE'
},
attachements = { -- all of the attachements to give each weapon
{
gun = 'WEAPON_COMBATPISTOL', -- The weapon name to apply the attachements to
ids = { -- The attachements IDs to apply to the weapon
'COMPONENT_AT_PI_FLSH' -- Again, component names can be found using the link above
}
},
{
gun = 'WEAPON_CARBINERIFLE',
ids = {
'COMPONENT_AT_AR_FLSH',
'COMPONENT_AT_AR_AFGRIP',
'COMPONENT_AT_SCOPE_MEDIUM'
}
},
{
gun = 'WEAPON_PUMPSHOTGUN',
ids = {
'COMPONENT_AT_AR_FLSH'
}
}
}
},
['/officer2'] = {
skin = nil,
guns = {
'WEAPON_NIGHTSTICK',
'WEAPON_FLASHLIGHT',
'WEAPON_COMBATPISTOL',
'WEAPON_CARBINERIFLE',
'WEAPON_PUMPSHOTGUN',
'WEAPON_STUNGUN',
'WEAPON_FIREEXTINGUISHER',
'WEAPON_PETROLCAN',
'WEAPON_FLARE'
},
attachements = {
{
gun = 'WEAPON_COMBATPISTOL',
ids = {
'COMPONENT_AT_PI_FLSH'
}
},
{
gun = 'WEAPON_CARBINERIFLE',
ids = {
'COMPONENT_AT_AR_FLSH',
'COMPONENT_AT_AR_AFGRIP',
'COMPONENT_AT_SCOPE_MEDIUM'
}
},
{
gun = 'WEAPON_PUMPSHOTGUN',
ids = {
'COMPONENT_AT_AR_FLSH'
}
}
}
},
['/firefighter'] = {
skin = 's_m_y_fireman_01',
guns = {
'WEAPON_STUNGUN',
'WEAPON_FIREEXTINGUISHER',
'WEAPON_FLARE',
'WEAPON_FLAREGUN',
'WEAPON_PETROLCAN',
'WEAPON_FLASHLIGHT'
},
attachements = {} -- Supplying an empty table of attachements means that it won't add any attachements
},
['/paramedic'] = {
skin = 's_m_m_paramedic_01',
guns = {
'WEAPON_STUNGUN',
'WEAPON_FLARE',
'WEAPON_FLAREGUN',
'WEAPON_FLASHLIGHT'
},
attachements = {}
},
['/default'] = {
skin = 'a_m_y_skater_01',
guns = {}, -- Supplying an empty table of guns means it removes all of the weapons
attachements = {}
}
}
|
RoleManager = RoleManager or BaseClass(BaseHotUpdate)
function RoleManager:__init()
if RoleManager.Instance then
ErrorLog("[RoleManager] Attemp to create a singleton twice !")
end
RoleManager.Instance = self
end
function RoleManager:__delete()
RoleManager.Instance = nil
end
function RoleManager:GetRoleByCRole(c_role)
if nil == c_role then
return nil
end
local role_id = c_role:GetUID()
return self:GetObject(role_id)
end
function RoleManager:GetRoleById(role_id)
return self:GetObject(role_id)
end
function RoleManager:OnAddRole(role_id, c_role)
if role_id <= 0 or nil == c_role then
return
end
self:DeleteRole(role_id)
role = self:CreateDynamicObject(role_id, Role, c_role)
Log(string.format("%d create role!", role_id))
end
function RoleManager:DeleteRole(role_id)
if nil == self:GetRoleById(role_id) then
return
end
self:DeleteObject(role_id)
Log(string.format("%d delete role!", role_id))
end
function RoleManager:OnDestoryRole(role_id)
local role = self:GetRoleById(role_id)
if nil == role then
return
end
role:DestoryC()
self:DeleteRole(role_id)
Log(string.format("%d destory role!", role_id))
end
function RoleManager:ReCalcRoleAttr(roleid, c_base_attr_add, recalc_reason, recalc_all)
local role = self:GetRoleById(roleid)
if nil == role then
return
end
role:GetLingyu():ReCalcAttr(c_base_attr_add, RECALC_REASON_TYPE.LINGYU == recalc_reason or recalc_all)
role:GetTianxiangeFb():ReCalcAttr(c_base_attr_add, RECALC_REASON_TYPE.TIANXIANGEFB == recalc_reason or recalc_all)
end
function RoleManager:OnRoleLogout(role_id)
local role = self:GetRoleById(role_id)
if nil ~= role then
role:OnRoleLogout()
end
end
function RoleManager:OnResetData(roleid, old_dayid, now_dayid)
local role = self:GetRoleById(roleid)
if nil ~= role then
role:OnResetData(old_dayid, now_dayid)
end
end
function RoleManager:OnRoleDieInStaticScene(role_id, killer_id)
local role = self:GetRoleById(role_id)
if nil ~= role then
role:OnDieInStaticScene(killer_id)
end
end
|
local util = require "formatter.util"
return function(lang)
return {
exe = "prettydiff",
args = {
util.format_prettydiff_arg("mode", "beautify"),
util.format_prettydiff_arg("lang", lang),
util.format_prettydiff_arg("readmethod", "filescreen"),
util.format_prettydiff_arg("endquietly", "quiet"),
util.format_prettydiff_arg("source", util.get_current_buffer_file_path()),
},
no_append = true,
}
end
|
RegisterNetEvent('ND_hospital:client:FinishServices')
AddEventHandler('ND_hospital:client:FinishServices', function(h, wasLucky)
if h and usedHiddenRev then return end
local player = PlayerPedId()
if IsPedDeadOrDying(player) then
local playerPos = GetEntityCoords(player, true)
NetworkResurrectLocalPlayer(playerPos, true, true, false)
end
if wasLucky then
SetEntityHealth(player, GetEntityMaxHealth(player))
ClearPedBloodDamage(player)
SetPlayerSprint(PlayerId(), true)
ResetAll()
else
SetEntityHealth(player, 110)
end
if h then
usedHiddenRev = true
DoScreenFadeIn(1000)
else
LeaveBed()
end
end)
|
local resource_autoplace = require("resource-autoplace")
resource_autoplace.initialize_patch_set("titanium-ore", true)
data:extend(
{
{
type = "resource",
name = "titanium-ore",
icon = "__spicy-teeth-core_assets__/graphics/icons/titanium-ore.png",
icon_size = 32,
flags = {"placeable-neutral"},
order = "a-b-b",
tree_removal_probability = 0.8,
tree_removal_max_distance = 32 * 32,
minable =
{
mining_particle = "titanium-ore-particle",
mining_time = 1,
result = "titanium-ore"
},
collision_box = {{-0.1, -0.1}, {0.1, 0.1}},
selection_box = {{-0.5, -0.5}, {0.5, 0.5}},
autoplace = resource_autoplace.resource_autoplace_settings
{
name = "titanium-ore",
order = "b",
base_density = 6,
has_starting_area_placement = true,
regular_rq_factor_multiplier = 1.10,
starting_rq_factor_multiplier = 0.9,
candidate_spot_count = 22, -- To match 0.17.50 placement
},
stage_counts = {15000, 9500, 5500, 2900, 1300, 400, 150, 80},
stages =
{
sheet =
{
filename = "__spicy-teeth-core_assets__/graphics/entity/titanium-ore/titanium-ore.png",
priority = "extra-high",
size = 64,
frame_count = 8,
variation_count = 8,
hr_version =
{
filename = "__spicy-teeth-core_assets__/graphics/entity/titanium-ore/hr-titanium-ore.png",
priority = "extra-high",
size = 128,
frame_count = 8,
variation_count = 8,
scale = 0.5
}
}
},
map_color = {0.800, 0.650, 0.400}
}
}
)
|
local awful = require('awful')
local wibox = require('wibox')
local gears = require('gears')
local beautiful = require('beautiful')
local dpi = beautiful.xresources.apply_dpi
local clickable_container = require('widget.clickable-container')
local icons = require('theme.icons')
local create_widget = function()
local exit_widget = wibox.widget {
{
{
widget = wibox.widget.imagebox,
image = icons.logout,
resize = true
},
margins = dpi(9),
widget = wibox.container.margin
},
layout = wibox.layout.align.vertical
}
local exit_button = wibox.widget {
exit_widget,
widget = clickable_container
}
exit_button:buttons(
awful.util.table.join(
awful.button(
{},
1,
nil,
function()
awesome.emit_signal('module::exit_screen:show')
end
)
)
)
awful.tooltip(
{
objects = {exit_button},
mode = 'outside',
align = 'right',
margin_leftright = dpi(8),
margin_topbottom = dpi(8),
text = 'End Session',
preferred_positions = {'right', 'left', 'top', 'bottom'}
}
)
return exit_button
end
return create_widget
|
includeFile("custom_content/draft_schematic/space/engine/collection_reward_engine_01_mk1.lua")
includeFile("custom_content/draft_schematic/space/engine/collection_reward_engine_01_mk2.lua")
includeFile("custom_content/draft_schematic/space/engine/collection_reward_engine_01_mk3.lua")
includeFile("custom_content/draft_schematic/space/engine/collection_reward_engine_01_mk4.lua")
includeFile("custom_content/draft_schematic/space/engine/collection_reward_engine_01_mk5.lua")
includeFile("custom_content/draft_schematic/space/engine/elite_engine.lua")
includeFile("custom_content/draft_schematic/space/engine/engine_overhaul_mk1.lua")
includeFile("custom_content/draft_schematic/space/engine/engine_overhaul_mk2.lua")
includeFile("custom_content/draft_schematic/space/engine/engine_stabilizer_mk1.lua")
includeFile("custom_content/draft_schematic/space/engine/engine_stabilizer_mk2.lua")
includeFile("custom_content/draft_schematic/space/engine/eng_elite_mk2.lua")
includeFile("custom_content/draft_schematic/space/engine/eng_reward_experimental.lua")
includeFile("custom_content/draft_schematic/space/engine/nova_eng_01.lua")
includeFile("custom_content/draft_schematic/space/engine/orion_eng_01.lua")
|
local skynet = require "skynet"
local s = require "service"
local socket = require "skynet.socket"
local cluster = require "skynet.cluster"
local runconfig = require "runconfig"
-- 保存客户端连接
local conns = {} -- [fd] = conn
-- 保存已登录玩家信息
local players = {} -- [playerid] = gateplayer
local function conn()
local m = {
fd = nil,
playerid = nil,
}
return m;
end
local function gateplayer()
local m = {
playerid = nil,
agent = nil,
conn = nil,
}
return m;
end
local function disconnect(fd)
local conn = conns[fd]
if not conn then
return
end
local playerid = conn.playerid
-- 还未完成登录就下线
if not playerid then
return
-- 已经在游戏中
else
players[playerid] = nil
local reason = "断线"
cluster.call("agentmgr", "lua", "reqkick", playerid, reason)
end
end
-- unpack msg
-- 字符串协议格式,每条消息由“\r\n”作为结束符,
-- 消息的各个参数用英文逗号分隔,第一个参数代表消息名称。
local function str_unpack(msgstr)
local msg = {}
while true do
local arg, rest = string.match( msgstr,"(.-),(.*)" )
if arg then
msgstr = rest
table.insert( msg, arg )
else
table.insert( msg, msgstr )
break
end
end
-- cmd, {cmd, ...}
return msg[1], msg
end
-- pack msg
local function str_pack(cmd, msg)
return table.concat( msg, "," ).."\r\n"
end
local function random_login()
local node = skynet.getenv("node")
local nodecfg = runconfig[node]
local id = math.random( 1, #nodecfg.login )
return "login"..id
end
local function process_msg(fd, msgstr)
skynet.error("gateway"..s.id.." recv from ["..fd.."] msgstr "..msgstr)
local cmd, msg = str_unpack(msgstr)
if not cmd then
skynet.error("gateway recv from ["..fd.."] not cmd.")
return
end
local conn = conns[fd]
local playerid = conn.playerid
-- 尚未完成登录
if not playerid then
local login = random_login()
skynet.send(login, "lua", "client", fd, cmd, msg)
-- 已完成登录
else
local gplayer = players[playerid]
local agent = gplayer.agent
skynet.error("todo forword msg to the agent.")
-- skynet.send(agent, "lua", "client", cmd, msg)
end
end
local function process_buff(fd, readbuff)
while true do
local msgstr, rest = string.match( readbuff, "(.-)\r\n(.*)" )
if msgstr then
readbuff = rest
process_msg(fd, msgstr)
else
return readbuff
end
end
end
-- 每一条新连接接收数据处理
local function recv_loop(fd)
socket.start(fd)
skynet.error("socket connected "..fd)
local readbuff = ""
while true do
local recvstr = socket.read(fd)
if recvstr then
readbuff = readbuff..recvstr
readbuff = process_buff(fd, readbuff)
else
skynet.error("socket close "..fd)
disconnect(fd)
socket.close(fd)
return
end
end
end
-- 接收新连接
local function connect(fd, addr)
print("connect from "..addr.." "..fd)
local c = conn();
conns[fd] = c
c.fd = fd
skynet.fork(recv_loop, fd)
end
function s.init()
skynet.error("[start]"..s.name.." "..s.id)
local node = skynet.getenv("node")
local nodecfg = runconfig[node]
local port = nodecfg.gateway[s.id].port
local listenfd = socket.listen("0.0.0.0", port)
skynet.error("gateway listen socket : ", "0.0.0.0 ", port);
socket.start(listenfd, connect);
end
-- forward login message.
function s.resp.send_by_fd( source, fd, msg )
local c = conns[fd]
if not c then
return
end
skynet.error("gateway "..s.id.." send "..fd.."["..msg[1].."] {"..table.concat( msg, "," ))
socket.write(fd, str_pack(msg[1], msg))
end
-- forward agent message.
function s.resp.send( source, playerid, msg )
local gplayer = players[playerid]
if not gplayer then
return
end
local c = gplayer.conn
if not c then
return
end
s.resp.send_by_fd(source, c.fd, msg)
end
-- login -> gateway
function s.resp.sure_agent( source, fd, playerid, agent )
local conn = conns[fd]
-- 登录过程中已经下线
if not conn then
cluster.call("agentmgr", "lua", "reqkick", playerid, "未完成登录即下线")
return false
end
conn.playerid = playerid
local gplayer = gateplayer()
gplayer.playerid = playerid
gplayer.agent = agent
gplayer.conn = conn
players[playerid] = gplayer
return true
end
-- agentmgr kick player.
function s.resp.kick( source, playerid )
local gplayer = players[playerid]
if not gplayer then
return
end
players[playerid] = nil
local conn = gplayer.conn
if not conn then
return
end
disconnect(conn.fd)
socket.close(conn.fd)
end
s.start(...)
|
require('actors/AI')
PlayerAI = class('PlayerAI', AI)
PlayerAI:includes(Beholder)
function PlayerAI:initialize()
super.initialize(self)
self._thrust = false
self._strafeLeft = false
self._strafeRight = false
self._fire = false
self:observe('keypressed_w', function(self) self._thrust = true end)
self:observe('keypressed_a', function(self) self._strafeLeft = true end)
self:observe('keypressed_d', function(self) self._strafeRight = true end)
self:observe('mousepressed_l', function(self) self._fire = true end)
self:observe('keyreleased_w', function(self) self._thrust = false end)
self:observe('keyreleased_a', function(self) self._strafeLeft = false end)
self:observe('keyreleased_d', function(self) self._strafeRight = false end)
self:observe('mousereleased_l', function(self) self._fire = false end)
end
function PlayerAI:wantsThrust()
return self._thrust
end
function PlayerAI:getStrafeDirection()
if(self._strafeLeft) then return 'left' end
if(self._strafeRight) then return 'right' end
return nil
end
function PlayerAI:getRotationDirection()
return self:orientateTowards(autoCamera:invert(love.mouse.getPosition()))
end
function PlayerAI:getWeaponsFired()
if(self._fire) then return self:getAllWeapons() end
return {}
end
|
class "ZombiesServer"
ZombiesTeamManager = require "ZombiesTeamManager"
ZombiesLogic = require "ZombiesLogic"
function ZombiesServer:__init()
self.m_TeamManager = ZombiesTeamManager()
self.m_GameLogic = ZombiesLogic()
self.m_UpdateEvent = Events:Subscribe("Engine:Update", self, self.OnUpdate)
self.m_SpawnEvent = Events:Subscribe('Player:SpawnOnSelectedSpawnPoint', self, self.OnSpawnOnSelectedSpawnPoint)
self.m_HumanCurrentDamage = 1.0
-- This shit crashes... rip, TODO: Bugfix within VU
--self.m_SoldierDamageHook = Hooks:Install('Soldier:DamageSimple', self, self.SoldierDamage)
ChatManager:SendMessage("Init")
end
function ZombiesServer:OnUpdate(p_Delta, p_SimulationDelta)
-- Call our game logic update function
self.m_GameLogic:OnUpdate(p_Delta, p_SimulationDelta)
local s_HumanCount = TeamSquadManager:GetTeamPlayerCount(TeamId.Team1)
local s_ZombieCount = TeamSquadManager:GetTeamPlayerCount(TeamId.Team2)
if s_HumanCount ~= 0 then
s_Calculation = s_ZombieCount / s_HumanCount
self.m_HumanCurrentDamage = math.min(2, s_Calculation)
end
end
function ZombiesServer:OnSpawnOnSelectedSpawnPoint(p_Player)
if p_Player == nil then
return
end
self.m_GameLogic:OnSpawnOnSelectedSpawnPoint(p_Player)
end
function ZombiesServer:SoldierDamage(p_Hook, p_Soldier, p_Giver, p_Damage, p_DamageOverTime, p_DamageType)
--print('Got damage event')
print("1")
if p_Soldier == nil or p_Damage == 10099.0 or p_Giver == nil then
return p_Hook:CallOriginal(p_Soldier, p_Giver, p_Damage, p_DamageOverTime, p_DamageType)
end
print("2")
--print('Getting player')
local s_Player = p_Soldier.player
if s_Player == nil then
return p_Hook:CallOriginal(p_Soldier, p_Giver, p_Damage, p_DamageOverTime, p_DamageType)
end
print("3")
if self.m_HumanCurrentDamage ~= 0 and p_Giver.teamID == TeamId.Team1 then
p_Damage = p_Damage * self.m_HumanCurrentDamage
end
--print(string.format('"%s" got %f (%f) damage of type %f.', s_Player.name, p_Damage, p_DamageOverTime, p_DamageType))
return p_Hook:CallOriginal(p_Soldier, p_Giver, p_Damage, p_DamageOverTime, p_DamageType)
end
g_AdminServer = ZombiesServer()
|
NewShipType = StartShipConfig()
NewShipType.displayedName="$10072"
NewShipType.sobDescription="$10073"
NewShipType.maxhealth=getShipNum(NewShipType, "maxhealth",26000)
NewShipType.regentime=0
NewShipType.minRegenTime=0
NewShipType.sideArmourDamage = getShipNum(NewShipType, "sideArmourDamage", 1.2)
NewShipType.rearArmourDamage = getShipNum(NewShipType, "rearArmourDamage", 1.2)
setTacticsMults(NewShipType, "ENGINEACCEL", 1.10, 0.90, 1.0)
setTacticsMults(NewShipType, "THRUSTERACCEL", 1.10, 0.90, 1.0)
setTacticsMults(NewShipType, "ROTATION", 0.95, 1.05, 1.0)
setTacticsMults(NewShipType, "ROTATIONACCEL", 1.10, 0.90, 1.0)
setTacticsMults(NewShipType, "FIRERATE", 0.98, 1.02, 1.0)
NewShipType.isTransferable=1
NewShipTypeuseEngagementRanges=1
NewShipType.defaultROE="Defensive"
NewShipType.defaultStance="Aggressive"
NewShipType.formationSpacing=250
NewShipType.mass=100
NewShipType.collisionMultiplier=1
NewShipType.thrusterMaxSpeed=125
NewShipType.mainEngineMaxSpeed=135
NewShipType.rotationMaxSpeed=40
NewShipType.thrusterAccelTime=7
NewShipType.thrusterBrakeTime=2
NewShipType.mainEngineAccelTime=8
NewShipType.mainEngineBrakeTime=2
NewShipType.rotationAccelTime=0.4
NewShipType.rotationBrakeTime=0.2
NewShipType.thrusterUsage=0.5
NewShipType.accelerationAngle=40
NewShipType.mirrorAngle=0
NewShipType.secondaryTurnAngle=0
NewShipType.maxBankingAmount=20
NewShipType.descendPitch=20
NewShipType.goalReachEpsilon=30
NewShipType.slideMoveRange=100
NewShipType.controllerType="Ship"
NewShipType.tumbleStaticX=10
NewShipType.tumbleStaticY=20
NewShipType.tumbleStaticZ=5
NewShipType.tumbleDynamicX=2
NewShipType.tumbleDynamicY=10
NewShipType.tumbleDynamicZ=5
NewShipType.tumbleSpecialDynamicX=2
NewShipType.tumbleSpecialDynamicY=10
NewShipType.tumbleSpecialDynamicZ=5
NewShipType.relativeMoveFactor=3
setTargetBox(NewShipType, 0, -0.3,-0.3,-0.7, 0.3,0.3,0.7)
NewShipType.useLayoutBounds=1
NewShipType.layoutBoundX=110
NewShipType.layoutBoundY=70
NewShipType.layoutBoundZ=110
NewShipType.layoutCenterX=0
NewShipType.layoutCenterY=0
NewShipType.layoutCenterZ=25
NewShipType.dustCloudDamageTime=160
NewShipType.nebulaDamageTime=200
NewShipType.MinimalFamilyToFindPathAround="MotherShip"
NewShipType.BuildFamily="Frigate_Tur"
NewShipType.AttackFamily="Frigate"
NewShipType.DockFamily="Frigate"
NewShipType.AvoidanceFamily="Frigate"
NewShipType.DisplayFamily="Frigate"
NewShipType.AutoFormationFamily="Frigate"
NewShipType.CollisionFamily="Big"
NewShipType.ArmourFamily=getShipStr(NewShipType, "ArmourFamily", "MediumArmour")
setSupplyValue(NewShipType, "Frigate", 1.0)
setSupplyValue(NewShipType, "LayoutFrigate", 1.0)
NewShipType.fighterValue=0
NewShipType.corvetteValue=0
NewShipType.frigateValue=12
NewShipType.neutralValue=0
NewShipType.antiFighterValue=0
NewShipType.antiCorvetteValue=0
NewShipType.antiFrigateValue=12
NewShipType.buildCost=800
NewShipType.buildTime=70
NewShipType.buildPriorityOrder=40
NewShipType.retaliationRange=5500
NewShipType.retaliationDistanceFromGoal=160
NewShipType.visualRange=1000
NewShipType.prmSensorRange=5000
NewShipType.secSensorRange=6000
NewShipType.detectionStrength=1
NewShipType.TOIcon="Diamond"
NewShipType.TOScale=1
NewShipType.TODistanceFade0=9000
NewShipType.TODistanceDisappear0=7000
NewShipType.TODistanceFade1=4500
NewShipType.TODistanceDisappear1=3500
NewShipType.TODistanceFade2=12000
NewShipType.TODistanceDisappear2=35000
NewShipType.TOGroupScale=1
NewShipType.TOGroupMergeSize=0
NewShipType.mouseOverMinFadeSize=0.045
NewShipType.mouseOverMaxFadeSize=0.1
NewShipType.healthBarStyle=1
NewShipType.nlips=0.000125
NewShipType.nlipsRange=6000
NewShipType.nlipsFar=0.0001
NewShipType.nlipsFarRange=10000
NewShipType.SMRepresentation="HardDot"
NewShipType.meshRenderLimit=14000
NewShipType.dotRenderLimit=10
NewShipType.visibleInSecondary=1
NewShipType.minLOD=0.25
NewShipType.goblinsStartFade=1540
NewShipType.goblinsOff=1540
NewShipType.minimumZoomFactor=0.6
NewShipType.selectionLimit=150000
NewShipType.preciseATILimit=0
NewShipType.selectionPriority=75
NewShipType.militaryUnit=1
addAbility(NewShipType,"MoveCommand",1,0);
addAbility(NewShipType,"CanDock",1,0);
NewShipType.dockTimeBetweenTwoFormations=1
NewShipType.dockTimeBeforeStart=2
NewShipType.dockNrOfShipsInDockFormation=1
NewShipType.dockFormation="delta"
NewShipType.queueFormation="dockline"
NewShipType.dontDockWithOtherRaceShips=1
NewShipType.ignoreRaceWhenDocking=0
addAbility(NewShipType,"CanLaunch");
NewShipType.launchTimeBetweenTwoFormations=1
NewShipType.launchTimeBeforeStart=2
NewShipType.launchNrOfShipsInDockFormation=1
NewShipType.launchFormation="delta"
addAbility(NewShipType,"ParadeCommand",1);
addAbility(NewShipType,"WaypointMove");
if hypBool == 1 then
addAbility(NewShipType,"HyperSpaceCommand",1,1,200,500,0,3);
end
addAbility(NewShipType,"CanAttack",1,1,0,1,0.35,1.5,"Capturer, Frigate, SmallCapitalShip, BigCapitalShip, Mothership, Utility, Corvette, Corvette_hw1, Fighter, Fighter_hw1","Frontal",
{SubSystem="FrontalVsSubSystem"},
{Fighter="frontal_vs_fighter"},
{Fighter_hw1="frontal_vs_fighter"},
{Corvette="frontal_vs_fighter"},
{Corvette="frontal_vs_fighter"});
addAbility(NewShipType,"GuardCommand",1,3000,600);
if hypBool == 1 then
addAbility(NewShipType,"HyperspaceViaGateCommand",1,3,1,0.3);
end
addAbility(NewShipType,"CanBeSalvageCaptured",0,1,0,0,1,"SalCap");
addAbility(NewShipType,"CanBeRepaired");
addAbility(NewShipType,"RetireAbility",1,0);
LoadSharedModel(NewShipType,"Tur_IonArrayFrigate");
StartShipWeaponConfig(NewShipType,"Tur_IonCannon","Weapon_Gun0","Weapon_Gun0");
addShield(NewShipType,"EMP",310,20);
NewShipType.battleScarCoverage=2
NewShipType.battleScarBudgetLow = 400
NewShipType.battleScarBudgetNext = 600
NewShipType.sobDieTime=1.9
NewShipType.sobSpecialDieTime=1
NewShipType.specialDeathSpeed=40
NewShipType.chanceOfSpecialDeath=0
NewShipType.deadSobFadeTime=0
NewShipType.trailLinger=4
setEngineBurn(NewShipType,6,1,1.5,60,1.1,0.1,0.25,120);
setEngineGlow(NewShipType,1,1,1.02,20,300,50,1.5,{0.27, 0.47, .69, 0.25});
loadLatchPointList(NewShipType,"SalCap","CapturePoint0","CapturePoint1");
loadShipPatchList(NewShipType,"data:sound/sfx/ship/",0,"Hiigaran/Frigate/Engines/HFrigateEng","",1,"misc/chatter/turanicraider","");
NewShipType.minFalloffDamageDist=100
NewShipType.maxFalloffDamageDist=100*2
NewShipType.maxFalloffScuttleDamageDist=100*4
NewShipType.explosiveScuttleDamageOnDeath=975
NewShipType.maxFalloffForce=500*10
NewShipType.explosiveDamageOnDeath=195
NewShipType.radiusDamageEvadeMod=1.1
NewShipType.strikeGroupSpeed=5000
NewShipType.canSurround=1
|
function onCreate()
-- background shit
makeLuaSprite('BG', 'black', -800, -800);
scaleObject('BG', 5, 5);
addLuaSprite('BG', false);
end
function onCreate ()
--background cuz yeah why not?
makeLuaSprite('BG2', 'sansbackgroundomfg', -800, -800);
scaleObject('BG2', 5, 5);
setProperty('BG2.antialiasing', true);
setProperty('BG2.visible', false);
makeLuaSprite('BG3', 'hdsansbackgroundnfw', -375, -325);
scaleObject('BG3', 0.9, 0.9);
setProperty('BG3.visible', false);
addCharacterToList('bf-pixel', 'boyfriend')
addCharacterToList('sans-pixel', 'dad')
addCharacterToList('bf', 'boyfriend')
addCharacterToList('sans', 'dad')
setCharacterX('dad', -100);
precacheImage('hdsansbackgroundnfw');
addLuaSprite('BG2', false);
addLuaSprite('BG3', false);
end
function onStepHit()
if curStep == 4 then
triggerEvent('Change Character', 'bf', 'bf');
triggerEvent('Change Character', 'dad', 'sans');
triggerEvent('noteskinchange', 'NOTE_assets_normal', '');
setProperty('BG.visible', false);
setProperty('BG3.visible', true);
end
if curStep == 8 then
triggerEvent('Change Character', 'bf', 'nobody');
triggerEvent('Change Character', 'dad', 'nobody');
setProperty('BG.visible', true);
setProperty('BG3.visible', false);
end
if curStep == 12 then
triggerEvent('Change Character', 'bf', 'bf-pixel');
triggerEvent('Change Character', 'dad', 'sans-pixel');
setProperty('BG.visible', false);
setProperty('BG2.visible', true);
end
if curStep == 272 then
triggerEvent('Change Character', 'bf', 'bf');
triggerEvent('Change Character', 'dad', 'sans');
setProperty('BG2.visible', false);
setProperty('BG3.visible', true);
end
if curStep == 527 then
triggerEvent('Change Character', 'bf', 'bf-pixel');
triggerEvent('Change Character', 'dad', 'sans-pixel');
setProperty('BG2.visible', true);
setProperty('BG3.visible', false);
end
if curStep == 655 then
triggerEvent('Change Character', 'bf', 'bf');
triggerEvent('Change Character', 'dad', 'sans');
setProperty('BG2.visible', false);
setProperty('BG3.visible', true);
end
if curStep == 784 then
triggerEvent('Change Character', 'bf', 'bf-pixel');
triggerEvent('Change Character', 'dad', 'sans-pixel');
setProperty('BG2.visible', true);
setProperty('BG3.visible', false);
end
if curStep == 912 then
triggerEvent('Change Character', 'bf', 'bf');
triggerEvent('Change Character', 'dad', 'sans');
setProperty('BG2.visible', false);
setProperty('BG3.visible', true);
end
end
|
AddCSLuaFile()
SWEP.PrintName = "BW Keys"
SWEP.Slot = 0
SWEP.SlotPos = 3
SWEP.DrawAmmo = false
SWEP.DrawCrosshair = false
SWEP.ViewModelFOV = 62
SWEP.ViewModelFlip = false
SWEP.Spawnable = false
SWEP.AdminSpawnable = false
SWEP.Primary.ClipSize = -1
SWEP.Primary.DefaultClip = 0
SWEP.Primary.Automatic = false
SWEP.Primary.Ammo = ""
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = 0
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = ""
function SWEP:Initialize()
self:SetWeaponHoldType("normal")
end
local function ValidateDoor(pl,door)
if (CLIENT) then return false end
if (!IsValid(door)) then return false end
if (door:GetPos():Distance(pl:GetPos()) > 100) then return false end
if (!door:GetClass():find("_door_")) then return false end
return true
end
function SWEP:PrimaryAttack()
if (CLIENT) then return end
local tr = self.Owner:GetEyeTrace()
if (!ValidateDoor(self.Owner,tr.Entity)) then return end
tr.Entity:Fire("lock", "", 0)
tr.Entity:EmitSound( "doors/door_latch1.wav" )
self:SetNextPrimaryFire(CurTime() + 0.5)
end
function SWEP:SecondaryAttack()
if (CLIENT) then return end
local tr = self.Owner:GetEyeTrace()
if (!ValidateDoor(self.Owner,tr.Entity)) then return end
tr.Entity:Fire("unlock", "", 0)
tr.Entity:EmitSound( "doors/door_latch3.wav" )
self:SetNextSecondaryFire(CurTime() + 0.5)
end
function SWEP:DrawWorldModel()
end
function SWEP:PreDrawViewModel()
return true
end
|
-- first entry is tech id to use if the player has none of the upgrades in the list
local kIndexToUpgrades =
{
{ kTechId.Shell, kTechId.Vampirism, kTechId.Carapace, kTechId.Regeneration },
{ kTechId.Spur, kTechId.Silence, kTechId.Celerity, kTechId.Adrenaline },
{ kTechId.Veil, kTechId.Camouflage, kTechId.Aura, kTechId.Focus },
}
debug.setupvaluex( GUIUpgradeChamberDisplay.Update, "kIndexToUpgrades", kIndexToUpgrades, true)
|
CLASS.name = "Doctor"
CLASS.faction = FACTION_CITIZEN
CLASS.salary = 230
CLASS.business = {
}
CLASS.weapons = {
"weapon_healer",
}
CLASS.limit = 3
CLASS.business = {
-- Foods
["aidkit"] = 1,
["healthkit"] = 1,
["healvial"] = 1,
}
CLASS.color = Color(47, 79, 79)
function CLASS:onSet(client)
for k, v in ipairs(self.weapons) do
client:Give(v)
end
end
CLASS_DOCTOR = CLASS.index
|
local export = {}
--[=[
[[Unsupported titles]] and pages with high
memory usage are listed at [[Module:links/data]].
Other modules used:
[[Module:script utilities]]
[[Module:scripts]]
[[Module:languages]] and its submodules
[[Module:gender and number]]
[[Module:utilities]]
[[Module:string]]
[[Module:debug]]
]=]
-- These are prefixed with u to avoid confusion with the default string methods
-- of the same name.
local usub = mw.ustring.sub
local table_insert = table.insert
local table_concat = table.concat
local ignore_cap = {
["ko"] = true,
}
local phonetic_extraction = {
["th"] = "Module:th",
["km"] = "Module:km",
}
local pos_tags = {
["a"] = "adjective",
["adv"] = "adverb",
["int"] = "interjection",
["n"] = "noun",
["pron"] = "pronoun",
["v"] = "verb",
["vi"] = "intransitive verb",
["vt"] = "transitive verb",
["vti"] = "transitive and intransitive verb",
}
local unsupported_titles
function export.getLinkPage(target, lang)
unsupported_titles = unsupported_titles or mw.loadData("Module:links/data").unsupported_titles
if unsupported_titles[target] then
return "Unsupported titles/" .. unsupported_titles[target]
end
-- If the link contains unexpanded template parameters, then don't create a link.
if target:find("{{{") then
return nil
end
if target:sub(1, 1) == ":" or target:sub(1, 2) == "w:" or target:sub(1, 10) == "wikipedia:" then
return target
end
-- Remove diacritics from the page name
target = lang:makeEntryName(target)
if target:sub(1, 1) == "/" then
return ":" .. target
-- Link to appendix for reconstructed terms and terms in appendix-only languages
elseif target:sub(1, 1) == "*" and #target > 1 then
if lang:getCode() == "und" then
return nil
end
target = "Reconstruction:" .. lang:getCanonicalName() .. "/" .. usub(target, 2)
elseif lang:getType() == "reconstructed" then
error("The specified language " .. lang:getCanonicalName()
.. " is unattested, while the given word is not marked with '*' to indicate that it is reconstructed")
elseif lang:getType() == "appendix-constructed" then
target = "Appendix:" .. lang:getCanonicalName() .. "/" .. target
end
return target
end
-- Make a language-specific link from given link's parts
local function makeLangLink(link, lang, id, allow_self_link)
-- Temporary tracking code
local langCode = lang:getCode()
if langCode == "se" or langCode == "sia" or langCode:find("^sm[ajns]$")
or langCode:find("^sj[dektu]$") then
if link.display and link.display:find("'") then
require("debug").track("links/Sami apostrophe display")
elseif link.target and link.target:find("'") then
require("debug").track("links/Sami apostrophe target")
end
end
-- Find fragments (when link didn't come from parseLink).
-- Prevents {{l|en|word#Etymology 2|word}} from linking to [[word#Etymology 2#English]].
if link.fragment == nil then
-- Replace numeric character references with the corresponding character ( → '),
-- as they contain #, which causes the numeric character reference to be
-- misparsed (wa'a → waa → pagename wa&, fragment 29;a).
link.target = link.target:gsub("&#(%d+);",
function(number) return mw.ustring.char(tonumber(number)) end)
local first, second = link.target:match("^([^#]+)#(.+)$")
if first then
link.target, link.fragment = first, second
end
end
-- If there is no display form, then create a default one
if not link.display then
link.display = link.target
-- Strip the prefix from the displayed form
-- TODO: other interwiki links?
if link.display:sub(1, 1) == ":" and not mw.loadData("Module:links/data").unsupported_titles[link.display] then
link.display = link.display:sub(2) -- remove colon from beginning
else
local prefix = link.display:match("^([^:]+):")
local prefixes = {
w = true,
wikipedia = true,
}
if prefixes[prefix] then
link.display = link.display:sub(#prefix + 2) -- remove prefix plus colon
end
end
end
-- Process the target
link.target = export.getLinkPage(link.target, lang)
if not link.target then
return link.display
end
-- If the target is the same as the current page and there is no sense id
-- and linking to the same page hasn't been turned on, then return a "self-link"
-- like the software does.
if not (allow_self_link or id) and link.target:gsub("^:", "") == mw.title.getCurrentTitle().prefixedText then
return "<strong class=\"selflink\">" .. link.display .. "</strong>"
end
--[[
Add fragment
Do not add a section link to "Undetermined", as such sections do not exist and are invalid.
TabbedLanguages handles links without a section by linking to the "last visited" section,
but adding "Undetermined" would break that feature.
For localized prefixes that make syntax error, please use the format: ["xyz"] = true,
]]
local prefix = link.target:match("^:?([^:]+):")
local prefixes = {
w = true,
wikipedia = true,
Category = true,
}
if not prefixes[prefix] then
if link.fragment or link.target:find("#$") then
require("debug").track {
"links/fragment",
"links/fragment/" .. lang:getCode()
}
end
if not link.fragment and lang:getCode() ~= "und" then
if id then
link.fragment = require("senseid").anchor(lang, id)
elseif not mw.ustring.find(link.target, "^Appendix:")
and not mw.ustring.find(link.target, "^Reconstruction:") then
link.fragment = lang:getCanonicalName()
end
end
-- This allows linking to pages like [[sms:a]] without it being treated weirdly.
link.target = link.target:gsub(":", ":")
end
return "[[" .. link.target .. (link.fragment and "#" .. link.fragment or "") .. "|" .. link.display .. "]]"
end
-- Split a link into its parts
local function parseLink(linktext)
local link = { target = linktext }
local first, second = link.target:match("^([^|]+)|(.+)$")
if first then
link.target = first
link.display = second
else
link.display = link.target
end
first, second = link.target:match("^(.+)#(.+)$")
if first then
link.target = first
link.fragment = second
else
-- So that makeLangLink does not look for a fragment again
link.fragment = false
end
return link
end
-- Creates a basic wikilink to the given term. If the text already contains
-- links, these are replaced with links to the correct section.
function export.language_link(data, allow_self_link)
if type(data) ~= "table" then
error("The first argument to the function language_link must be a table. See Module:links/documentation for more information.")
end
local text = data.term
if ignore_cap[data.lang:getCode()] and text then
text = text:gsub("%^", "")
end
-- If the text begins with * and another character,
-- then act as if each link begins with *
local allReconstructed = false
if text:find("^*.") then
allReconstructed = true
end
-- Do we have embedded wikilinks?
if text:find("[[", nil, true) then
--[=[
[[Special:WhatLinksHere/Template:tracking/links/alt-ignored]]
[[Special:WhatLinksHere/Template:tracking/links/id-ignored]]
]=]
if data.alt then
require("debug").track("links/alt-ignored")
mw.log("(from Module:links)", "text with embedded wikilinks:", text,
"ignored alt:", data.alt, "lang:", data.lang:getCode())
end
if data.id then
require("debug").track("links/id-ignored")
mw.log("(from Module:links)", "text with embedded wikilinks:", text,
"ignored id:", data.id, "lang:", data.lang:getCode())
end
-- Begins and ends with a wikilink tag
if text:find("^%[%[(.+)%]%]$") then
-- There are no [ ] in between.
-- This makes the wikilink tag redundant.
if text:find("^%[%[[^%[%]]+%]%]$") then
require("debug").track("links/redundant wikilink")
else
local temp = text:gsub("^%[%[(.+)%]%]$", "%1")
temp = temp:gsub("%]%], %[%[", "|")
if not temp:find("[%[%]]") then
require("debug").track("links/list")
end
end
end
text = text:gsub("%[%[([^%]]+)%]%]",
function(linktext)
local link = parseLink(linktext)
if allReconstructed then
link.target = "*" .. link.target
end
return makeLangLink(link, data.lang, data.id, allow_self_link)
end)
-- Remove the extra * at the beginning if it's immediately followed
-- by a link whose display begins with * too
if allReconstructed then
text = text:gsub("^%*%[%[([^|%]]+)|%*", "[[%1|*")
end
else
-- There is no embedded wikilink, make a link using the parameters.
text = makeLangLink({ target = text, display = data.alt }, data.lang, data.id, allow_self_link)
end
return text
end
function export.mark(text, itemType, face, lang)
local tag = { "", "" }
if itemType == "gloss" then
tag = { '<span class="mention-gloss-double-quote">“</span><span class="mention-gloss">',
'</span><span class="mention-gloss-double-quote">”</span>' }
elseif itemType == "tr" then
if face == "term" then
tag = { '<span lang="' .. lang:getCode() .. '" class="tr mention-tr Latn">',
'</span>' }
else
tag = { '<span lang="' .. lang:getCode() .. '" class="tr Latn">', '</span>' }
end
elseif itemType == "ts" then
tag = { '<span class="ts mention-ts Latn">/', '/</span>' }
elseif itemType == "pos" then
tag = { '<span class="ann-pos">', '</span>' }
elseif itemType == "annotations" then
tag = { '<span class="mention-gloss-paren annotation-paren">(</span>',
'<span class="mention-gloss-paren annotation-paren">)</span>' }
end
if type(text) == "string" then
return tag[1] .. text .. tag[2]
else
return ""
end
end
-- Format the annotations (things following the linked term)
function export.format_link_annotations(data, face)
local output = {}
-- Interwiki link
if data.interwiki then
table_insert(output, data.interwiki)
end
-- Genders
if type(data.genders) ~= "table" then
data.genders = { data.genders }
end
if data.genders and #data.genders > 0 then
local m_gen = require("gender and number")
table_insert(output, " " .. m_gen.format_list(data.genders, data.lang))
end
local annotations = {}
-- Transliteration and transcription
if data.tr or data.ts then
local kind
if face == "term" then
kind = face
else
kind = "default"
end
if data.tr and data.ts then
table_insert(annotations,
require("script utilities").tag_translit(data.tr, data.lang, kind)
.. " " .. export.mark(data.ts, "ts"))
elseif data.ts then
table_insert(annotations, export.mark(data.ts, "ts"))
else
table_insert(annotations,
require("script utilities").tag_translit(data.tr, data.lang, kind))
end
end
-- Gloss/translation
if data.gloss then
table_insert(annotations, export.mark(data.gloss, "gloss"))
end
-- Part of speech
if data.pos then
-- debug category for pos= containing transcriptions
if data.pos:find("/[^><]*/") then
data.pos = data.pos .. "[[Category:links likely containing transcriptions in pos]]"
end
table_insert(annotations, export.mark(pos_tags[data.pos] or data.pos, "pos"))
end
-- Literal/sum-of-parts meaning
if data.lit then
table_insert(annotations, "literally " .. export.mark(data.lit, "gloss"))
end
if #annotations > 0 then
table_insert(output, " " .. export.mark(table_concat(annotations, ", "), "annotations"))
end
return table_concat(output)
end
-- A version of {{l}} or {{m}} that can be called from other modules too
function export.full_link(data, face, allow_self_link, no_check_redundant_translit)
if type(data) ~= "table" then
error("The first argument to the function full_link must be a table. "
.. "See Module:links/documentation for more information.")
end
-- Create the link
local output = {}
local categories = {}
local link = ""
local annotations
--local m_utilities = require("utilities")
-- Is there any text to show?
if (data.term or data.alt) then
-- Try to detect the script if it was not provided
if not data.sc then
data.sc = require("scripts").findBestScript(data.alt or data.term, data.lang)
else
-- Track uses of sc parameter
local best = require("scripts").findBestScript(data.alt or data.term, data.lang)
require("debug").track("links/sc")
if data.sc:getCode() == best:getCode() then
require("debug").track("links/sc/redundant")
require("debug").track("links/sc/redundant/" .. data.sc:getCode())
else
require("debug").track("links/sc/needed")
require("debug").track("links/sc/needed/" .. data.sc:getCode())
end
end
local class = ""
local function encode_accel_param(prefix, param)
-- This is decoded again by [[WT:ACCEL]].
return param and prefix .. param:gsub("%%", "."):gsub(" ", "_") or ""
end
if data.accel then
local form = data.accel.form and data.accel.form .. "-form-of" or ""
local gender = encode_accel_param("gender-", data.accel.gender)
local pos = encode_accel_param("pos-", data.accel.pos)
local translit = encode_accel_param("transliteration-", data.accel.translit)
local lemma = encode_accel_param("origin-", data.accel.lemma)
local lemma_translit = encode_accel_param("origin_transliteration-", data.accel.lemma_translit)
local no_store = data.accel.no_store and "form-of-nostore" or ""
local accel =
form .. " " ..
gender .. " " ..
pos .. " " ..
translit .. " " ..
lemma .. " " ..
lemma_translit .. " " ..
no_store .. " "
class = "form-of lang-" .. data.lang:getCode() .. " " .. accel
end
-- Only make a link if the term has been given, otherwise just show the alt text without a link
link = require("script utilities").tag_text(
data.term and export.language_link(data, allow_self_link)
or data.alt, data.lang, data.sc, face, class)
else
--[[ No term to show.
Is there at least a transliteration we can work from? ]]
link = require("script utilities").request_script(data.lang, data.sc)
if link == "" or not data.tr or data.tr == "-" then
-- No link to show, and no transliteration either. Show a term request.
local category = ""
if mw.title.getCurrentTitle().nsText ~= "Template" then
table_insert(categories, "[[Category:" .. data.lang:getCanonicalName() .. " term requests]]")
end
link = "<small>[Term?]</small>"
end
end
table_insert(output, link)
if data.tr == "" or data.tr == "-" then
data.tr = nil
elseif phonetic_extraction[data.lang:getCode()] then
local m_phonetic = require(phonetic_extraction[data.lang:getCode()])
data.tr = data.tr or m_phonetic.getTranslit(export.remove_links(data.term))
elseif (data.term or data.alt) and not data.sc:getCode():find("Lati?n") then
-- Try to generate a transliteration, unless transliteration has been supplied and either
-- no_check_redundant_translit is given or we are in a high-memory entry. (Checking for redundant
-- transliteration can use up significant amounts of memory so we don't want to do it if memory
-- is tight. `no_check_redundant_translit` is currently set when called ultimately from
-- {{multitrans|...|no-check-redundant-translit=1}}.)
if not (data.tr and (
no_check_redundant_translit or
mw.loadData("Module:links/data").high_memory_entries[mw.title.getCurrentTitle().text]
)) then
local automated_tr = data.lang:transliterate(export.remove_links(data.alt or data.term), data.sc)
if automated_tr then
local manual_tr = data.tr
if manual_tr then
if manual_tr == automated_tr then
table_insert(categories,
"[[Category:Terms with redundant transliterations]]"
.. "[[Category:Terms with redundant transliterations/" .. data.lang:getCode() .. "]]")
else
-- Prevents Arabic root categories from flooding the tracking categories.
if mw.title.getCurrentTitle().nsText ~= "Category" then
table_insert(categories,
"[[Category:Terms with manual transliterations different from the automated ones]]"
.. "[[Category:Terms with manual transliterations different from the automated ones/" .. data.lang:getCode() .. "]]")
end
end
end
if (not manual_tr) or data.lang:overrideManualTranslit() then
data.tr = automated_tr
end
end
end
end
-- Link to the transliteration entry for languages that require this
if data.tr and data.lang:link_tr() then
data.tr = export.language_link { lang = data.lang, term = data.tr }
end
table_insert(output, export.format_link_annotations(data, face))
return table_concat(output) .. table_concat(categories)
end
--[[ Strips links: deletes category links,
the targets of piped links,
and all double square brackets. ]]
function export.remove_links(text)
if type(text) == "table" then
text = text.args[1]
end
if not text or text == "" then
return ""
end
text = mw.ustring.gsub(text, "%[%[Category:[^|%]]-|?[^|%]]-%]%]", "")
text = text:gsub("%[%[[^|%]]-|", "")
text = text:gsub("%[%[", "")
text = text:gsub("%]%]", "")
return text
end
function export.english_links(text)
local lang = require("languages").getByCode("en")
-- Parentheses around function call to remove second return value, the
-- number of replacements.
return (text:gsub("%[%[([^%]]+)%]%]",
function(linktext)
local link = parseLink(linktext)
return makeLangLink(link, lang, nil, true, false)
end))
end
--[=[
For example, Norwegian_Bokm.C3.A5l → Norwegian_Bokmål. 0xC3 and 0xA5 are the
hexadecimal-base representation of the two bytes used to encode the character
å in the UTF-8 encoding:
11000011 10100101
Note that the bytes used to represent a character are actually different from
the Unicode codepoint. For å, the codepoint is 0xE5. The bits (digits) that
actually spell the codepoint are found in the brackets: 110[00011] 10[100101].
For further explanation, see [[w:UTF-8#Description]].
]=]
-- The character class %x should not be used, as it includes the characters a-f,
-- which do not occur in these anchor encodings.
local capitalHex = "[0-9A-F]"
local function decodeAnchor(anchor)
return (anchor:gsub("%.(" .. capitalHex .. capitalHex .. ")",
function(hexByte)
return string.char(tonumber(hexByte, 16))
end))
end
function export.section_link(link)
if type(link) ~= "string" then
error("The first argument to section_link was a " .. type(link) .. ", but it should be a string.")
end
link = link:gsub("_", " ")
local numberSigns = require("string").count(link, "#")
if numberSigns > 1 then
error("The section link should only contain one number sign (#).")
end
link = mw.uri.decode(link, "WIKI")
local page, section = link:match("^([^#]*)#(.+)$")
if page == "" then
page = nil
end
if section then
section = decodeAnchor(section)
-- URI-encode (percent-encode) section to allow square brackets and
-- other dodgy characters in section name.
-- If not percent-encoded, they prevent the parser from creating a link.
-- Decode percent-encoding in the displayed text
if page then
return "[[" .. page .. "#" .. mw.uri.encode(section, "WIKI")
.. "|" .. page .. " § " .. section .. "]]"
else
return "[[#" .. mw.uri.encode(section, "WIKI")
.. "|§ " .. section .. "]]"
end
else
error("The function “section_link” could not find a number sign marking a section name.")
end
end
return export
|
--
-- -- Copyright 2012 Rackspace
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
--
require "lunit"
module( "mongodb_opcounters", package.seeall, lunit.testcase )
local http_server
custom_arguments = { ipaddress = {'127.0.0.1'}, port = { 28019 } }
function equus_setup()
http_server = test_util.run_test_http_server('127.0.0.1', 28019, nil,
{ ['/_status'] = {
method = 'GET',
status_line = '200 OK',
content_type = 'application/json',
file = 'data/mongodb_response.json' }})
end
function equus_teardown()
test_util.kill_test_server(http_server)
end
function test_mongodb_opcounters()
assert_equal('A', check_result.availability)
assert_equal('G', check_result.state)
assert_equal('opcounters_delete', check_result.checks[1].name)
assert_equal('opcounters_insert', check_result.checks[2].name)
assert_equal('opcounters_command', check_result.checks[3].name)
assert_equal('opcounters_getmore', check_result.checks[4].name)
assert_equal('opcounters_update', check_result.checks[5].name)
assert_equal('opcounters_query', check_result.checks[6].name)
assert_equal('L', check_result.checks[1].type)
assert_equal('L', check_result.checks[2].type)
assert_equal('L', check_result.checks[3].type)
assert_equal('L', check_result.checks[4].type)
assert_equal('L', check_result.checks[5].type)
assert_equal('L', check_result.checks[6].type)
end
|
slot0 = class("FragmentShopPage", import(".ShamShopPage"))
slot0.getUIName = function (slot0)
return "FragmentShop"
end
slot0.GetPaintingCommodityUpdateVoice = function (slot0)
return
end
slot0.CanOpen = function (slot0, slot1, slot2)
return pg.SystemOpenMgr.GetInstance():isOpenSystem(slot2.level, "FragmentShop")
end
slot0.OnLoaded = function (slot0)
slot0.uilist = UIItemList.New(slot0:findTF("scrollView/view"), slot0:findTF("tpl"))
slot0.dayTxt = slot0:findTF("time/day"):GetComponent(typeof(Text))
slot0.fragment = slot0:findTF("res_fragment/count"):GetComponent(typeof(Text))
slot0.resolveBtn = slot0:findTF("res_fragment/resolve")
slot0.urRes = slot0:findTF("res_ur/count"):GetComponent(typeof(Text))
end
slot0.OnInit = function (slot0)
slot0.super.OnInit(slot0)
onButton(slot0, slot0.resolveBtn, function ()
if not slot0.resolvePanel then
slot0.resolvePanel = FragResolvePanel.New(slot0)
slot0.resolvePanel:Load()
end
slot0.resolvePanel.buffer:Reset()
slot0.resolvePanel.buffer.Reset.resolvePanel.buffer:Trigger("control")
end, SFX_PANEL)
onButton(slot0, slot0:findTF("res_fragment"), function ()
slot0:emit(BaseUI.ON_ITEM, id2ItemId(PlayerConst.ResBlueprintFragment))
end, SFX_PANEL)
onButton(slot0, slot0:findTF("res_ur"), function ()
slot0:emit(BaseUI.ON_ITEM, pg.gameset.urpt_chapter_max.description[1])
end, SFX_PANEL)
end
slot0.OnUpdatePlayer = function (slot0)
slot1 = slot0.player
slot0.fragment.text = slot0.player:getResource(PlayerConst.ResBlueprintFragment)
end
slot0.OnFragmentSellUpdate = function (slot0)
if slot0.resolvePanel then
slot0.resolvePanel.buffer:Reset()
slot0.resolvePanel.buffer:Trigger("control")
end
end
slot0.OnUpdateItems = function (slot0)
if not LOCK_UR_SHIP then
slot0.urRes.text = slot0.items[pg.gameset.urpt_chapter_max.description[1]] or {
count = 0
}.count
else
setActive(slot0:findTF("res_ur"), false)
setAnchoredPosition(slot0:findTF("res_fragment"), {
x = 938.5
})
end
end
slot0.OnUpdateCommodity = function (slot0, slot1)
slot0.cards[slot1.id].goodsVO = slot1
ActivityGoodsCard.StaticUpdate(slot0.cards[slot1.id].tr, slot1, slot0.TYPE_FRAGMENT)
end
slot0.AddCard = function (slot0, slot1, slot2)
ActivityGoodsCard.StaticUpdate(slot2, slot1, slot0.TYPE_FRAGMENT)
return {
goodsVO = slot1,
tr = slot2
}
end
slot0.OnPurchase = function (slot0, slot1, slot2)
slot0:emit(NewShopsMediator.ON_FRAGMENT_SHOPPING, slot1.id, slot2)
end
slot0.OnDestroy = function (slot0)
slot0.super.OnDestroy(slot0)
if slot0.resolvePanel then
slot0.resolvePanel:Destroy()
slot0.resolvePanel = nil
end
end
return slot0
|
return function(parent, dir)
local lgi = require 'lgi'
local Gtk = lgi.Gtk
local window = Gtk.Dialog {
title = "Gtk.SizeGroup",
transient_for = parent,
buttons = {
{ Gtk.STOCK_CLOSE, Gtk.ResponseType.NONE },
},
resizable = false,
on_response = Gtk.Widget.destroy,
}
window:get_content_area():add(
Gtk.Box {
orientation = 'VERTICAL',
border_width = 5,
spacing = 5,
Gtk.Frame {
label = "Color Options",
Gtk.Grid {
id = 'colors',
row_spacing = 5,
column_spacing = 10,
}
},
Gtk.Frame {
label = "Line Options",
Gtk.Grid {
id = 'lines',
row_spacing = 5,
column_spacing = 10,
}
},
Gtk.CheckButton {
id = 'enable_grouping',
label = "_Enable grouping",
use_underline = true,
active = true,
},
})
local size_group = Gtk.SizeGroup { mode = 'HORIZONTAL' }
local function add_row(grid, row, label, strings)
local combo = Gtk.ComboBoxText {}
for _, text in ipairs(strings) do
combo:append_text(text)
end
combo.active = 0
size_group:add_widget(combo)
grid:add {
left_attach = 0, top_attach = row,
Gtk.Label {
label = label,
use_underline = true,
halign = 'START',
valign = 'END',
hexpand = true,
mnemonic_widget = combo,
}
}
grid:add {
left_attach = 1, top_attach = row,
combo
}
end
add_row(window.child.colors, 0, "_Foreground", {
"Red", "Green", "Blue",
})
add_row(window.child.colors, 1, "_Background", {
"Red", "Green", "Blue",
})
add_row(window.child.lines, 0, "_Dashing", {
"Solid", "Dashed", "Dotted",
})
add_row(window.child.lines, 1, "_Line ends", {
"Square", "Round", "Arrow",
})
function window.child.enable_grouping:on_toggled()
size_group.mode = self.active and 'HORIZONTAL' or 'NONE'
end
window:show_all()
return window
end,
"Size Groups",
table.concat {
[[Gtk.SizeGroup provides a mechanism for grouping a number of widgets ]],
[[together so they all request the same amount of space. This is ]],
[[typically useful when you want a column of widgets to have the same ]],
[[size, but you can't use a Gtk.Grid widget.
]],
[[Note that size groups only affect the amount of space requested, ]],
[[not the size that the widgets finally receive. If you want ]],
[[the widgets in a Gtk.SizeGroup to actually be the same size, ]],
[[you need to pack them in such a way that they get the size they ]],
[[request and not more. For example, if you are packing your widgets ]],
[[into a grid, you would not include the 'FILL' flag.]],
}
|
local helpers = require("open-related.helpers")
local filename = require("open-related.helpers.filename")
local M = {}
M.alternate_header = helpers.make_builtin({
filetypes = { "cpp" },
related_to = filename.from_patterns({
{ match = "(.*).h$", format = "%s.cpp" },
{ match = "(.*).cpp$", format = "%s.h" },
}),
})
return M
|
-- MutantAlert
-- For when the AI has been alerted to something and is just going to investigate what it was
local Behavior = CreateAIBehavior("MutantAlert", "MutantBase",
{
Alertness = 0,
Constructor = function (self, entity)
self:Log("MutantAlert");
-- Search at least 10s.
entity.AI.allowLeave = false;
entity.AI.alertTimer = Script.SetTimerForFunction(10 * 1000.0, "AIBehavior.MutantAlert.ALERT_TIMER", entity);
self:Log("SelectPipe: mutant_alert");
entity:SelectPipe(0, "mutant_alert");
end,
Destructor = function(self, entity)
self:KillAlertTimer(entity);
end,
KillAlertTimer = function(self, entity)
if (entity.AI.alertTimer) then
Script.KillTimer(entity.AI.alertTimer);
end
end,
---------------------------------------------
ALERT_TIMER = function(entity, timerid)
Log("MutantAlert::ALERT_TIMER");
entity.AI.alertTimer = nil;
entity.AI.allowLeave = true;
local target = AI.GetAttentionTargetEntity(entity.id);
if (target == nil) then
AI.Signal(SIGNALFILTER_SENDER, 1, "ALERT_IDLE_LOOKAROUND", entity.id);
end
end,
ALERT_IDLE = function(self, entity)
self:Log("MutantAlert::ALERT_IDLE");
self:Log("SelectPipe: mutant_alert_idle"); -- want to look around at least once
entity:SelectPipe(0, "mutant_alert_idle");
end,
ALERT_IDLE_LOOKAROUND = function(self, entity)
self:Log("MutantAlert::ALERT_IDLE_LOOKAROUND");
if (entity.AI.allowLeave == true) then
self:GoBackToIdlePos(entity);
else
self:Log("SelectPipe: mutant_alert_idle");
entity:SelectPipe(0, "mutant_alert_idle");
end
end,
IDLEPOS_REACHED = function(self, entity)
self:Log("MutantAlert::IDLEPOS_REACHED");
AI.SetBehaviorVariable(entity.id, "Alerted", false);
end,
-- threats (all threats take us to seek mode)
OnEnemySeen = function(self, entity, fDistance, data)
self:Log("MutantAlert::OnEnemySeen");
self:EnterSeekBehavior(entity, distance);
end,
OnEnemyDamage = function(self, entity, distance, data)
self:Log("MutantAlert::OnEnemyDamage");
local enemy = System.GetEntity(data.id);
if (enemy) then
self:ForceLookAtEntity(entity, enemy);
end
self:EnterSeekBehavior(entity, distance);
end,
OnEnemyHeard = function(self, entity, distance)
self:Log("MutantAlert::OnEnemyHeard");
self:ForceLookAtTarget(entity); -- have to force as we're switching behaviors
self:EnterSeekBehavior(entity, distance);
end,
OnBulletRain = function(self, entity, sender, data)
self:Log("MutantAlert::OnBulletRain");
if (AI.Hostile(entity.id, data.id)) then -- only react to hostile bullets
self:EnterSeekBehavior(entity, distance);
end
end,
OnThreateningSeen = function(self, entity)
self:Log("MutantAlert::OnThreateningSoundHeard");
self:EnterSeekBehavior(entity, distance);
end,
OnThreateningSoundHeard = function(self, entity)
self:Log("MutantAlert::OnThreateningSoundHeard");
self:ForceLookAtTarget(entity);
self:EnterSeekBehavior(entity, distance);
end,
-- curiosities
InvestigatePosition = function(self, entity, distance)
self:Log("MutantAlert::InvestigatePosition");
if (entity.AI.allowLeave) then
local attPos = g_Vectors.temp_v1; -- needs to be initialized like this
AI.GetAttentionTargetPosition(entity.id, attPos);
AI.SetRefPointPosition(entity.id, attPos);
entity.AI.allowLeave = false;
entity.AI.alertTimer = Script.SetTimerForFunction(10 * 1000.0, "AIBehavior.MutantAlert.ALERT_TIMER", entity);
self:Log("SelectPipe: mutant_alert");
entity:SelectPipe(0, "mutant_alert");
end
end,
OnSomethingSeen = function(self, entity, distance, data)
self:Log("MutantAlert::OnSomethingSeen");
self:InvestigatePosition(entity, distance);
end,
OnObjectSeen = function(self, entity, distance, data)
self:Log("MutantAlert::OnObjectSeen");
self:InvestigatePosition(entity, distance);
end,
OnInterestingSoundHeard = function(self, entity)
self:Log("MutantAlert::OnInterestingSoundHeard");
self:InvestigatePosition(entity, distance);
end,
})
|
local foo = {}
function foo.load(x, w, h)
foo.win = false
foo.instruction = "Run!"
foo.x = x
foo.w = w
foo.h = h
end
function foo.keypressed(key, bindings)
end
function foo.update(dt, bindings)
if love.keyboard.isDown(bindings.pl.left) then
end
if love.keyboard.isDown(bindings.pl.right) then
end
if love.keyboard.isDown(bindings.pl.up) then
end
if love.keyboard.isDown(bindings.pl.down) then
end
if love.keyboard.isDown(bindings.pr.left) then
end
if love.keyboard.isDown(bindings.pr.right) then
end
if love.keyboard.isDown(bindings.pr.up) then
end
if love.keyboard.isDown(bindings.pr.down) then
end
end
function foo.draw()
love.graphics.printf("It Works", foo.x, foo.h / 2, foo.w, "center")
end
return foo
|
local length = table.getn(KEYS);
for i = 1, length, 1 do
redis.call("zincrby", KEYS[i], ARGV[1], ARGV[2])
end
return 1
|
help([[
Loads the Pythia environment
]])
local version = "8.2.3"
whatis("loads the Pythia environment")
prefix = "/opt/pythia8230"
if (depends_on) then
depends_on("root")
else
if (not isloaded("root")) then always_load("root") end
end
prepend_path("LD_LIBRARY_PATH", pathJoin(prefix, "/lib"))
prepend_path("DYLD_LIBRARY_PATH", pathJoin(prefix, "/lib"))
prepend_path("PATH", pathJoin(prefix, "/bin"))
prepend_path("PYTHONPATH", pathJoin(prefix, "/lib"))
|
Data={}
function Data.every() return "*" end
function Data.new (name)
local self = {}
local name = name
local nums = {} -- indexes of indepedendent numerics
local syms = {} -- indexes of indepedendent symbols
local dnums = {} -- indexes of depedendent numerics
local dsyms = {} -- indexes of depedendent symbols
local terms = {} -- table of terms a.k.a. attributes, features, columns
local rows = {} -- table or rows a.k.a. instaces, examples
function self.newTerm(x)
table.insert(terms,x)
table.insert(x.where,#terms)
end
return self
end
|
-- XMS_Tester_A.lua --
dofile( "XMS.lua" )
XMS_Tester_A = class( nil )
XMS_Tester_A.maxChildCount = 0
XMS_Tester_A.maxParentCount = 1
XMS_Tester_A.connectionInput = sm.interactable.connectionType.logic
XMS_Tester_A.connectionOutput = sm.interactable.connectionType.none
XMS_Tester_A.colorNormal = sm.color.new( 0x404040ff )
XMS_Tester_A.colorHighlight = sm.color.new( 0x606060ff )
function XMS_Tester_A.client_onCreate( self )
self.xmsManager = XMS_Manager("XMS_Tester_A")
end
function XMS_Tester_A.client_onSetupGui( self )
self.xmsManager:client_onSetupGui()
end
function XMS_Tester_A.client_onInteract( self )
self.xmsManager:setXMS(0, math.pi)
self.xmsManager:setXMS(1, true)
self.xmsManager:setXMS(2, "Lorem ipsum dolor")
self.xmsManager:setXMS(3, testfunction)
end
function testfunction()
print("This is a function printing the secret value: " .. secret_value) -- This will print "I don't like MLP" even if it's sent to a different mod.
end
secret_value = "I don't like MLP"
|
-- returns a function that, invoked with a delta, calls the callback
-- when the total time is reached. if provided, the elseCallback
-- will be invoked on each call with time < total.
local function timeout(total, callback, elseCallback, periodic)
local elapsed = 0
return function(dt)
elapsed = elapsed + dt
if elapsed >= total then
callback(total, dt, elapsed, total - elapsed)
if periodic then elapsed = 0 end
elseif elseCallback then
elseCallback(total, dt, elapsed, total - elapsed)
end
end
end
-- returns a function that, invoked with a delta, calls the callback
-- when the total time is reached, and then resets the elapsed time.
-- if provided, the elseCallback will be invoked on each call with time < total.
local function interval(total, callback, elseCallback)
return timeout(total, callback, elseCallback, true)
end
return {
timeout = timeout,
interval = interval,
}
|
CAchievement = {}
function CAchievement:new(player)
outputDebugString("CAchievement:new >> "..string.gsub(getPlayerName(player), "#%x%x%xx%x%x", ""), 0, 255, 180, 0)
dbQuery(CAchievement.constructor, {player}, g_Connection, "SELECT * FROM v_achievements WHERE `account_id` = ?", getElementData(player, "account_id"))
end
function CAchievement.constructor(query, player)
local result = dbPoll(query, 0)
if not result then
return outputDebugString("[Achievements] constructor failure")
end
g_PlayerAchievements[player] = {}
for _, row in pairs(result) do
local achievement_id = row.achievement_id
g_PlayerAchievements[player][achievement_id] = true
end
exports.v_mysql:setPlayerStats(player, "achievements", #result, true)
triggerEvent("Achievements:onPlayerInit", player)
triggerClientEvent(player, "Achievements:onPlayerReceiveList", player, g_Achievements, g_PlayerAchievements[player])
end
function CAchievement.destructor(player)
player = isElement(player) and player or source
if not getElementData(player, "LoggedIn") then
return
end
if g_PlayerAchievements[player] then
g_PlayerAchievements[player] = nil
end
end
local function tableFind(tbl, key)
local findings = {}
local first_result = false
for i = 1, #tbl do
if tbl[i][1] == key then
if first_result == false then
first_result = true
end
table.insert(findings, i)
end
end
return (first_result == true and findings or false)
end
function CAchievement:onPlayerStatsUpdate(player, key, newValue)
local achievement_ids = tableFind(g_Achievements, key)
if achievement_ids then
for index, achievement_id in pairs(achievement_ids) do
if type(newValue) ~= "number" then
outputDebugString("Found achievement id for a non-numeric value >> "..key.." >> "..newValue, 1)
end
local player_achievement_data = g_PlayerAchievements[player]
if(not player_achievement_data) then
outputDebugString("CAchievement:onPlayerStatsUpdate >> Achievement data not present for "..getPlayerName(player).." (key: "..key..")", 0, 255, 180, 0)
return
end
local achievement_data = g_Achievements[achievement_id]
if newValue >= achievement_data[3] and player_achievement_data[achievement_id] == nil then
player_achievement_data[achievement_id] = true
exports.v_mysql:givePlayerStats(player, "money", achievement_data[5])
CAchievement:UpdateAchievements(player, achievement_id)
end
end
end
end
function CAchievement:UpdateAchievements(player, achievement_id)
local account_id = getElementData(player, "account_id")
dbExec(g_Connection, "INSERT INTO v_achievements (`account_id`, `achievement_id`) VALUES (?, ?)", account_id, achievement_id)
triggerClientEvent(player, "Achievements:onPlayerUnlockAchievement", player, achievement_id)
exports.v_mysql:setPlayerStats(player, "achievements", (exports.v_mysql:getPlayerStats(player, "achievements") or 0)+1, true)
--outputDebugString("CAchievement:UpdateAchievements >> "..string.gsub(getPlayerName(player), "#%x%x%xx%x%x", ""), 0, 255, 180, 0)
end
|
data:extend({
{
type = "item",
name = "dummy-item",
icon = "__Logistics Railway__/graphics/control-panel.png",
flags = {"hidden"},
subgroup = "transport",
order = "z",
stack_size = 1,
icon_size = 32
},
{
type = "item",
name = "storage-rail",
icon = "__Logistics Railway__/graphics/storage-rail.png",
flags = {"goes-to-quickbar"},
subgroup = "transport",
order = "a[train-system]-b[rail-storage]",
place_result = "storage-rail",
stack_size = 100,
icon_size = 32
},
{
type = "item",
name = "passive-provider-rail",
icon = "__Logistics Railway__/graphics/passive-provider-rail.png",
flags = {"goes-to-quickbar"},
subgroup = "transport",
order = "a[train-system]-b[rail-passive-provider]",
place_result = "passive-provider-rail",
stack_size = 100,
icon_size = 32
},
{
type = "item",
name = "active-provider-rail",
icon = "__Logistics Railway__/graphics/active-provider-rail.png",
flags = {"goes-to-quickbar"},
subgroup = "transport",
order = "a[train-system]-b[rail-active-provider]",
place_result = "active-provider-rail",
stack_size = 100,
icon_size = 32
},
{
type = "item",
name = "requester-rail",
icon = "__Logistics Railway__/graphics/requester-rail.png",
flags = {"goes-to-quickbar"},
subgroup = "transport",
order = "a[train-system]-b[rail-requester]",
place_result = "requester-rail",
stack_size = 100,
icon_size = 32
},
})
|
------------------------------------------------------------
------------------------------------------------------------
local channels = TokoVoipConfig.channels;
function addPlayerToRadio(channelId,playerServerId)
if (not channels[channelId]) then
channels[channelId] = {id = channelId, name = channelId.." Mhz", subscribers = {}};
end
if (not channels[channelId].id) then
channels[channelId].id = channelId;
end
channels[channelId].subscribers[playerServerId] = playerServerId;
for _, subscriberServerId in pairs(channels[channelId].subscribers) do
if (subscriberServerId ~= playerServerId) then
TriggerClientEvent("TokoVoip:onPlayerJoinChannel",subscriberServerId,channelId,playerServerId);
else
TriggerClientEvent("TokoVoip:onPlayerJoinChannel",subscriberServerId,channelId,playerServerId,channels[channelId]);
end
end
end
RegisterServerEvent("TokoVoip:addPlayerToRadio");
AddEventHandler("TokoVoip:addPlayerToRadio",addPlayerToRadio);
function removePlayerFromRadio(channelId,playerServerId)
if (channels[channelId] and channels[channelId].subscribers[playerServerId]) then
channels[channelId].subscribers[playerServerId] = nil;
if (channelId > 1000) then
if (tablelength(channels[channelId].subscribers) == 0) then
channels[channelId] = nil;
end
end
TriggerClientEvent("TokoVoip:onPlayerLeaveChannel",playerServerId,channelId,playerServerId);
if (not channels[channelId]) then return end
for _, subscriberServerId in pairs(channels[channelId].subscribers) do
TriggerClientEvent("TokoVoip:onPlayerLeaveChannel",subscriberServerId,channelId,playerServerId);
end
end
end
RegisterServerEvent("TokoVoip:removePlayerFromRadio");
AddEventHandler("TokoVoip:removePlayerFromRadio",removePlayerFromRadio);
function removePlayerFromAllRadio(playerServerId)
for channelId, channel in pairs(channels) do
if (channel.subscribers[playerServerId]) then
removePlayerFromRadio(channelId,playerServerId);
end
end
end
RegisterServerEvent("TokoVoip:removePlayerFromAllRadio");
AddEventHandler("TokoVoip:removePlayerFromAllRadio",removePlayerFromAllRadio);
AddEventHandler("playerDropped",function()
removePlayerFromAllRadio(source);
end);
|
hp = 5000
attack = 280
defense = 250
speed = 55
mdefense = 300
luck = 60
explodes = true
strength = ELEMENT_NONE
weakness = ELEMENT_FIRE
local player_ids = {}
local attacks_in_a_row = 0
function initId(id)
myId = id
end
function numCharmed()
local count = 0
for i=1,#player_ids do
if (battleGetEntityCondition(player_ids[i]) == CONDITION_CHARMED) then
count = count + 1
end
end
return count
end
function start()
local id = battleGetNextEntity(myId)
while (not (id == myId)) do
local t = battleGetEntityType(id)
if (t == COMBATENTITY_TYPE_PLAYER) then
player_ids[#player_ids+1] = id
end
id = battleGetNextEntity(id)
end
end
function get_action(step)
local n = getRandomNumber(2)
if (n == 0 or attacks_in_a_row > 2) then
attacks_in_a_row = 0
local nc = numCharmed()
if (#player_ids > 1 and nc < #player_ids/2) then
local start = getRandomNumber(#player_ids)+1
local n = start
local found
repeat
if (battleGetEntityHP(player_ids[n]) > 0 and not (battleGetEntityCondition(player_ids[n]) == CONDITION_CHARMED)) then
found = n
n = start - 999 -- hack
break
end
n = n + 1
if (n > #player_ids) then
n = 1
end
until n == start
if (n == start) then
return COMBAT_ATTACKING, 1, getRandomPlayer()
else
return COMBAT_CASTING, "Charm", 1, player_ids[found]
end
else
return COMBAT_ATTACKING, 1, getRandomPlayer()
end
else
attacks_in_a_row = attacks_in_a_row + 1
return COMBAT_ATTACKING, 1, getRandomPlayer()
end
end
function die()
addEnemy("Spirit", battleGetX(myId), battleGetY(myId)-10, true)
end
function spell_has_no_effect(name)
if (name == "Stun" or name == "Slow" or name == "Charm") then
return true
else
return false
end
end
|
local const = require("constants")
local class = require("libs.class")
local states = require("gameobject.player.states.states")
local Shword = require("gameobject.shword")
local Wait = class("Wait", states.Base)
function Wait:initialize(player, ...)
states.Base.initialize(self, player)
end
function Wait:enter()
self.lastMove = nil
self.player.animator:play('idle')
self.canDash = false
end
function Wait:exit(newState)
end
function Wait:update()
local player = self.player
player:friction(const.player.friction)
if math.abs(player.moveDir[1]) <= 1e-5 then
self.canDash = true
self.lastMove = nil
else
if not self.lastMove then
self.lastMove = player.time
end
end
if self.canDash and math.abs(player.moveDir[1]) > const.player.dashThresh then
player:setState(states.Dash)
return
end
if self.lastMove and player.time - self.lastMove > const.player.dashInputDelay then
player:setState(states.Run)
return
end
if player.controller.jump.pressed then
player:setState(states.JumpSquat)
return
end
if not player:onGround() then
player:setState(states.Fall)
return
end
player:enterAimShword()
end
return Wait
|
-- @module: PageViewTest
-- @author: JoeyChen
-- @Date: 2018-10-22 16:14:39
-- @Last Modified by JoeyChen
-- @Last Modified time 2018-10-22 17:32:49
local function createUI()
local pageView = ccui.PageView:create()
-- 设置容器尺寸
pageView:setContentSize(200,200)
-- 设置能否触摸
pageView:setTouchEnabled(true)
pageView:setAnchorPoint(cc.p(0.5,0.5))
pageView:setPosition(display.cx,display.cy)
for i = 1, 5, 1 do
local layout = ccui.Layout:create()
layout:setContentSize(200,200)
layout:setBackGroundColorType(ccui.LayoutBackGroundColorType.solid);
layout:setBackGroundColor(cc.c3b(255, 255, 150));
layout:setPosition(display.cx,display.cy)
local text = cc.Label:createWithSystemFont("第" .. i .. "页", "Arial", 30)
:setTextColor(cc.c3b(0, 0, 0))
:move(layout:getContentSize().width/2, layout:getContentSize().height/2)
:addTo(layout)
pageView:addPage(layout)
end
-- 触摸回调
local function callBackFunc(sender,event)
-- 翻页
if event == ccui.PageViewEventType.turning then
-- 页码索引(索引从0开始,需加1)
local index = pageView:getCurrentPageIndex()
print("翻到了第" .. index + 1 .. "页")
end
end
pageView:addEventListener(callBackFunc)
-- 垂直翻页
-- pageView:setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL)
-- 翻到第3页(索引从0开始)
pageView:scrollToPage(2)
return pageView
end
local function main()
local scene = cc.Scene:create()
scene:addChild(createUI())
scene:addChild(CreateBackMenuItem())
return scene
end
return main
|
tutorial = {}
tutMap = {}
tutMap.width = 5
tutMap.height = 5
for i = 0, tutMap.width+1 do
tutMap[i] = {}
end
tutMap[1][3] = "C"
tutMap[2][3] = "C"
tutMap[3][3] = "C"
tutMap[4][3] = "C"
tutMap[5][3] = "C"
tutMap[3][1] = "C"
tutMap[3][2] = "C"
tutMap[3][4] = "C"
tutMap[3][5] = "C"
tutMap[1][1] = "SCHOOL"
tutMap[2][1] = "SCHOOL"
tutMap[1][2] = "SCHOOL"
tutMap[2][2] = "SCHOOL"
tutMap[5][2] = "PL"
tutMap[2][5] = "HO"
tutorialSteps = {}
currentStep = 1
currentStepTitle = ""
currentTutBox = nil
local CODE_chooseDirectionFunction1 = parseCode([[
function ai.chooseDirection( train, directions )
end
]])
local CODE_chooseDirectionFunction2 = parseCode([[
function ai.chooseDirection( train, directions )
-- Beispiel: Gib den Namen des trAIns aus
-- und den Namen des Passagiers:
-- (passenger ist 'nil' falls kein Passagier da ist)
if train.passenger == nil then
print(train.name.." hat keinen Passagier.")
else
print(train.name.." befördert "..train.passenger.name)
end
end
]])
local CODE_pickUpPassenger = parseCode([[
-- Code um Passagiere mitzunehmen:
function ai.foundPassengers( train, passengers )
return passengers[1]
end
]])
local CODE_chooseDirectionWithPassenger1 = parseCode([[
function ai.chooseDirection( train, directions )
if train.passenger == nil then
print(train.name.." hat keinen Passagier.")
-- fahre nach Süden, denn da sind die Passagiere!
return "S"
else
print(train.name.." befördert "..train.passenger.name)
end
end
]])
local CODE_chooseDirectionWithPassenger2 = parseCode([[
function ai.chooseDirection( train, directions )
if train.passenger == nil then
print(train.name.." hat keinen Passagier.")
return "S"
else
print(train.name.." befördert "..train.passenger.name)
if train.passenger.destX < train.x then
return "W"
else
return "E"
end
end
end
]])
local CODE_dropOffPassenger = parseCode([[
-- Code zum Rauslassen der Passagiere:
function ai.foundDestination(train)
-- lass den Passagier raus:
dropPassenger(train)
end
]])
local CODE_enoughMoney = parseCode([[
-- diese Funktion wird aufgerufen, sobald du genug Geld hast:
function ai.enoughMoney()
buyTrain(1,3)
end
]])
local CODE_moreIdeas = parseCode([[
-- Schau, ob es der erste trAIn ist:
if train.ID == 1 then
...
-- Iteriere durch die Passagiere:
-- ACHTUNG: #passengers ist die Länge der Liste!!
i = 1
while i <= #passengers do
...
if ... then
-- nimm Passagier mit
break -- beende die Schleife!
end
i = i + 1
end
]])
function nextTutorialStep()
currentStep = currentStep + 1
showCurrentStep()
end
function prevTutorialStep()
currentStep = currentStep - 1
showCurrentStep()
end
function showCurrentStep()
if cBox then
codeBox.remove(cBox)
cBox = nil
end
if additionalInfoBox then
tutorialBox.remove(additionalInfoBox)
additionalInfoBox = nil
end
if tutorialSteps[currentStep].event then
tutorialSteps[currentStep].event()
end
if currentTutBox then
TUT_BOX_X = currentTutBox.x
TUT_BOX_Y = currentTutBox.y
tutorialBox.remove(currentTutBox)
end
if tutorialSteps[currentStep].stepTitle then
currentStepTitle = tutorialSteps[currentStep].stepTitle
else
local l = currentStep - 1
while l > 0 do
if tutorialSteps[l] and tutorialSteps[l].stepTitle then
currentStepTitle = tutorialSteps[l].stepTitle
break
end
l = l - 1
end
end
currentTutBox = tutorialBox.new( TUT_BOX_X, TUT_BOX_Y, tutorialSteps[currentStep].message, tutorialSteps[currentStep].buttons )
end
function startThisTutorial()
--define buttons for message box:
print("tutorialSteps[1].buttons", tutorialSteps[1].buttons[1].name)
if currentTutBox then tutorialBox.remove(currentTutBox) end
currentTutBox = tutorialBox.new( TUT_BOX_X, TUT_BOX_Y, tutorialSteps[1].message, tutorialSteps[1].buttons )
STARTUP_MONEY = TRAIN_COST + 15
timeFactor = 0.5
tutorial.passengersEnRoute = 0
end
function tutorial.start()
aiFileName = "TutorialAI3.lua"
--ai.backupTutorialAI(aiFileName)
ai.createNewTutAI(aiFileName, fileContent)
stats.start( 1 )
tutMap.time = 0
map.print()
loadingScreen.reset()
loadingScreen.addSection("Neue Karte")
loadingScreen.addSubSection("Neue Karte", "Größe: " .. tutMap.width .. "x" .. tutMap.height)
loadingScreen.addSubSection("Neue Karte", "Zeit: Tag")
loadingScreen.addSubSection("Neue Karte", "Tutorial 3: Sei smart!")
train.init()
train.resetImages()
ai.restart() -- make sure aiList is reset!
ok, msg = pcall(ai.new, AI_DIRECTORY .. aiFileName)
if not ok then
print("Fehler: " .. msg)
else
stats.setAIName(1, aiFileName:sub(1, #aiFileName-4))
train.renderTrainImage(aiFileName:sub(1, #aiFileName-4), 1)
end
tutorial.noTrees = true -- don't render trees!
map.generate(nil,nil,1,tutMap)
tutorial.createTutBoxes()
tutorial.mapRenderingDoneCallback = startThisTutorial
menu.exitOnly()
tutorial.passengersEnRoute = 0
tutorial.passengerDropoffCorrectlyEvent = function()
tutorial.passengersEnRoute = tutorial.passengersEnRoute - 1
end
MAX_NUM_PASSENGERS = 50 -- overwrite default!
end
function tutorial.endRound()
tutorial.passengersEnRoute = 0
tutorial.reachedEast = false
tutorial.reachedWest = false
end
local codeBoxX, codeBoxY = 0,0
local tutBoxX, tutBoxY = 0,0
--[[
function additionalInformation(text, code)
return function()
if not additionalInfoBox then
if currentTutBox then
TUT_BOX_X = currentTutBox.x
TUT_BOX_Y = currentTutBox.y
end
if TUT_BOX_Y + TUT_BOX_HEIGHT + 50 < love.graphics.getHeight() then -- only show BELOW the current box if there's still space there...
additionalInfoBox = tutorialBox.new(TUT_BOX_X, TUT_BOX_Y + TUT_BOX_HEIGHT +10, text, {})
else -- Otherwise, show it ABOVE the current tut box!
additionalInfoBox = tutorialBox.new(TUT_BOX_X, TUT_BOX_Y - 10 - TUT_BOX_HEIGHT, text, {})
end
end
if not cBox then
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, code)
end
end
end
]]--
function tutorial.createTutBoxes()
CODE_BOX_X = love.graphics.getWidth() - CODE_BOX_WIDTH - 30
CODE_BOX_Y = (love.graphics.getHeight() - TUT_BOX_HEIGHT)/2 - 50
local k = 1
tutorialSteps[k] = {}
tutorialSteps[k].stepTitle = "Check!"
tutorialSteps[k].message =
"Das dritte Tutorial zeigt Dir:\n\n"..
"1) Wie man klügere Entscheidungen trifft, je nachdem wo deine Passagiere hin wollen\n\n"..
"2) Den Umgang mit mehreren Zügen."
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Starte Tutorial", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message =
"Auf dieser Karte sind einige Kinder. "..
"Wie Schüler eben sind, wollen einige in die Schule, andere lieber nicht.\n"..
"Als trAIn-Programmierer steht es uns nicht zu, dies zu verurteilen, obwohl...\n"..
"(Drücke die Leertaste oder klicke auf einen Passagier, um sein Ziel zu sehen)"
tutorialSteps[k].event = startCreatingPassengers(k)
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message =
"Dein Job ist es die Passagiere an ihr Ziel zu bringen.\n"..
"Wir könnten einfach alle Richtungen ausprobieren, bis wir die des Passagieres finden, "..
"aber dann wären wir kein guter Gegner für andere, klügere AIs.\n"..
"Stattdessen versuchen wir herauszufinden, wo unser Passagier hin will und fahren dann entsprechend dorthin."
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message =
"Um dies zu erreichen, fügen wir der Funktion ai.chooseDirection zwei Parameter hinzu, "..
"namens 'train' und 'directions'.\n Öffne Deutsch_TutorialAI3.lua und kopiere den Code aus dem Code-Kasten."
tutorialSteps[k].event = function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_chooseDirectionFunction1)
end
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message =
"Der Parameter 'train' ist eine Tabelle, die den trAIn repräsentiert "..
"Sie hat folgende Elemente: 'ID', 'name', 'x' und 'y'. "..
"Wenn der trAIn gerade einen Passagier befördert, "..
"ist ein weiteres Element namens 'passenger' in der Tabelle "..
"(eine Tabelle die den Passager repräsentiert). Diese Tabelle wiederum "..
"hat die Elemente: 'destX' und 'destY', welche das Ziel des Passagieres angeben "..
"und 'name' - der Name unseres Passagiers. Füge den neuen Code deiner Funktion hinzu."
tutorialSteps[k].event = function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_chooseDirectionFunction2)
end
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message =
"Wie in Tutorial 1, müssen wir Code hinzufügen, um einen Passagier mitzunehmen. "..
"Füge dies deinem Script hinzu...\n\nWenn du fertig bist, lade neu und schau ob es funktioniert!"
tutorialSteps[k].event = function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_pickUpPassenger)
end
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message =
"Nächster Schritt: Immer wenn der Zug eine Weiche erreicht und keinen Passagier "..
"an Bord hat, soll er nach Süden fahren. Füge die Zeile Code entsprechend hinzu."
tutorialSteps[k].event = function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_chooseDirectionWithPassenger1)
end
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message =
"Wenn ein Passagier an Bord ist, vergleichen wir die aktuellen X-Koordinaten "..
"des Zuges (train.x) mit den Zielkoordinaten des Passagieres "..
"(train.passenger.destX). Liegt das Ziel im Westen "..
"(X des Ziels ist kleiner als X des trAIns), dann fahren wir nach Westen. "..
"Ansonsten fahren wir nach Osten.\nErweitere deine Funktion entsprechend."
tutorialSteps[k].event = function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_chooseDirectionWithPassenger2)
end
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message =
"Als Letztes müssen wir den Passagier absetzen, so wie letztes Mal\n\n"..
"Wenn du das alles programmiert hast, lade neu und beobachte wie der trAIn die Passagiere rauslässt!\n"..
"(Du kannst die Geschwindigkeit des Tutorials ändern indem du auf + oder - klickst"
tutorialSteps[k].event = waitingForPassengersEvent(k)
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Mehr Info", event = additionalInformation("Das Spielt geht automatisch weiter, wenn du die Passagiere im Westen und im Osten raus gelassen hast."), inBetweenSteps = true}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message =
"Du scheinst es richtig gemacht zu haben, super! Aber es würde viel viel schneller gehen, "..
"wenn wir mehr als einen trAIn hätten. Du beginnst das Tutorial mit einem trAIn und 15 Credits. "..
"Ein neuer trAIn kostet" .. TRAIN_COST .. " credits. Immer wenn du einen Passagier rauslässt, "..
"verdienst du Geld (Credits). Sobald du genug Geld für einen neuen trAIn hast, "..
"wird die Funktion 'ai.enoughMoney aufgerufen. Benutze sie, um einen neuen trAIn zu kaufen.\n"..
"Sobald du den Code geschrieben hast, lade neu."
tutorialSteps[k].event = enoughMoneyEvent(k)
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message =
"Du besitzt jetzt zwei trAIns.\nLehne dich zurück und beobachte deine trAIns dabei, "..
"wie sie 10 Passagiere zu ihrem Ziel bringen. Gute Arbeit!\n\n"..
"0 von 10 transportiert."
tutorialSteps[k].event = waitFor10Passengers(k)
tutorialSteps[k].buttons = {}
--tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].stepTitle = "Erledigt!"
tutorialSteps[k].message =
"Du hast das dritte Tutorial beendet, gute Arbeit!\n"..
"Mit diesem Tutorial hast du die Basics gemeistert. "..
"Klicke auf 'Mehr Ideen' für deine erste richtige Herausforderung!"
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Mehr Ideen", event = additionalInformation(
"Versuche, dass der erste trAIn nur Passagiere, die nach Osten wollen, transportiert. "..
"Um dies zu erreichen:\nChecke in ai.foundPassengers ob die train.ID 1 ist. "..
"Dann prüfe ob passengers[1]'s destX kleiner als train.x ist.\n"..
"Wenn ja, dann nimm ihn mit, andernfalls gehe zu passengers[2] und so weiter,\n"..
"Falls möglich, benutze eine while-Schleife für die passenger-Liste. "..
"Sorge zuletzt dafür, dass der zweite trAIn nur Passagiere, die nach Westen wollen, mitnimmt. "..
"ACHTUNG: #passengers ist die Größe der Liste! Denk daran: 'break' "..
"lässt dich die Schleife beenden sobald du deinen Passagier gefunden hast.", CODE_moreIdeas), inBetweenSteps = true}
tutorialSteps[k].buttons[3] = {name = "Weiter", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Gehe direkt zum nächsten Tutorial oder zurück zum Menü."
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Zurück", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Ende", event = endTutorial}
tutorialSteps[k].buttons[3] = {name = "Nächstes Tutorial", event = nextTutorial}
--tutorialSteps[k].buttons[3] = {name = "Weiter Tutorial", event = nextTutorial}
k = k + 1
end
function startCreatingPassengers(k)
createPassengers = k
tutorial.restartEvent = function()
if currentStep >= k then -- if I haven't gone back to a previous step
createPassengers = k
tutorial.passengersEnRoute = 0
end
end
end
function waitingForPassengersEvent(k)
return function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_dropOffPassenger)
tutorial.reachedNewTileEvent = function(x, y)
if x == 5 then
tutorial.reachedEast = true
elseif x == 1 then
tutorial.reachedWest = true
end
if tutorial.reachedEast and tutorial.reachedWest then
if currentStep == k then -- if I haven't gone back to a previous step
-- tutorial.reachedNewTileEvent = nil
nextTutorialStep()
tutorialBox.succeed()
end
end
end
end
end
function enoughMoneyEvent(k)
return function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_enoughMoney)
local numOfTrains = 0
tutorial.trainPlacingEvent = function()
numOfTrains = numOfTrains + 1
if numOfTrains >= 2 then
if currentStep >= k then -- if I haven't gone back to a previous step
tutorial.trainPlacingEvent = nil
nextTutorialStep()
tutorialBox.succeed()
end
end
end
end
end
function waitFor10Passengers(k)
return function()
numPassengers = 0
tutorial.passengerDropoffCorrectlyEvent = function()
tutorial.passengersEnRoute = tutorial.passengersEnRoute - 1
numPassengers = numPassengers + 1
if currentStep == k then
currentTutBox.text =
"Du besitzt jetzt zwei trAIns\nLehne dich zurück, entspanne und beobachte deine trAIns, "..
"wie sie 10 Passagiere zu ihrem Ziel bringen. Gute Arbeit!\n\n".. numPassengers .." von 10 transportiert."
if numPassengers >= 10 then
nextTutorialStep()
tutorialBox.succeed()
end
end
end
end
end
function endTutorial()
map.endRound()
mapImage = nil
curMap = nil
tutorial = {}
menu.init()
end
function nextTutorial()
map.endRound()
mapImage = nil
curMap = nil
tutorial = {}
menu.init()
menu.executeTutorial("Tutorial4.lua")
end
function tutorial.roundStats()
love.graphics.setColor(255,255,255,255)
x = love.graphics.getWidth()-roundStats:getWidth()-20
y = 20
love.graphics.draw(roundStats, x, y)
love.graphics.print("Tutorial 3: Sei smart!", x + roundStats:getWidth()/2 - FONT_STAT_MSGBOX:getWidth("Tutorial 3: Sei smart!")/2, y+10)
love.graphics.print(currentStepTitle, x + roundStats:getWidth()/2 - FONT_STAT_MSGBOX:getWidth(currentStepTitle)/2, y+30)
end
function tutorial.handleEvents(dt)
newTrainQueueTime = newTrainQueueTime + dt*timeFactor
if newTrainQueueTime >= .1 then
train.handleNewTrains()
newTrainQueueTime = newTrainQueueTime - .1
end
if tutorial.passengersEnRoute <= 5 and createPassengers and currentStep >= createPassengers then
tutorial.passengersEnRoute = tutorial.passengersEnRoute + 1
if goWest then
passenger.new(3,5, 1,3, kidSpeaches[math.random(#kidSpeaches)])
goWest = nil
else
passenger.new(3,5, 5,3, kidSpeaches[math.random(#kidSpeaches)])
goWest = true
end
end
end
kidSpeaches = {}
kidSpeaches[1] = "Ich werde die Mathe-Prüfung verhauen..."
kidSpeaches[2] = "Habe heute Informatik. Hörte, dass wir heute was namens 'Lua' beginnen. Egal!."
kidSpeaches[3] = "Ich hab meine Hausis vergessen."
kidSpeaches[4] = "Schwänzen oder nicht Schwänzen, das ist hier die Frage..."
kidSpeaches[5] = "Das wird mein Untergang."
kidSpeaches[6] = "Letzter Schultag!"
kidSpeaches[7] = "Siehst du diesen Sonnenschein? Er sagt: 'Neeeein... geh nicht zur Schule!'"
fileContent = [[
-- Tutorial 3: Sei smart!
function ai.init()
buyTrain(3,1)
end
]]
|
data:extend({
{
type = "double-setting",
name = "camera-san-zoom",
setting_type = "runtime-per-user",
default_value = 0.25,
minimum_value = 0.1,
maximum_value = 2.0
}
})
|
local assert_error = require("lapis.application").assert_error
local assert_valid = require("lapis.validate").assert_valid
local csrf = require "lapis.csrf"
local capture = require "utils.capture"
local format = require "utils.text_formatter"
local generate = require "utils.generate"
local process = require "utils.request_processor"
local Posts = require "models.posts"
return {
before = function(self)
-- Get board
for _, board in ipairs(self.boards) do
if board.name == self.params.uri_name then
self.board = board
break
end
end
-- Board not found
if not self.board or self.params.page and not tonumber(self.params.page) then
return self:write({ redirect_to = self:url_for("web.pages.index") })
end
-- Get announcements
-- TODO: Consolidate these into a single call
self.announcements = assert_error(capture.get(self:url_for("api.announcements.announcement", { uri_id="global" })))
local board_announcements = assert_error(capture.get(self:url_for("api.boards.announcements", { uri_name=self.params.uri_name })))
for _, announcement in ipairs(board_announcements) do
table.insert(self.announcements, announcement)
end
-- Page title
self.page_title = string.format(
"/%s/ - %s",
self.board.name,
self.board.title
)
-- Flag comments as required or not
self.comment_flag = self.board.thread_comment
-- Generate CSRF token
self.csrf_token = csrf.generate_token(self)
-- Current page
self.params.page = self.params.page or 1
-- Get threads
local response = assert_error(capture.get(self:url_for("api.boards.threads", { uri_name=self.params.uri_name, uri_page=self.params.page })))
self.threads = response.threads
self.pages = response.pages
-- Get posts
for _, thread in ipairs(self.threads) do
-- Get posts visible on the board index
thread.posts = Posts:get_index_posts(thread.id)
-- Get hidden posts
thread.hidden = Posts:count_hidden_posts(thread.id)
-- Get op
local op = thread.posts[#thread.posts]
if not op then
assert_error(false, { "err_orphaned", { thread.id } })
end
thread.url = self:url_for("web.boards.thread", { uri_name=self.board.name, thread=op.post_id })
-- Format comments
for _, post in ipairs(thread.posts) do
-- OP gets a thread tag
if post.post_id == op.post_id then
post.thread = post.post_id
end
post.name = post.name or self.board.anon_name
post.reply = self:url_for("web.boards.thread", { uri_name=self.board.name, thread=op.post_id, anchor="q", id=post.post_id })
post.link = self:url_for("web.boards.thread", { uri_name=self.board.name, thread=op.post_id, anchor="p", id=post.post_id })
post.remix = self:url_for("web.boards.thread", { uri_name=self.board.name, thread=op.post_id, anchor="r", id=post.post_id })
post.timestamp = os.date("%Y-%m-%d (%a) %H:%M:%S", post.timestamp)
post.file_size = math.floor(post.file_size / 1024)
post.file_dimensions = ""
if post.file_width > 0 and post.file_height > 0 then
post.file_dimensions = string.format(", %dx%d", post.file_width, post.file_height)
end
if not post.file_duration or post.file_duration == "0" then
post.file_duration = ""
else
post.file_duration = string.format(", %s", post.file_duration)
end
if post.file_path then
local name, ext = post.file_path:match("^(.+)(%..+)$")
ext = string.lower(ext)
-- Get thumbnail URL
if post.file_type == "audio" then
if post == thread.posts[#thread.posts] then
post.thumb = self:format_url(self.static_url, "op_audio.png")
else
post.thumb = self:format_url(self.static_url, "post_audio.png")
end
elseif post.file_type == "image" then
if post.file_spoiler then
if post == thread.posts[#thread.posts] then
post.thumb = self:format_url(self.static_url, "op_spoiler.png")
else
post.thumb = self:format_url(self.static_url, "post_spoiler.png")
end
else
if ext == ".webm" or ext == ".svg" then
post.thumb = self:format_url(self.files_url, self.board.name, 's' .. name .. '.png')
else
post.thumb = self:format_url(self.files_url, self.board.name, 's' .. post.file_path)
end
end
end
post.file_path = self:format_url(self.files_url, self.board.name, post.file_path)
end
-- Process comment
if post.comment then
local comment = post.comment
comment = format.sanitize(comment)
comment = format.quote(comment, self, self.board, post)
comment = format.green_text(comment)
comment = format.blue_text(comment)
comment = format.spoiler(comment)
comment = format.new_lines(comment)
post.comment = comment
else
post.comment = ""
end
end
end
end,
on_error = function(self)
self.errors = generate.errors(self.i18n, self.errors)
return { render = "board"}
end,
GET = function()
return { render = "board" }
end,
POST = function(self)
-- Validate CSRF token
csrf.assert_token(self)
local board_url = self:url_for("web.boards.board", { uri_name=self.board.name })
-- Submit new thread
if self.params.submit then
-- Validate user input
assert_valid(self.params, {
{ "name", max_length=255 },
{ "subject", max_length=255 },
{ "options", max_length=255 },
{ "comment", max_length=self.text_size }
})
-- Validate post
local post = assert_error(process.create_thread(self.params, self.session, self.board))
return { redirect_to = self:url_for("web.boards.thread", { uri_name=self.board.name, thread=post.post_id, anchor="p", id=post.post_id }) }
end
-- Delete thread
if self.params.delete and self.params.thread_id then
-- Validate user input
assert_valid(self.params, {
{ "post_id", exists=true }
})
-- Validate deletion
assert_error(process.delete_thread(self.params, self.session, self.board))
return { redirect_to = board_url }
end
-- Delete post
if self.params.delete and not self.params.thread_id then
-- Validate user input
assert_valid(self.params, {
{ "post_id", exists=true }
})
-- Validate deletion
assert_error(process.delete_post(self.params, self.session, self.board))
return { redirect_to = board_url }
end
-- Report post
if self.params.report then
-- Validate user input
assert_valid(self.params, {
{ "board", exists=true },
{ "post_id", exists=true }
})
-- Validate report
assert_error(process.report_post(self.params, self.board))
return { redirect_to = board_url }
end
-- Admin commands
if self.session.admin or self.session.mod then
-- Sticky thread
if self.params.sticky then
assert_error(process.sticky_thread(self.params, self.board))
return { redirect_to = board_url }
end
-- Lock thread
if self.params.lock then
assert_error(process.lock_thread(self.params, self.board))
return { redirect_to = board_url }
end
-- Save thread
if self.params.save then
assert_error(process.save_thread(self.params, self.board))
return { redirect_to = board_url }
end
-- Override thread
if self.params.override then
assert_error(process.override_thread(self.params, self.board))
return { redirect_to = board_url }
end
-- Ban user
if self.params.ban then
assert_error(process.ban_user(self.params, self.board))
return { redirect_to = board_url }
end
end
return { redirect_to = board_url }
end
}
|
local X = {}
local team = GetTeam();
local CStackTime = {55,55,55,55,55,54,55,55,55,55,55,55,55,55,55,55,55,55}
local CStackLoc = {
Vector(-800.000000, -5000.000000, 0.000000),
Vector(-1871.000000, -2936.000000, 0.000000),
Vector(801.000000, -3146.000000, 0.000000),
Vector(-3481.000000, -1122.000000, 0.000000),
Vector(5773.000000, -3071.000000, 0.000000),
Vector(3570.000000, -5963.000000, 0.000000),
Vector(-5374.000000, 446.000000, 0.000000),
Vector(-1872.000000, 1141.000000, 0.000000),
Vector(801.000000, -3146.000000, 0.000000),
Vector(586.000000, 4456.000000, 0.000000),
Vector(-3457.000000, 6297.000000, 0.000000),
Vector(-955.000000, 5121.000000, 0.000000),
Vector(-3050.000000, 3434.000000, 0.000000),
Vector(3473.000000, 1870.000000, 0.000000),
Vector(2474.000000, 5051.000000, 0.000000),
Vector(3036.000000, -1168.000000, 0.000000),
Vector(957.000000, 2295.000000, 0.000000),
Vector(4071.000000, -2013.000000, 0.000000)
}
--test hero
local jungler = {
'npc_dota_hero_alchemist',
'npc_dota_hero_bloodseeker',
'npc_dota_hero_legion_commander',
'npc_dota_hero_life_stealer'
--'npc_dota_hero_skeleton_king',
--'npc_dota_hero_ursa'
}
function X.GetCampMoveToStack(id)
return CStackLoc[id]
end
function X.GetCampStackTime(camp)
if camp.cattr.speed == "fast" then
return 55;
elseif camp.cattr.speed == "slow" then
return 54;
else
return 55;
end
end
function X.IsEnemyCamp(camp)
return camp.team ~= GetTeam();
end
function X.IsAncientCamp(camp)
return camp.type == "ancient";
end
function X.IsSmallCamp(camp)
return camp.type == "small";
end
function X.IsMediumCamp(camp)
return camp.type == "medium";
end
function X.IsLargeCamp(camp)
return camp.type == "large";
end
function X.RefreshCamp(bot)
local camps = GetNeutralSpawners();
local AllCamps = {};
for k,camp in pairs(camps) do
if bot:GetLevel() <= 6 then
if not X.IsEnemyCamp(camp) and not X.IsLargeCamp(camp) and not X.IsAncientCamp(camp)
then
table.insert(AllCamps, {idx=k, cattr=camp});
end
elseif bot:GetLevel() <= 10 then
if not X.IsEnemyCamp(camp) and not X.IsAncientCamp(camp)
then
table.insert(AllCamps, {idx=k, cattr=camp});
end
else
table.insert(AllCamps, {idx=k, cattr=camp});
end
end
local nCamps = #AllCamps;
return AllCamps, nCamps;
end
function X.IsStrongJungler(bot)
local name = bot:GetUnitName();
for _,n in pairs(jungler)
do
if name == n then
return true;
end
end
return false;
end
function X.GetClosestNeutralSpwan(bot, AvailableCamp)
local minDist = 10000;
local pCamp = nil;
for _,camp in pairs(AvailableCamp)
do
local dist = GetUnitToLocationDistance(bot, camp.cattr.location);
if X.IsTheClosestOne(bot, dist, camp.cattr.location) and dist < minDist then
minDist = dist;
pCamp = camp;
end
end
return pCamp
end
function X.IsTheClosestOne(bot, bDis, loc)
local dis = bDis;
local closest = bot;
for k,v in pairs(GetTeamPlayers(GetTeam()))
do
local member = GetTeamMember(k);
if member ~= nil and not member:IsIllusion() and member:IsAlive() and member:GetActiveMode() == BOT_MODE_FARM then
local dist = GetUnitToLocationDistance(member, loc);
if dist < dis then
dis = dist;
closest = member;
end
end
end
return closest:GetUnitName() == bot:GetUnitName();
end
function X.FindFarmedTarget(Creeps)
local minHP = 10000;
local target = nil;
for _,creep in pairs(Creeps)
do
local hp = creep:GetHealth();
--if team == TEAM_DIRE then print(tostring(creep:CanBeSeen())) end
if creep ~= nil and not creep:IsNull() and creep:IsAlive() and hp < minHP then
minHP = hp;
target = creep;
end
end
return target
end
function X.IsSuitableToFarm(bot)
local mode = bot:GetActiveMode();
if mode == BOT_MODE_RUNE
or mode == BOT_MODE_DEFEND_TOWER_TOP
or mode == BOT_MODE_DEFEND_TOWER_MID
or mode == BOT_MODE_DEFEND_TOWER_BOT
or mode == BOT_MODE_ATTACK
then
return false;
end
return true;
end
function X.UpdateAvailableCamp(bot, preferedCamp, AvailableCamp)
if preferedCamp ~= nil then
for i = 1, #AvailableCamp
do
if AvailableCamp[i].cattr.location == preferedCamp.cattr.location or GetUnitToLocationDistance(bot, AvailableCamp[i].cattr.location) < 300 then
table.remove(AvailableCamp, i);
--print("Updating available camp : "..tostring(#AvailableCamp))
preferedCamp = nil;
return AvailableCamp, preferedCamp;
end
end
end
end
return X
--[[
--RADIANT CAMP
[VScript] =======================
[VScript] max:Vector 00000000005D3140 [-29.500122 -2992.000000 639.999939]
[VScript] team:2
[VScript] location:Vector 0000000000258AD0 [-371.000000 -3374.000000 265.000000]
[VScript] type:large
[VScript] min:Vector 00000000005D3048 [-1204.000000 -3598.000000 -384.000000]
[VScript] speed:fast
[VScript] =======================
[VScript] max:Vector 000000000072F370 [-1472.000000 -3784.000000 608.000061]
[VScript] team:2
[VScript] location:Vector 00000000005D31B8 [-1806.244507 -4485.535156 256.000000]
[VScript] type:medium
[VScript] min:Vector 00000000005D31E8 [-2187.000000 -4640.000000 -384.000000]
[VScript] speed:fast
[VScript] =======================
[VScript] max:Vector 000000000072F4F0 [1112.000000 -4128.000000 512.000061]
[VScript] team:2
[VScript] location:Vector 000000000072F3C8 [384.000000 -4672.000000 519.999939]
[VScript] type:medium
[VScript] min:Vector 000000000072F3F8 [178.999939 -5093.500000 -384.000000]
[VScript] speed:fast
[VScript] =======================
[VScript] max:Vector 00000000009A19C8 [-4272.000000 96.000000 1096.000000]
[VScript] team:2
[VScript] location:Vector 00000000005D2FE0 [-4873.000000 -512.500000 263.999756]
[VScript] type:large
[VScript] min:Vector 00000000005D3010 [-5165.500000 -640.000000 112.500000]
[VScript] speed:fast
[VScript] =======================
[VScript] max:Vector 00000000009A1B90 [-3962.000000 4224.000000 384.500061]
[VScript] team:2
[VScript] location:Vector 00000000009A19F8 [-4448.000000 3456.000000 470.714874]
[VScript] type:large
[VScript] min:Vector 00000000009A1A28 [-4784.000000 3328.000244 -384.000000]
[VScript] speed:slow
[VScript] =======================
[VScript] max:Vector 00000000002FBA50 [3800.000000 -4048.000000 608.000000]
[VScript] team:2
[VScript] location:Vector 00000000009A1BC0 [2849.953857 -4557.562012 263.999878]
[VScript] type:small
[VScript] min:Vector 00000000005D3280 [2784.000000 -4912.000000 -384.000000]
[VScript] speed:normal
[VScript] =======================
[VScript] max:Vector 00000000002FBBA8 [-3474.999756 1088.000000 768.000061]
[VScript] team:2
[VScript] location:Vector 00000000002FBA80 [-3685.870605 871.857666 263.999939]
[VScript] type:medium
[VScript] min:Vector 00000000002FBAB0 [-4319.999512 192.000000 -383.999817]
[VScript] speed:normal
[VScript] =======================
[VScript] max:Vector 0000000000290EC0 [-2277.000000 207.999939 928.000000]
[VScript] team:2
[VScript] location:Vector 00000000002FBC00 [-3077.500000 -199.000000 393.000000]
[VScript] type:ancient
[VScript] min:Vector 00000000002FBC30 [-3203.500000 -643.500061 -384.000000]
[VScript] speed:normal
[VScript] =======================
[VScript] max:Vector 0000000000291018 [516.000000 -1593.750000 704.000000]
[VScript] team:2
[VScript] location:Vector 0000000000290EF0 [69.066162 -1851.600098 392.000000]
[VScript] type:ancient
[VScript] min:Vector 0000000000290F20 [-356.000000 -2292.000000 280.500000]
[VScript] speed:normal
--DIRE CAMP
[VScript] =======================
[VScript] max:Vector 00000000005D3248 [113.500000 3645.500000 735.000000]
[VScript] team:3
[VScript] location:Vector 00000000009A1A88 [-108.500000 3339.500000 393.000000]
[VScript] type:large
[VScript] min:Vector 00000000005D3218 [-768.000000 3232.000000 -384.000000]
[VScript] speed:normal
[VScript] =======================
[VScript] max:Vector 000000000028F0E8 [-2524.000244 5199.250000 512.000061]
[VScript] team:3
[VScript] location:Vector 000000000028EF50 [-2816.000000 4736.000000 393.000000]
[VScript] type:small
[VScript] min:Vector 000000000028EF80 [-3620.000244 4424.000000 -384.000000]
[VScript] speed:normal
[VScript] =======================
[VScript] max:Vector 0000000000260268 [-1264.000000 4302.000000 540.500061]
[VScript] team:3
[VScript] location:Vector 000000000028EFB8 [-1952.000000 4128.000000 280.000000]
[VScript] type:medium
[VScript] min:Vector 000000000028EFE8 [-2096.000000 3680.000000 77.000061]
[VScript] speed:fast
[VScript] =======================
[VScript] max:Vector 0000000000260458 [4738.593750 1088.000000 944.000000]
[VScript] team:3
[VScript] location:Vector 00000000002602C0 [4452.000000 840.000000 391.999878]
[VScript] type:large
[VScript] min:Vector 00000000002602F0 [4032.000000 511.999878 384.000000]
[VScript] speed:fast
[VScript] =======================
[VScript] max:Vector 0000000000765398 [4992.000000 -3872.000000 800.000000]
[VScript] team:3
[VScript] location:Vector 0000000000260350 [4804.000000 -4472.000000 264.000000]
[VScript] type:large
[VScript] min:Vector 00000000007652A0 [4016.000000 -4640.000000 -384.000000]
[VScript] speed:normal
[VScript] =======================
[VScript] max:Vector 0000000000765238 [1584.500000 3920.000000 1152.000000]
[VScript] team:3
[VScript] location:Vector 00000000007653F0 [1346.833252 3289.285156 391.999878]
[VScript] type:medium
[VScript] min:Vector 0000000000765420 [607.999939 3128.500000 -384.000000]
[VScript] speed:normal
[VScript] =======================
[VScript] max:Vector 00000000005DBBB0 [3284.000000 424.000000 448.000000]
[VScript] team:3
[VScript] location:Vector 00000000002B7B40 [2548.799561 92.937256 391.999878]
[VScript] type:medium
[VScript] min:Vector 00000000005DBAB8 [2320.000000 -160.000000 -384.000122]
[VScript] speed:normal
[VScript] =======================
[VScript] max:Vector 00000000002B7B70 [-288.000000 2752.000000 1144.500000]
[VScript] team:3
[VScript] location:Vector 00000000005DBC08 [-948.000000 2268.500000 391.999756]
[VScript] type:ancient
[VScript] min:Vector 00000000005DBC38 [-1034.875000 1967.999878 383.999756]
[VScript] speed:normal
[VScript] =======================
[VScript] max:Vector 0000000000803520 [4176.000000 -384.000000 400.000000]
[VScript] team:3
[VScript] location:Vector 00000000005DBA78 [3936.000000 -576.000000 295.644104]
[VScript] type:ancient
[VScript] min:Vector 0000000000291048 [3192.000000 -976.000000 -384.000000]
[VScript] speed:normal
]]--
|
function Lothros_OnEnterCombat(Unit,Event)
Unit:RegisterUnitEvent("Lothros_Spell", 60000, 0)
end
function Lothros_Spell(Unit,Event)
Unit:FullCastSpellOnTarget(38167,Unit:GetClosestPlayer())
end
function Lothros_OnLeaveCombat(Unit,Event)
Unit:RemoveEvents()
end
function Lothros_OnDied(Unit,Event)
Unit:RemoveEvents()
end
RegisterUnitEvent(21928, 1, "Lothros_OnEnterCombat")
RegisterUnitEvent(21928, 2, "Lothros_OnLeaveCombat")
RegisterUnitEvent(21928, 4, "Lothros_OnDied")
|
module("luci.controller.advanced",package.seeall)
function index()
if not nixio.fs.access("/etc/config/advanced")then
return
end
local e
e=entry({"admin","system","advanced"},cbi("advanced"),_("高级设置"),60)
e.dependent=true
end
|
local ReplicatedStorage = game:GetService("ReplicatedStorage")
require(ReplicatedStorage.TestEZ).TestBootstrap:run({
ReplicatedStorage.Plasma,
ReplicatedStorage.Tests,
})
|
function opponentNoteHit(id, direction, noteType, isSustainNote)
if curBeat < 186 then
if curBeat > 148 then
cameraShake('cam', '0.015', '0.1')
end
end
end
|
local ngx = _G.ngx
local action = setmetatable({}, require "apps.api.internal.action_base")
local assert_error = require("lapis.application").assert_error
local models = require "models"
local Threads = models.threads
function action:GET()
-- Get Thread
local thread = assert_error(Threads:get(self.params.uri_id))
--Threads:format_from_db(thread)
return {
status = ngx.HTTP_OK,
json = thread
}
end
function action:PUT()
local params = { id=self.params.uri_id }
-- Extract flag from URI
if self.params.uri_value:lower() == "true" or
self.params.uri_value:lower() == "t" or
tonumber(self.params.uri_value) == 1 then
self.params.uri_value = true
elseif self.params.uri_value:lower() == "false" or
self.params.uri_value:lower() == "f" or
tonumber(self.params.uri_value) == 0 then
self.params.uri_value = false
else
return {
status = ngx.HTTP_BAD_REQUEST,
json = {}
}
end
-- Extract variable from URI
if self.params.uri_action == "sticky" then
params.sticky = self.params.uri_value
elseif self.params.uri_action == "lock" then
params.lock = self.params.uri_value
elseif self.params.uri_action == "save" then
params.save = self.params.uri_value
elseif self.params.uri_action == "size_override" then
params.size_override = self.params.uri_value
else
return {
status = ngx.HTTP_BAD_REQUEST,
json = {}
}
end
-- Modify thread
local thread = assert_error(Threads:modify(params))
--Threads:format_from_db(thread)
return {
status = ngx.HTTP_OK,
json = thread
}
end
function action:DELETE()
end
return action
|
local Animation = {}
local Animation_mt = { __index = Animation }
function Animation.new(image, frames, duration)
local new_animation = {
image=image,
frames=frames,
max_frame=#frames,
duration=duration or 0.1,
position=0,
elapsed=0,
}
return setmetatable(new_animation, Animation_mt)
end
function Animation:update(dt)
self.elapsed = self.elapsed + dt
if self.elapsed >= self.duration then
self.elapsed = self.elapsed - self.duration
if self.position == self.max_frame then
self.position = 1
else
self.position = self.position + 1
end
end
end
function Animation:draw(x, y)
if self.frames[self.position] ~= nil then
love.graphics.setColor(255,255,255)
love.graphics.draw(self.image, self.frames[self.position], x, y)
end
end
return Animation
|
local asdf_to_number = require 'asdf_to_number'
return function(vars, args)
-- s [str] [digit 1] [digit 2]
vars.write(args[2], vars.read(args[2]):sub(
asdf_to_number(vars.read(args[3])) + 1,
asdf_to_number(vars.read(args[4])) + 1))
end
|
--- Holds all created standard operating procedures.
-- The created SOPs must be added in this static module. This prevents from being dependent on the load order of the Lua files.
-- The currently added SOPs can be received at any time. A callback can be added to get notified about SOPs which are added subsequently.
-- @module sopRegister
-- @author Patrick Lang
-- @copyright 2022 Patrick Lang
local sopRegister = {}
local utils = require "audiochecklist.utils"
local standardOperatingProcecudes = {}
local addedCallbacks = {}
--- Adds a standard operating procedure to the list of SOPs
-- @tparam standardOperatingProcedure sop The standard operating procedure to add
function sopRegister.addSOP(sop)
utils.verifyNotNil("sop", sop)
utils.logInfo("SopExecutor", "Registered SOP '" .. sop:getName() .. "'")
table.insert(standardOperatingProcecudes, sop)
for _, callback in ipairs(addedCallbacks) do
callback(sop)
end
end
--- Gets all registered standard operating procedures
-- @treturn tab An array which contains all standard operating procedures
function sopRegister.getAllSOPs()
return standardOperatingProcecudes
end
--- Adds a callback which is exeucted if a SOP is added to the register.
-- The added SOP is passed as a parameter to the callback.
-- @tparam func callback The callback to add.
-- @usage sopRegister.addAddedCallback(function(sop) end)
function sopRegister.addAddedCallback(callback)
utils.verifyType("callback", callback, "function")
table.insert(addedCallbacks, callback)
end
return sopRegister
|
local me = game.Players.yfc
local char = me.Character
local pg = me.PlayerGui
local spd = 0
local cordx = 25000
local cordy = 750000
local cordz = 2765
local reading = "No readings found;"
local wepstatus = "Inactive - none on board"
local locations = 65
pcall(function() char["Ship"]:remove() end)
local model = Instance.new("Model", char)
model.Name = "Ship"
function create(part, weld, mesh, sizex, sizey, sizez, scalex, scaley, scalez, type, bevel, id, cz, ca, color, form, anchored, cancollide, trans, reflect, name, topsurf, botsurf)
part.formFactor = form
part.Size = Vector3.new(sizex, sizey, sizez)
part.BrickColor = BrickColor.new(color)
part.Anchored = anchored
part.CanCollide = cancollide
part.Transparency = trans
part.Reflectance = reflect
part.Name = name
part.TopSurface = topsurf
part.BottomSurface = botsurf
part:BreakJoints()
weld.Part0 = part
weld.Part1 = cz
weld.C1 = ca
weld.Parent = part
mesh.Parent = part
mesh.Scale = Vector3.new(scalex, scaley, scalez)
if mesh.className == "BlockMesh" then
mesh.Bevel = bevel
end
if mesh.className == "SpecialMesh" then
mesh.MeshType = type
end
if mesh.className == "SpecialMesh" and mesh.meshType == "FileMesh" then
mesh.MeshId = id
end
end
local part1 = Instance.new("Part", model)
local mesh1 = Instance.new("BlockMesh")
local weld1 = Instance.new("Weld")
create(part1, weld1, mesh1, 10, 1, 30, 1.01, 1.01, 1.01, "", 0.1, "", nil, CFrame.new(0, -0.4, 0) * CFrame.Angles(0, 0, 0), "Dark stone grey", "Custom", false, true, 0, 0, "Torso", "Smooth", "Smooth")
local pos = Instance.new("BodyPosition", part1)
pos.position = Vector3.new(25, 10, 0)
pos.maxForce = Vector3.new(math.huge, math.huge, math.huge)
local gyro = Instance.new("BodyGyro", part1)
gyro.maxTorque = Vector3.new(math.huge, math.huge, math.huge)
local part2 = Instance.new("Part", model)
local mesh2 = Instance.new("BlockMesh")
local weld2 = Instance.new("Weld")
create(part2, weld2, mesh2, 1, 10, 20, 1.01, 1.01, 1.01, "", 0.1, "", part1, CFrame.new(5, 4.5, 0) * CFrame.Angles(0, 0, 0), "Dark stone grey", "Custom", false, true, 0, 0, "Torso", "Smooth", "Smooth")
local part3 = Instance.new("Part", model)
local mesh3 = Instance.new("BlockMesh")
local weld3 = Instance.new("Weld")
create(part3, weld3, mesh3, 1, 10, 20, 1.01, 1.01, 1.01, "", 0.1, "", part1, CFrame.new(-5, 4.5, 0) * CFrame.Angles(0, 0, 0), "Dark stone grey", "Custom", false, true, 0, 0, "Torso", "Smooth", "Smooth")
local part4 = Instance.new("Part", model)
local mesh4 = Instance.new("BlockMesh")
local weld4 = Instance.new("Weld")
create(part4, weld4, mesh4, 10, 1, 20, 1.01, 1.01, 1.01, "", 0.1, "", part1, CFrame.new(0, 9, 0) * CFrame.Angles(0, 0, 0), "Dark stone grey", "Custom", false, true, 0, 0, "Torso", "Smooth", "Smooth")
local part5 = Instance.new("Part", model)
local mesh5 = Instance.new("BlockMesh")
local weld5 = Instance.new("Weld")
create(part5, weld5, mesh5, 10, 1, 11, 1.01, 1.01, 1.01, "", 0.1, "", part1, CFrame.new(0, 4.5, 12.5) * CFrame.Angles(1.1, 0, 0), "Dark stone grey", "Custom", false, true, 0, 0, "Torso", "Smooth", "Smooth")
local part6 = Instance.new("Part", model)
local mesh6 = Instance.new("SpecialMesh")
local weld6 = Instance.new("Weld")
create(part6, weld6, mesh6, 1, 10, 5, 1.01, 1.01, 1.01, "Wedge", 0.1, "", part1, CFrame.new(-5, 4.5, 12.5) * CFrame.Angles(0, 1.55*2, 0), "Dark stone grey", "Custom", false, true, 0, 0, "Torso", "Smooth", "Smooth")
local part7 = Instance.new("Part", model)
local mesh7 = Instance.new("SpecialMesh")
local weld7 = Instance.new("Weld")
create(part7, weld7, mesh7, 1, 10, 5, 1.01, 1.01, 1.01, "Wedge", 0.1, "", part1, CFrame.new(5, 4.5, 12.5) * CFrame.Angles(0, 1.55*2, 0), "Dark stone grey", "Custom", false, true, 0, 0, "Torso", "Smooth", "Smooth")
local part8 = Instance.new("Part", model)
local mesh8 = Instance.new("BlockMesh")
local weld8 = Instance.new("Weld")
create(part8, weld8, mesh8, 10, 10, 1, 1.01, 1.01, 1.01, "", 0.1, "", part1, CFrame.new(0, 4.5, -10.5) * CFrame.Angles(0, 0, 0), "Dark stone grey", "Custom", false, false, 0, 0, "Torso", "Smooth", "Smooth")
local part9 = Instance.new("Seat", model)
local mesh9 = Instance.new("CylinderMesh")
local weld9 = Instance.new("Weld")
create(part9, weld9, mesh9, 2, 1, 2, 1.01, 1.01, 1.01, "", 0.1, "", part1, CFrame.new(0, 0.5, 9.5) * CFrame.Angles(0, 1.55*2, 0), "Dark stone grey", "Custom", false, true, 0, 0, "Torso", "Smooth", "Smooth")
for i = 1, 5 do
local part10 = Instance.new("Seat", model)
local mesh10 = Instance.new("CylinderMesh")
local weld10 = Instance.new("Weld")
create(part10, weld10, mesh10, 2, 1, 2, 1.01, 1.01, 1.01, "", 0.1, "", part1, CFrame.new(3.5, 0.5, -7.5+i*2.5) * CFrame.Angles(0, 1.55, 0), "Dark stone grey", "Custom", false, true, 0, 0, "Torso", "Smooth", "Smooth")
local part11 = Instance.new("Seat", model)
local mesh11 = Instance.new("CylinderMesh")
local weld11 = Instance.new("Weld")
create(part11, weld11, mesh11, 2, 1, 2, 1.01, 1.01, 1.01, "", 0.1, "", part1, CFrame.new(-3.5, 0.5, -7.5+i*2.5) * CFrame.Angles(0, -1.55, 0), "Dark stone grey", "Custom", false, true, 0, 0, "Torso", "Smooth", "Smooth")
wait()
end
pcall(function() pg.RpgGui:remove() end)
local gui = Instance.new("ScreenGui", pg)
gui.Name = "RpgGui"
local back = Instance.new("Frame", gui)
back.Position = UDim2.new(0, 0, 0, 200)
back.Size = UDim2.new(0, 200, 0, 200)
back.BorderSizePixel = 0
back.BackgroundColor = BrickColor.new("Reddish brown")
back.BackgroundTransparency = 0.15
local id = Instance.new("TextLabel", back)
id.Position = UDim2.new(0, 0, 0, 0)
id.Size = UDim2.new(0, 200, 0, 25)
id.BorderSizePixel = 0
id.BackgroundColor = BrickColor.new("Really black")
id.BackgroundTransparency = 0.5
id.TextColor = BrickColor.new("White")
id.Text = "Speed: " ..spd.. " kps"
id.TextWrap = true
local id2 = Instance.new("TextLabel", back)
id2.Position = UDim2.new(0, 0, 0, 30)
id2.Size = UDim2.new(0, 200, 0, 25)
id2.BorderSizePixel = 0
id2.BackgroundColor = BrickColor.new("Really black")
id2.BackgroundTransparency = 0.5
id2.TextColor = BrickColor.new("White")
id2.Text = "Cordinates: " ..cordx.. ", " ..cordy.. ", " ..cordz.. " "
id2.TextWrap = true
local id3 = Instance.new("TextButton", back)
id3.Position = UDim2.new(0, 0, 0, 60)
id3.Size = UDim2.new(0, 200, 0, 25)
id3.BorderSizePixel = 0
id3.BackgroundColor = BrickColor.new("Really black")
id3.BackgroundTransparency = 0.5
id3.TextColor = BrickColor.new("White")
id3.Text = "Open interface"
local id4 = Instance.new("TextButton", back)
id4.Position = UDim2.new(0, 0, 0, 90)
id4.Size = UDim2.new(0, 200, 0, 25)
id4.BorderSizePixel = 0
id4.BackgroundColor = BrickColor.new("Really black")
id4.BackgroundTransparency = 0.5
id4.TextColor = BrickColor.new("White")
id4.Text = "Open flight data"
local id5 = Instance.new("TextButton", back)
id5.Position = UDim2.new(0, 0, 0, 120)
id5.Size = UDim2.new(0, 200, 0, 25)
id5.BorderSizePixel = 0
id5.BackgroundColor = BrickColor.new("Really black")
id5.BackgroundTransparency = 0.5
id5.TextColor = BrickColor.new("White")
id5.Text = "Open Realease switch"
local id6 = Instance.new("TextButton", back)
id6.Position = UDim2.new(0, 0, 0, 150)
id6.Size = UDim2.new(0, 200, 0, 40)
id6.BorderSizePixel = 0
id6.BackgroundColor = BrickColor.new("Really red")
id6.BackgroundTransparency = 0.5
id6.TextColor = BrickColor.new("White")
id6.Text = "ABORT"
id6.FontSize = "Size18"
local back2 = Instance.new("Frame", gui)
back2.Position = UDim2.new(0, 200, 0, 200)
back2.Size = UDim2.new(0, 200, 0, 125)
back2.BorderSizePixel = 0
back2.BackgroundColor = BrickColor.new("Reddish brown")
back2.BackgroundTransparency = 0.15
back2.Visible = false
local idi = Instance.new("TextLabel", back2)
idi.Position = UDim2.new(0, 0, 0, 0)
idi.Size = UDim2.new(0, 200, 0, 25)
idi.BorderSizePixel = 0
idi.BackgroundColor = BrickColor.new("Really black")
idi.BackgroundTransparency = 0.5
idi.TextColor = BrickColor.new("White")
idi.Text = "Interface: " ..reading.. " "
idi.TextWrap = true
local idi2 = Instance.new("TextButton", back2)
idi2.Position = UDim2.new(0, 0, 0, 30)
idi2.Size = UDim2.new(0, 200, 0, 25)
idi2.BorderSizePixel = 0
idi2.BackgroundColor = BrickColor.new("Really black")
idi2.BackgroundTransparency = 0.5
idi2.TextColor = BrickColor.new("White")
idi2.Text = "Search again?"
local idi3 = Instance.new("TextButton", back2)
idi3.Position = UDim2.new(0, 0, 0, 60)
idi3.Size = UDim2.new(0, 200, 0, 25)
idi3.BorderSizePixel = 0
idi3.BackgroundColor = BrickColor.new("Really black")
idi3.BackgroundTransparency = 0.5
idi3.TextColor = BrickColor.new("White")
idi3.Text = "Reset scanner"
local idi4 = Instance.new("TextButton", back2)
idi4.Position = UDim2.new(0, 0, 0, 90)
idi4.Size = UDim2.new(0, 200, 0, 25)
idi4.BorderSizePixel = 0
idi4.BackgroundColor = BrickColor.new("Really black")
idi4.BackgroundTransparency = 0.5
idi4.TextColor = BrickColor.new("White")
idi4.Text = "Open Weapons console"
local back3 = Instance.new("Frame", gui)
back3.Position = UDim2.new(0, 400, 0, 200)
back3.Size = UDim2.new(0, 200, 0, 125)
back3.BorderSizePixel = 0
back3.Visible = false
back3.BackgroundColor = BrickColor.new("Reddish brown")
back3.BackgroundTransparency = 0.15
local idis = Instance.new("TextLabel", back3)
idis.Position = UDim2.new(0, 0, 0, 0)
idis.Size = UDim2.new(0, 200, 0, 25)
idis.BorderSizePixel = 0
idis.BackgroundColor = BrickColor.new("Really black")
idis.BackgroundTransparency = 0.5
idis.TextColor = BrickColor.new("White")
idis.Text = "Weapons: " ..wepstatus.. " "
idis.TextWrap = true
local back4 = Instance.new("Frame", gui)
back4.Position = UDim2.new(0, 200, 0, 200)
back4.Size = UDim2.new(0, 200, 0, 125)
back4.BorderSizePixel = 0
back4.Visible = false
back4.BackgroundColor = BrickColor.new("Reddish brown")
back4.BackgroundTransparency = 0.15
local idis = Instance.new("TextLabel", back4)
idis.Position = UDim2.new(0, 0, 0, 0)
idis.Size = UDim2.new(0, 200, 0, 50)
idis.BorderSizePixel = 0
idis.BackgroundColor = BrickColor.new("Really red")
idis.BackgroundTransparency = 0.5
idis.TextColor = BrickColor.new("White")
idis.Text = "Are you sure?"
idis.TextWrap = true
local idis2 = Instance.new("TextButton", back4)
idis2.Position = UDim2.new(0, 0, 0, 60)
idis2.Size = UDim2.new(0, 100, 0, 50)
idis2.BorderSizePixel = 5
idis2.BackgroundColor = BrickColor.new("Really red")
idis2.BackgroundTransparency = 0.5
idis2.TextColor = BrickColor.new("White")
idis2.Text = "Yes"
local idis3 = Instance.new("TextButton", back4)
idis3.Position = UDim2.new(0, 100, 0, 60)
idis3.Size = UDim2.new(0, 100, 0, 50)
idis3.BorderSizePixel = 5
idis3.BackgroundColor = BrickColor.new("Really red")
idis3.BackgroundTransparency = 0.5
idis3.TextColor = BrickColor.new("White")
idis3.Text = "No"
local back5 = Instance.new("Frame", gui)
back5.Position = UDim2.new(0, 200, 0, 200)
back5.Size = UDim2.new(0, 600, 0, 600)
back5.BorderSizePixel = 0
back5.Visible = false
back5.BackgroundColor = BrickColor.new("Really blue")
back5.BackgroundTransparency = 0.15
for i = 1, locations do
local idisi = Instance.new("TextButton", back5)
idisi.Position = UDim2.new(0, math.random(1, i*10), 0, math.random(1, i*10))
idisi.Size = UDim2.new(0, 1, 0, 1)
idisi.BorderSizePixel = 0
idisi.BackgroundColor = BrickColor.new("White")
idisi.BackgroundTransparency = 0.5
idisi.TextColor = BrickColor.new("White")
idisi.Text = "" ..i.. ""
wait()
end
id3.MouseButton1Click:connect(function()
if back2.Visible == false then
back2.Visible = true
id3.Text = "Close interface"
else
back2.Visible = false
id3.Text = "Open interface"
end
end)
id4.MouseButton1Click:connect(function()
if back5.Visible == false then
back5.Visible = true
id4.Text = "Close Flight Data"
else
back5.Visible = false
id4.Text = "Open Flight Data"
end
end)
idi4.MouseButton1Click:connect(function()
if back3.Visible == false then
back3.Visible = true
idi4.Text = "Close Weapons consol"
else
back3.Visible = false
idi4.Text = "Open Weapons console"
end
end)
id5.MouseButton1Click:connect(function()
if back4.Visible == false then
back4.Visible = true
id5.Text = "Close Realease switch"
else
back4.Visible = false
id5.Text = "Open Realease switch"
end
end)
idis2.MouseButton1Click:connect(function()
back4.Visible = false
end)
idis3.MouseButton1Click:connect(function()
back4.Visible = false
end)
id6.MouseButton1Click:connect(function()
gui:remove()
model:remove()
script:remove()
end)
|
local F, C, L = unpack(select(2, ...))
local CHAT = F:GetModule('Chat')
local split, strfind, strmatch, gmatch, gsub, sub = string.split, string.find, string.match, string.gmatch, string.gsub, string.sub
local pairs, ipairs, tonumber = pairs, ipairs, tonumber
local min, max, tremove = math.min, math.max, table.remove
local IsGuildMember, C_FriendList_IsFriend, IsGUIDInGroup, C_Timer_After = IsGuildMember, C_FriendList.IsFriend, IsGUIDInGroup, C_Timer.After
local Ambiguate, UnitIsUnit, BNGetGameAccountInfoByGUID, GetTime, SetCVar = Ambiguate, UnitIsUnit, BNGetGameAccountInfoByGUID, GetTime, SetCVar
local GetItemInfo, GetItemStats = GetItemInfo, GetItemStats
local LE_ITEM_CLASS_WEAPON, LE_ITEM_CLASS_ARMOR = LE_ITEM_CLASS_WEAPON, LE_ITEM_CLASS_ARMOR
local BN_TOAST_TYPE_CLUB_INVITATION = BN_TOAST_TYPE_CLUB_INVITATION or 6
-- Filter Chat symbols
local msgSymbols = {'`', '~', '@', '#', '^', '*', '!', '?', '。', '|', ' ', '—', '——', '¥', '’', '‘', '“', '”', '【', '】', '『', '』', '《', '》', '〈', '〉', '(', ')', '〔', '〕', '、', ',', ':', ',', '_', '/', '~', '%-', '%.'}
local FilterList = {}
function CHAT:UpdateFilterList()
F.SplitList(FilterList, C.chat.keywordsList, true)
end
-- ECF strings compare
local last, this = {}, {}
function CHAT:CompareStrDiff(sA, sB) -- arrays of bytes
local len_a, len_b = #sA, #sB
for j = 0, len_b do
last[j+1] = j
end
for i = 1, len_a do
this[1] = i
for j = 1, len_b do
this[j+1] = (sA[i] == sB[j]) and last[j] or (min(last[j+1], this[j], last[j]) + 1)
end
for j = 0, len_b do
last[j+1] = this[j+1]
end
end
return this[len_b+1] / max(len_a, len_b)
end
C.BadBoys = {} -- debug
local chatLines, prevLineID, filterResult = {}, 0, false
function CHAT:GetFilterResult(event, msg, name, flag, guid)
if name == C.Name or (event == 'CHAT_MSG_WHISPER' and flag == 'GM') or flag == 'DEV' then
return
elseif guid and (IsGuildMember(guid) or BNGetGameAccountInfoByGUID(guid) or C_FriendList_IsFriend(guid) or (IsInInstance() and IsGUIDInGroup(guid))) then
return
end
if C.BadBoys[name] and C.BadBoys[name] >= 5 then return true end
local filterMsg = gsub(msg, '|H.-|h(.-)|h', '%1')
filterMsg = gsub(filterMsg, '|c%x%x%x%x%x%x%x%x', '')
filterMsg = gsub(filterMsg, '|r', '')
-- Trash Filter
for _, symbol in ipairs(msgSymbols) do
filterMsg = gsub(filterMsg, symbol, '')
end
local matches = 0
for keyword in pairs(FilterList) do
if keyword ~= '' then
local _, count = gsub(filterMsg, keyword, '')
if count > 0 then
matches = matches + 1
end
end
end
if matches >= 1 then
return true
end
-- ECF Repeat Filter
local msgTable = {name, {}, GetTime()}
if filterMsg == '' then filterMsg = msg end
for i = 1, #filterMsg do
msgTable[2][i] = filterMsg:byte(i)
end
local chatLinesSize = #chatLines
chatLines[chatLinesSize+1] = msgTable
for i = 1, chatLinesSize do
local line = chatLines[i]
if line[1] == msgTable[1] and ((msgTable[3] - line[3] < .6) or CHAT:CompareStrDiff(line[2], msgTable[2]) <= .1) then
tremove(chatLines, i)
return true
end
end
if chatLinesSize >= 30 then tremove(chatLines, 1) end
end
function CHAT:UpdateChatFilter(event, msg, author, _, _, _, flag, _, _, _, _, lineID, guid)
if lineID == 0 or lineID ~= prevLineID then
prevLineID = lineID
local name = Ambiguate(author, 'none')
filterResult = CHAT:GetFilterResult(event, msg, name, flag, guid)
if filterResult then C.BadBoys[name] = (C.BadBoys[name] or 0) + 1 end
end
return filterResult
end
-- Block addon msg
local addonBlockList = C.chat.addonBlockList
local cvar
local function toggleCVar(value)
value = tonumber(value) or 1
SetCVar(cvar, value)
end
function CHAT:ToggleChatBubble(party)
cvar = 'chatBubbles'..(party and 'Party' or '')
if not GetCVarBool(cvar) then return end
toggleCVar(0)
C_Timer_After(.01, toggleCVar)
end
function CHAT:UpdateAddOnBlocker(event, msg, author)
local name = Ambiguate(author, 'none')
if UnitIsUnit(name, 'player') then return end
for _, word in ipairs(addonBlockList) do
if strfind(msg, word) then
if event == 'CHAT_MSG_SAY' or event == 'CHAT_MSG_YELL' then
CHAT:ToggleChatBubble()
elseif event == 'CHAT_MSG_PARTY' or event == 'CHAT_MSG_PARTY_LEADER' then
CHAT:ToggleChatBubble(true)
end
return true
end
end
end
-- Block trash clubs
local trashClubs = {'站桩', '致敬我们'}
function CHAT:BlockTrashClub()
if self.toastType == BN_TOAST_TYPE_CLUB_INVITATION then
local text = self.DoubleLine:GetText() or ''
for _, name in pairs(trashClubs) do
if strfind(text, name) then
self:Hide()
return
end
end
end
end
function CHAT:ChatFilter()
if C.chat.filters then
self:UpdateFilterList()
ChatFrame_AddMessageEventFilter('CHAT_MSG_CHANNEL', self.UpdateChatFilter)
ChatFrame_AddMessageEventFilter('CHAT_MSG_SAY', self.UpdateChatFilter)
ChatFrame_AddMessageEventFilter('CHAT_MSG_YELL', self.UpdateChatFilter)
ChatFrame_AddMessageEventFilter('CHAT_MSG_WHISPER', self.UpdateChatFilter)
ChatFrame_AddMessageEventFilter('CHAT_MSG_EMOTE', self.UpdateChatFilter)
ChatFrame_AddMessageEventFilter('CHAT_MSG_TEXT_EMOTE', self.UpdateChatFilter)
ChatFrame_AddMessageEventFilter('CHAT_MSG_RAID', self.UpdateChatFilter)
ChatFrame_AddMessageEventFilter('CHAT_MSG_RAID_LEADER', self.UpdateChatFilter)
end
if C.chat.blockAddonAlert then
ChatFrame_AddMessageEventFilter('CHAT_MSG_SAY', self.UpdateAddOnBlocker)
ChatFrame_AddMessageEventFilter('CHAT_MSG_WHISPER', self.UpdateAddOnBlocker)
ChatFrame_AddMessageEventFilter('CHAT_MSG_EMOTE', self.UpdateAddOnBlocker)
ChatFrame_AddMessageEventFilter('CHAT_MSG_PARTY', self.UpdateAddOnBlocker)
ChatFrame_AddMessageEventFilter('CHAT_MSG_PARTY_LEADER', self.UpdateAddOnBlocker)
ChatFrame_AddMessageEventFilter('CHAT_MSG_RAID', self.UpdateAddOnBlocker)
ChatFrame_AddMessageEventFilter('CHAT_MSG_RAID_LEADER', self.UpdateAddOnBlocker)
ChatFrame_AddMessageEventFilter('CHAT_MSG_INSTANCE_CHAT', self.UpdateAddOnBlocker)
ChatFrame_AddMessageEventFilter('CHAT_MSG_INSTANCE_CHAT_LEADER', self.UpdateAddOnBlocker)
ChatFrame_AddMessageEventFilter('CHAT_MSG_CHANNEL', self.UpdateAddOnBlocker)
end
hooksecurefunc(BNToastFrame, 'ShowToast', self.BlockTrashClub)
end
|
bmd.openurl("https://www.youtube.com/c/JiPi_YT/videos")
|
package("spdlog")
set_homepage("https://github.com/gabime/spdlog")
set_description("Fast C++ logging library.")
set_urls("https://github.com/gabime/spdlog/archive/$(version).zip",
"https://github.com/gabime/spdlog.git")
add_versions("v1.9.0", "61f751265cfce8fb17f67e18fa1ad00077280c080008252d9e8f0fbab5c30662")
add_versions("v1.8.5", "6e66c8ed4c014b0fb00c74d34eea95b5d34f6e4b51b746b1ea863dc3c2e854fd")
add_versions("v1.8.2", "f0410b12b526065802b40db01304783550d3d20b4b6fe2f8da55f9d08ed2035d")
add_versions("v1.8.1", "eed0095a1d52d08a0834feda146d4f9148fa4125620cd04d8ea57e0238fa39cd")
add_versions("v1.8.0", "3cc41508fcd79e5141a6ef350506ef82982ca42a875e0588c02c19350ac3702e")
add_versions("v1.5.0", "87e87c989f15d6b9f5379385aec1001c89a42941341ebaa09ec895b98a00efb4")
add_versions("v1.4.2", "56b90f0bd5b126cf1b623eeb19bf4369516fa68f036bbc22d9729d2da511fb5a")
add_versions("v1.3.1", "db6986d0141546d4fba5220944cc1f251bd8afdfc434bda173b4b0b6406e3cd0")
add_configs("header_only", { description = "Use header only", default = true, type = "boolean"})
add_configs("fmt_external", { description = "Use external fmt library instead of bundled", default = false, type = "boolean"})
add_configs("noexcept", { description = "Compile with -fno-exceptions. Call abort() on any spdlog exceptions", default = false, type = "boolean"})
on_load(function (package)
if not package:config("header_only") then
package:add("defines", "SPDLOG_COMPILE_LIB")
end
if package:config("fmt_external") then
package:add("defines", "SPDLOG_FMT_EXTERNAL")
end
if package:version():ge("1.4.0") and not package:config("header_only") then
package:add("deps", "cmake")
end
if package:config("fmt_external") then
package:add("deps", "fmt", {configs = {header_only = true}})
end
end)
on_install(function (package)
if package:version():lt("1.4.0") or package:config("header_only") then
os.cp("include", package:installdir())
return
end
local configs = {}
if package:config("shared") and is_plat("windows") then
raise("spdlog shared lib is not yet supported under windows!")
end
table.insert(configs, "-DSPDLOG_BUILD_SHARED=" .. (package:config("shared") and "ON" or "OFF"))
table.insert(configs, "-DSPDLOG_FMT_EXTERNAL=" .. (package:config("fmt_external") and "ON" or "OFF"))
table.insert(configs, "-SPDLOG_NO_EXCEPTIONS=" .. (package:config("noexcept") and "ON" or "OFF"))
table.insert(configs, "-DSPDLOG_BUILD_TESTS=OFF")
table.insert(configs, "-DSPDLOG_BUILD_EXAMPLE=OFF")
import("package.tools.cmake").install(package, configs)
end)
on_test(function (package)
assert(package:has_cxxfuncs("spdlog::info(\"\")", {includes = "spdlog/spdlog.h", configs = {languages = "c++11"}}))
end)
|
local LoggerEnums = require "LoggerEnums"
local Config = {
logging = {
mode = LoggerEnums.mode.file,
level = LoggerEnums.level.debug,
filePath = getScriptPath() .. "\\Logs\\"
},
server = {
host = "127.0.0.1",
port = 34130,
timeout = 1 -- In seconds.
}
script = {
loopDelayOnError = 100 -- In milliseconds.
waitForClientConnectionDelay = 100 -- In milliseconds.
waitForClientConnectionAttemptLoggingInterval = 20
}
}
return Config
|
local util = require 'monochrome.util'
local Default = { '#EBEBEB', '#101010' }
local Subtle = { '#F1F5F9', '#0A1219' }
local CoolGray = { '#F9FAFB', '#111827' }
local Photon = { '#c6c6c6', '#262626' }
local Amplified = { '#FFFFFF', '#000000' }
-- LuaFormatter off
local colors = {
bright_red = '#ffc4c4',
bright_green = '#eff6ab',
bright_yellow = '#ffe6b5',
bright_blue = '#c9e6fd',
bright_purple = '#f7d7ff',
bright_aqua = '#ddfcf8',
bright_orange = '#ffd3c2',
neutral_red = '#eca8a8',
neutral_green = '#ccd389',
neutral_yellow = '#efd5a0',
neutral_blue = '#a5c6e1',
neutral_purple = '#e1bee9',
neutral_aqua = '#c7ebe6',
neutral_orange = '#efb6a0',
faded_red = '#ec8989',
faded_green = '#c9d36a',
faded_yellow = '#ceb581',
faded_blue = '#8abae1',
faded_purple = '#db9fe9',
faded_aqua = '#abebe2',
faded_orange = '#E69E83',
base03 = '#002b36',
base02 = '#073642',
base01 = '#586e75',
base00 = '#657b83',
base0 = '#839496',
base1 = '#93a1a1',
base2 = '#eee8d5',
base3 = '#fdf6e3',
yellow = '#b58900',
orange = '#cb4b16',
red = '#dc322f',
magenta = '#d33682',
violet = '#6c71c4',
blue = '#268bd2',
cyan = '#2aa198',
green = '#719e07',
}
-- LuaFormatter on
local color_style
if vim.g.monochrome_style == 'default' then
color_style = Default
elseif vim.g.monochrome_style == 'subtle' then
color_style = Subtle
elseif vim.g.monochrome_style == 'amplified' then
color_style = Amplified
elseif vim.g.monochrome_style == 'coolgray' then
color_style = CoolGray
elseif vim.g.monochrome_style == 'photon' then
color_style = Photon
elseif vim.g.monochrome_style == 'custom' then
color_style = vim.g.monochrome_custom_style
else
color_style = Default
end
local fg, bg = unpack(color_style)
if vim.o.background == 'light' then
bg, fg = fg, bg
end
for k, v in pairs(util.colorize(fg, bg)) do
colors[k] = v
end
return colors
|
--[[
QA API: Aligns a question to most likely predicates and entities from a structured knowledge base.
Given the question, produces a ranked list of the most likely {predicate, entity pairs}
--]]
local QA_API = torch.class('softmax.AttentionAPI')
function QA_API:__init(config)
-- load modelf
self.config = config
self.model_path = config.model_path or "models/cm_5.th"
self.models = {}
self.path_to_idx = {}
--self.model = self:load_model(self.model_path)
end
-- Loads model from current model path and sets the network to load from that model
-- Adds model to our index
function QA_API:load_model_from_path(model_path)
assert(model_path ~= nil, "Must specify path to load model from")
local model = dmn.Attention_Network.load(model_path)
-- dmn.logger:print configurations
model:print_config()
-- set it to predict mode
model:disable_dropouts()
dmn.logger:print("Adding model at index" .. #self.models)
table.insert(self.models, model)
self.path_to_idx[model_path] = #self.models
return model
end
function QA_API:load_model_from_binary(model)
assert(model ~= nil, "Must specify model binary to load from")
-- dmn.logger:print configurations
model:print_config()
-- set it to predict mode
model:disable_dropouts()
table.insert(self.models, model)
self.path_to_idx[model:get_path(model.model_epoch)] = #self.models
return model
end
-- Reranks predicates and entities for a question
-- returns: rankings, likelihoods, question predicate/entity focus
function QA_API:align(question, predicates, entities, beam_size)
assert(question ~= nil, "Must specify question to use for Attention Network")
assert(predicates ~= nil, "Must specify candidate predicates to use for Attention Network")
assert(entities ~= nil, "Must specify candidate entities to use for Attention Network")
assert(beam_size ~= nil, "Beam size must be specified")
-- get all results from model ensemble and aggregate them
local ranking_to_idx = {}
local final_rankings = {}
local final_likelihoods = {}
local returned_rankings = {}
local returned_likelihoods = {}
local question_pred_focuses, question_entity_focuses
if #predicates == 0 then
for i = 1, beam_size do
table.insert(predicates, "FOO")
end
end
if #entities == 0 then
for i = 1, beam_size do
table.insert(entities, "BAR")
end
end
assert(#predicates > 0, "Must give positive # of predicates")
assert(#entities > 0, "Must give positive # of entities")
for i = 1, #self.models do
local cur_model = self.models[i]
local rankings, likelihoods, cur_question_pred_focuses, cur_question_entity_focuses =
cur_model:predict(question, predicates, entities, beam_size)
question_pred_focuses = cur_question_pred_focuses
question_entity_focuses = cur_question_entity_focuses
--assert(false, json.encode(question_entity_focuses))
cur_size = 0
for j = 1, #rankings do
local ranking = rankings[j]
concated_ranking = table.concat(ranking)
local cur_idx = cur_size + 1
if ranking_to_idx[concated_ranking] ~= nil then
cur_idx = ranking_to_idx[concated_ranking]
else
ranking_to_idx[tostring(concated_ranking)] = cur_size
cur_size = cur_size + 1
end
local cur_cost = (final_rankings[cur_idx] == nil) and 0 or final_rankings[cur_idx][1]
final_rankings[cur_idx] = {cur_cost + likelihoods[j], ranking}
end
end
reranked_values = dmn.functions.topk(final_rankings, #final_rankings)
for i = 1, #reranked_values do
local log_loss = reranked_values[i][1]
local ranking = reranked_values[i][2]
table.insert(returned_rankings, ranking)
table.insert(returned_likelihoods, log_loss)
end
return returned_rankings, returned_likelihoods, question_pred_focuses, question_entity_focuses
end
-- Reranks predicates/entities for a single model
function QA_API:model_align(model, question, predicates, entities, beam_size)
assert(question ~= nil, "Must specify question to use for Attention Network")
assert(predicates ~= nil, "Must specify candidate predicates to use for Attention Network")
assert(entities ~= nil, "Must specify candidate entities to use for Attention Network")
assert(beam_size ~= nil, "Beam size must be specified")
assert(model ~= nil, "Model to predict with must not be null")
local rankings, likelihoods, question_pred_focuses, question_entity_focuses =
model:predict(question, predicates, entities, beam_size)
return rankings, likelihoods, question_pred_focuses, question_entity_focuses
end
-- returns best predicate and name for question
function QA_API:answer_v2(question, min_ngrams, max_ngrams, num_results, beam_size, rerank)
assert(question ~= nil, "Must specify question to answer")
assert(min_ngrams ~= nil, "Must specify number of ngrams to use")
assert(max_ngrams ~= nil, "Must specify max number of ngrams to use")
assert(beam_size ~= nil, "Must specify beam size to use for reranking")
assert(num_results ~= nil, "Must specify number of results to request from api")
assert(rerank ~= nil, "Must specify whether to rerank ngrams or use raw ones")
local num_facts = 10000
dmn.logger:print("Answering question " .. question)
dmn.logger:print("Getting all ids")
all_possibilities, log_likelihoods = softmax.entity_linker_api:candidate_ngrams(
softmax.qa_api.models[1],
question,
min_ngrams,
max_ngrams,
beam_size,
rerank)
-- take the top one
local query = {all_possibilities[1]}
local ids, all_names, all_types =
softmax.entity_linker_api:candidate_entities(query, num_results)
dmn.logger:print("Generating candidates")
--[[
candidate_predicates = {
'/people/person/composer',
'/song/writer/author',
'/people/person/place_of_birth'
}
candidate_entities = {'Foo bar',
'Bar foo',
'Bye bye love',
'song'}
]]
candidate_ids = {}
fact_mappings = {}
local candidate_predicates, candidate_entities, candidate_ids, fact_mappings =
datasets.freebase_api:facts(ids, num_facts)
dmn.logger:print("Reranking candidates")
local rankings, likelihoods, question_pred_focuses, question_entity_focuses
= softmax.qa_api:align(
question,
candidate_predicates,
candidate_entities,
beam_size
)
likely_predicates = {}
likely_names = {}
likely_facts = {}
likely_ids = {}
for i = 1, #rankings do
local ranking = rankings[i]
local entity_ranking = ranking[2]
local predicate_ranking = ranking[1]
local likely_id = candidate_ids[entity_ranking]
local likely_name = candidate_entities[entity_ranking]
local likely_predicate = candidate_predicates[predicate_ranking]
local likely_fact = fact_mappings[likely_name .. " " .. likely_predicate]
if likely_fact == nil then
--dmn.logger:print("NULL FACT")
likely_fact = "NO FACT"
end
table.insert(likely_ids, likely_id)
table.insert(likely_predicates, likely_predicate)
table.insert(likely_names, likely_name)
table.insert(likely_facts, likely_fact)
end
return likely_predicates, likely_names, likely_ids, likely_facts, fact_mappings,
likelihoods, question_pred_focuses, question_entity_focuses,
candidate_predicates, candidate_entities
end
-- returns best predicate and name for question
function QA_API:answer_v3(question, min_ngrams, max_ngrams, num_results, beam_size, rerank)
assert(question ~= nil, "Must specify question to answer")
assert(min_ngrams ~= nil, "Must specify number of ngrams to use")
assert(max_ngrams ~= nil, "Must specify max number of ngrams to use")
assert(beam_size ~= nil, "Must specify beam size to use for reranking")
assert(num_results ~= nil, "Must specify number of results to request from api")
assert(rerank ~= nil, "Must specify whether to rerank ngrams or use raw ones")
local num_facts = 10000
dmn.logger:print("Answering question " .. question)
dmn.logger:print("Getting all ids")
all_possibilities, log_likelihoods = softmax.entity_linker_api:candidate_ngrams(
softmax.qa_api.models[1],
question,
min_ngrams,
max_ngrams,
beam_size,
rerank)
-- take the top one
local query = {all_possibilities[1]}
local ids, all_names, all_types =
softmax.entity_linker_api:candidate_entities(query, num_results)
dmn.logger:print("Generating candidates")
local candidate_predicates, candidate_entities, fact_mappings =
datasets.freebase_api:facts(ids, num_facts)
dmn.logger:print("Reranking candidates")
local entity_rankings, likelihoods, question_pred_focuses, question_entity_focuses
= softmax.qa_api:align(
question,
{'foo'},
candidate_entities,
beam_size
)
local predicate_rankings, likelihoods, question_pred_focuses, question_entity_focuses
= softmax.qa_api:align(
question,
candidate_predicates,
candidate_entities,
beam_size
)
likely_predicates = {}
likely_names = {}
likely_facts = {}
for i = 1, #entity_rankings do
local entity_ranking = entity_rankings[i][2]
local predicate_ranking = predicate_rankings[i][1]
local likely_name = candidate_entities[entity_ranking]
local likely_predicate = candidate_predicates[predicate_ranking]
local likely_fact = fact_mappings[likely_name .. " " .. likely_predicate]
if likely_fact == nil then
--dmn.logger:print("NULL FACT")
likely_fact = "NO FACT"
end
table.insert(likely_predicates, likely_predicate)
table.insert(likely_names, likely_name)
table.insert(likely_facts, likely_fact)
end
return likely_predicates, likely_names, likely_facts, fact_mappings,
likelihoods, question_pred_focuses, question_entity_focuses,
candidate_predicates, candidate_entities
end
function QA_API:answer(question, ngrams, filter_beam_size, rank_beam_size, query_beam_size, rerank)
assert(question ~= nil, "Must specify question to answer")
assert(ngrams ~= nil, "Must specify number of ngrams to use")
assert(filter_beam_size ~= nil, "Must specify filter beam size to use")
assert(rank_beam_size ~= nil, "Must specify rank beam size to use")
assert(query_beam_size ~= nil, "Must specify query beam size to use")
assert(rerank ~= nil, "Must specify whether to rerank ngrams or use raw ones")
dmn.logger:print("Answering question " .. question)
dmn.logger:print("Getting all ids")
all_possibilities, log_likelihoods = softmax.entity_linker_api:candidate_ngrams(
softmax.qa_api.models[1],
question,
ngrams,
query_beam_size,
rerank)
local ids, all_names, all_types = softmax.entity_linker_api:candidate_entities(all_possibilities, 500)
dmn.logger:print("Filtering ids and names from")
local filtered_ids, filtered_names, filtered_types =
softmax.entity_linker_api:filter_entities(
softmax.qa_api,
question,
ids,
all_names,
all_types,
query_beam_size)
dmn.logger:print("Generating candidates")
local candidate_predicates, candidate_entities, fact_mappings =
softmax.entity_linker_api:candidate_facts(filtered_ids, filtered_names)
dmn.logger:print("Reranking candidates")
local rankings, likelihoods, question_pred_focuses, question_entity_focuses
= softmax.qa_api:align(
question,
candidate_predicates,
candidate_entities,
rank_beam_size
)
likely_predicates = {}
likely_names = {}
likely_facts = {}
for i = 1, #rankings do
local ranking = rankings[i]
local entity_ranking = ranking[2]
local predicate_ranking = ranking[1]
local likely_name = candidate_entities[entity_ranking]
local likely_predicate = candidate_predicates[predicate_ranking]
local likely_fact = fact_mappings[likely_name .. " " .. likely_predicate]
table.insert(likely_predicates, likely_predicate)
table.insert(likely_names, likely_name)
table.insert(likely_facts, likely_fact)
end
return likely_predicates, likely_names, likely_facts,
likelihoods,
question_pred_focuses, question_entity_focuses,
candidate_predicates, candidate_entities
end
|
-- Busted runner
require "busted.runner"()
-- Modules
local Dispatcher = require "dispatcher"
local Event = require "event"
describe("Event dispatcher", function()
it("should be createable", function()
local dispatcher = Dispatcher:new()
assert.same("table", type(dispatcher))
end)
it("should be possible to register a single listener", function()
local dispatcher = Dispatcher:new()
dispatcher:on("event-name", function() end)
assert.same(1, #dispatcher:getListeners("event-name"))
end)
it("should be possible to register multiple listeners", function()
local dispatcher = Dispatcher:new()
dispatcher:on("event-name", function() end)
dispatcher:on("event-name", function() end)
assert.same(2, #dispatcher:getListeners("event-name"))
end)
it("should be possible to register a listener to multiple events", function()
local dispatcher = Dispatcher:new()
dispatcher:on("event-name-1", function() end)
dispatcher:on("event-name-2", function() end)
assert.same(1, #dispatcher:getListeners("event-name-1"))
assert.same(1, #dispatcher:getListeners("event-name-2"))
end)
it("should not be possible to register non-callable listeners", function()
local dispatcher = Dispatcher:new()
assert.has_error(function()
dispatcher:addListener("event-name", true)
end, "A registered listener must be callable")
end)
it("should be possible to remove a listener", function()
local dispatcher = Dispatcher:new()
local listener1 = function() end
local listener2 = function() end
dispatcher:on("event-name", listener1)
dispatcher:on("event-name", listener2)
assert.same(2, #dispatcher:getListeners("event-name"))
dispatcher:removeListener("event-name", listener1)
assert.same(1, #dispatcher:getListeners("event-name"))
dispatcher:removeListener("event-name", listener2)
assert.same(0, #dispatcher:getListeners("event-name"))
end)
it("should be possible to remove all listeners for a given event", function()
local dispatcher = Dispatcher:new()
local listener1 = function() end
local listener2 = function() end
dispatcher:on("event-name", listener1)
dispatcher:on("event-name", listener2)
dispatcher:on("another-event", listener1)
dispatcher:on("another-event", listener2)
assert.same(2, #dispatcher:getListeners("event-name"))
assert.same(2, #dispatcher:getListeners("another-event"))
dispatcher:removeListeners("event-name")
assert.same(0, #dispatcher:getListeners("event-name"))
assert.same(2, #dispatcher:getListeners("another-event"))
end)
it("should be possible to remove all listeners", function()
local dispatcher = Dispatcher:new()
local listener1 = function() end
local listener2 = function() end
dispatcher:on("event-name", listener1)
dispatcher:on("event-name", listener2)
dispatcher:on("another-event", listener1)
dispatcher:on("another-event", listener2)
assert.same(2, #dispatcher:getListeners("event-name"))
assert.same(2, #dispatcher:getListeners("another-event"))
dispatcher:removeAllListeners()
assert.same(0, #dispatcher:getListeners("event-name"))
assert.same(0, #dispatcher:getListeners("another-event"))
end)
it("should be possible to dispatch an event object", function()
local dispatcher = Dispatcher:new()
local event1 = Event:new()
local event2 = Event:new()
dispatcher:addListener("event-name", function() end)
dispatcher:dispatch("event-name", event1)
assert.truthy(event1.isDispatched)
assert.is_not.truthy(event2.isDispatched)
end)
it("should be possible to dispatch without an event object", function()
local dispatcher = Dispatcher:new()
dispatcher:addListener("event-name", function() end)
dispatcher:dispatch("event-name")
assert.truthy(true)
end)
it("should be possible to pass data within an event object", function()
local dispatcher = Dispatcher:new()
local event = Event:new({
changed = false
})
dispatcher:on("event-name", function(e)
e.data.changed = true
end)
dispatcher:dispatch("event-name", event)
assert.truthy(event.data)
assert.truthy(event.data.changed)
end)
it("should be possible to stop the event propagation", function()
local dispatcher = Dispatcher:new()
local event = Event:new()
local listener1 = spy.new(function(e)
e:stopPropagation()
end)
local listener2 = spy.new(function() end)
dispatcher:on("event-name", listener1)
dispatcher:on("event-name", listener2)
dispatcher:on("event-name", listener2)
dispatcher:dispatch("event-name", event)
assert.spy(listener1).was.called()
assert.spy(listener2).was_not.called()
end)
it("should be possible to stop the event propagation event without an event object", function()
local dispatcher = Dispatcher:new()
local listener1 = spy.new(function(e)
e:stopPropagation()
end)
local listener2 = spy.new(function() end)
dispatcher:on("event-name", listener1)
dispatcher:on("event-name", listener2)
dispatcher:dispatch("event-name")
assert.spy(listener1).was.called()
assert.spy(listener2).was_not.called()
end)
it("should be possible to have multiple dispatchers (event busses)", function()
local dispatcher1 = Dispatcher:new()
local dispatcher2 = Dispatcher:new()
local listener = function() end
dispatcher1:on("event-name", listener)
dispatcher2:on("event-name", listener)
assert.same(1, #dispatcher1:getListeners("event-name"))
assert.same(1, #dispatcher2:getListeners("event-name"))
end)
it("should be possible to use the method :on instead of :addListener", function()
local dispatcher = Dispatcher:new()
local event = Event:new()
local listener = spy.new(function() end)
dispatcher:on("event-name", listener)
dispatcher:dispatch("event-name", event)
assert.spy(listener).was.called()
end)
it("should be possible to run listeners in order", function()
local dispatcher = Dispatcher:new()
local event = Event:new({
number = 1
})
dispatcher:on("event-name", function(e)
e.data.number = e.data.number + 1
end, 4)
dispatcher:on("event-name", function(e)
e.data.number = e.data.number + 2
end, 3)
dispatcher:on("event-name", function(e)
e.data.number = e.data.number * 2
end, 2)
dispatcher:on("event-name", function(e)
e.data.number = e.data.number * 3
end, 1)
dispatcher:dispatch("event-name", event)
assert.same(24, event.data.number)
assert.is_not.same(9, event.data.number)
end)
it("should be possible to register multiple listeners for the same priority", function()
local dispatcher = Dispatcher:new()
local event = Event:new({
number = 1
})
dispatcher:on("event-name", function(e)
e.data.number = e.data.number + 1
end, 1)
dispatcher:on("event-name", function(e)
e.data.number = e.data.number + 1
end, 1)
dispatcher:on("event-name", function(e)
e.data.number = e.data.number * 2
end, 2)
dispatcher:on("event-name", function(e)
e.data.number = e.data.number * 2
end, 2)
dispatcher:dispatch("event-name", event)
assert.same(6, event.data.number)
assert.is_not.same(12, event.data.number)
end)
it("should not be possible to add a non-numeric priority", function()
local dispatcher = Dispatcher:new()
assert.has_error(function()
dispatcher:addListener("event-name", function() end, "NaN")
end, "priority must be a number")
end)
it("should do nothing if removeListeners is called without an eventName", function()
local dispatcher = Dispatcher:new()
local listener = function() end
dispatcher:on("event-name", listener)
dispatcher:on("event-name", listener)
dispatcher:removeListeners()
assert.same(2, #dispatcher:getListeners("event-name"))
end)
end)
|
local t = Def.ActorFrame { }
for player_index, player_number in ipairs(GAMESTATE:GetEnabledPlayers()) do
-- Modifiers
local MOD_SIZE = 48
-- Frame
local mod_frame = Def.ActorFrame {
InitCommand = function(self)
self:x(-512)
:y(SCREEN_HEIGHT - 158)
end,
OnCommand = function(self)
self:sleep(0.5)
:tween(0.8, "TweenType_Decelerate")
:x(224)
end
}
---- Loop trough modifiers
local mods = GAMESTATE:GetPlayerState(player_number):GetPlayerOptionsArray("ModsLevel_Preferred")
local mod_filter = function(a)
return a ~= "1x" and a ~= "Overhead"
end
for mod_index, mod in ipairs(table.find_all(mods, mod_filter)) do
---- Modifier Frame
local m = Def.ActorFrame {
InitCommand = function(self)
self:x((MOD_SIZE + 16) * mod_index)
end,
}
---- Background
m[#m+1] = Def.Quad {
InitCommand = function(self)
self:zoomto(MOD_SIZE, MOD_SIZE)
:diffuse(ThemeColor.Purple)
:diffusebottomedge(ColorDarkTone(ThemeColor.Purple))
end
}
---- Label
m[#m+1] = Def.BitmapText {
Font = "Common body",
InitCommand = function(self)
local size = (MOD_SIZE/2) - 4
self:settext(mod)
:scaletofit(-size, -size, size, size)
end
}
mod_frame[#mod_frame+1] = m
end
t[#t+1] = mod_frame
-- Score display
local SCORE_FRAME_WIDTH = 360
---- Frame
local score_frame = Def.ActorFrame {
InitCommand = function(self)
self:x(player_number == "PlayerNumber_P1" and -SCORE_FRAME_WIDTH or SCREEN_WIDTH + SCORE_FRAME_WIDTH)
:y(SCREEN_HEIGHT - 96)
end,
OnCommand = function(self)
self:tween(0.8, "TweenType_Decelerate")
:x(player_number == "PlayerNumber_P1" and SCORE_FRAME_WIDTH/2 or SCREEN_WIDTH - SCORE_FRAME_WIDTH/2)
:y(SCREEN_HEIGHT - 96)
end
}
---- Background
score_frame[#score_frame+1] = Def.Sprite {
Texture = THEME:GetPathG("", "Gameplay/ScoreHolder.png"),
InitCommand = function(self)
self:diffuse(PlayerColors[player_number])
:zoom(0.60)
:rotationy(player_number == "PlayerNumber_P1" and 0 or 180)
end
}
---- Score
score_frame[#score_frame+1] = Def.RollingNumbers {
Font = "Common body",
InitCommand = function(self)
self:diffuse(ThemeColor.White)
:shadowcolor(ThemeColor.Black)
:shadowlength(1)
:set_chars_wide(7)
:set_approach_seconds(0.5)
:set_leading_attribute{ Diffuse=ThemeColor.Black }
end,
ScoreChangedMessageCommand = function(self, data)
if data.PlayerNumber ~= player_number then return end
local stage_stats = STATSMAN:GetCurStageStats()
self:target_number(get_score(GAMESTATE:GetCurrentSteps(data.PlayerNumber), stage_stats:GetPlayerStageStats(data.PlayerNumber), true))
end,
}
---- Background (Difficulty)
score_frame[#score_frame+1] = Def.Sprite {
Texture = THEME:GetPathG("", "Gameplay/DifficultyHolder.png"),
InitCommand = function(self)
local difficulty = GAMESTATE:GetCurrentSteps(player_number):GetDifficulty()
self:diffuse(ThemeColor.Black)
:zoom(0.60)
:y(-58)
:x(player_number == "PlayerNumber_P1" and -58 or 58)
:rotationy(player_number == "PlayerNumber_P1" and 0 or 180)
end
}
---- Difficulty name
score_frame[#score_frame+1] = Def.BitmapText {
Font = "Common Body",
InitCommand = function(self)
local difficulty = GAMESTATE:GetCurrentSteps(player_number):GetDifficulty()
self:diffuse(ThemeColor.White)
:settext(THEME:GetString("Difficulty", difficulty))
:diffuse(ThemeColor.White)
:shadowcolor(ThemeColor.Black)
:shadowlength(1)
:zoom(0.5)
:halign(player_number == "PlayerNumber_P1" and 1 or 0)
:y(-54)
:x(player_number == "PlayerNumber_P1" and -35 or 35)
:shadowcolor(ThemeColor.Black)
:shadowlength(1)
end,
}
---- Difficulty level
score_frame[#score_frame+1] = Def.BitmapText {
Font = "MusicWheel Difficulty",
InitCommand = function(self)
local meter = GAMESTATE:GetCurrentSteps(player_number):GetMeter()
local difficulty = GAMESTATE:GetCurrentSteps(player_number):GetDifficulty()
self:diffuse(ThemeColor.White)
:settext(meter)
:diffuse(DifficultyColors[difficulty])
:shadowcolor(ThemeColor.Black)
:shadowlength(1)
:halign(player_number == "PlayerNumber_P1" and 0 or 1)
:y(-54)
:x(player_number == "PlayerNumber_P1" and -25 or 25)
:shadowcolor(ThemeColor.Black)
:shadowlength(1)
end,
}
t[#t+1] = score_frame
-- Life display
local LIFE_FRAME_WIDTH = 650
local LIFE_FRAME_HEIGHT = 34
---- Frame
local life_frame = Def.ActorFrame {
InitCommand = function(self)
self:x(player_number == "PlayerNumber_P1" and PlayerP1X() or PlayerP2X())
:y(-48)
end,
OnCommand = function(self)
self:tween(0.8, "TweenType_Decelerate" )
:x(player_number == "PlayerNumber_P1" and PlayerP1X() or PlayerP2X())
:y(48)
end
}
---- Background
life_frame[#life_frame+1] = Def.Quad {
InitCommand = function(self)
self:zoomto(LIFE_FRAME_WIDTH, LIFE_FRAME_HEIGHT)
:diffuse(PlayerColors[player_number])
:diffusealpha(0.4)
end
}
---- Life Meter
life_frame[#life_frame+1] = Def.Quad {
InitCommand = function(self)
self:zoomto(0, LIFE_FRAME_HEIGHT)
:halign(player_number == "PlayerNumber_P1" and 0 or 1)
:x(player_number == "PlayerNumber_P1" and -LIFE_FRAME_WIDTH/2 or LIFE_FRAME_WIDTH/2)
:diffuse(ThemeColor.Green)
end,
LifeChangedMessageCommand = function(self, data)
if data.Player ~= player_number then return end
local life = data.LifeMeter:GetLife()
local state = "Regular"
if data.LifeMeter:IsInDanger() then state = "Danger"
elseif data.LifeMeter:IsHot() then state = "Hot" end
if self.life_last_update ~= life then
self:stoptweening()
:linear(0.1)
:zoomto(LIFE_FRAME_WIDTH * data.LifeMeter:GetLife(), LIFE_FRAME_HEIGHT)
:diffuse(ThemeColor.White)
:queuecommand(state)
end
self.life_last_update = data.LifeMeter:GetLife()
end,
RegularCommand = function(self)
self:linear(0.2)
:diffuse(ThemeColor.Green)
end,
HotCommand = function(self)
local color = { ThemeColor.Green, ThemeColor.Blue, ThemeColor.Purple }
for i, color in ipairs(color) do
self:linear(0.2)
:diffuse(color)
end
self:queuecommand("Hot")
end,
DangerCommand = function(self)
for i, color in ipairs(ClearLampStates.Failed.flash_colors) do
self:diffuse(color)
:sleep(ClearLampStates.Failed.flash_speed)
end
self:queuecommand("Danger")
end
}
life_frame[#life_frame+1] = Def.Sprite {
Texture = THEME:GetPathG("", "Gameplay/LifeBar.png"),
InitCommand = function(self)
self:zoom(0.50)
:diffuse(PlayerColors[player_number])
:x(player_number == "PlayerNumber_P1" and 9 or -9)
:rotationy(player_number == "PlayerNumber_P1" and 0 or 180)
:shadowcolor(ThemeColor.Black)
:shadowlength(1)
end
}
t[#t+1] = life_frame
end
return t
|
ENT.Type = "anim"
ENT.Base = "cw_attpack_base"
ENT.PrintName = "KHR Pistol Optics"
ENT.PackageText = "KHR Pistol Optics"
ENT.Category = "CW 2.0 Attachments"
ENT.Author = "Spy"
ENT.Spawnable = true
ENT.AdminSpawnable = true
ENT.attachments = {"kry_docter_sight", "md_microt1kh", "md_rmr"}
|
local ConstEnum = require("prototypes.enums.ConstEnum")
-- 聚灵阵 --
ENTITY {
type = "assembling-machine",
name = "灵药园",
icon = ConstEnum.graphics .. "/entity/7x7.png",
icon_size = 288,
max_health = 5000,
flags = { "not-rotatable", "placeable-neutral", "placeable-player", "player-creation" },
minable = { mining_time = 2, result = "灵药园" },
crafting_categories = { "灵药种植" },
crafting_speed = 1,
collision_box = { { -6.25, -6.25 }, { 6.25, 6.25 } },
selection_box = { { -6.5, -6.5 }, { 6.5, 6.5 } },
scale_entity_info_icon = true,
always_draw_idle_animation = true,
fluid_boxes = {
{
base_area = 1,
base_level = 1,
--pipe_covers = pipecoverspictures(),
pipe_connections = {
{ type = "output", position = { 0, 7 } }
},
production_type = "output",
},
},
working_visualisations = { {
animation = {
filename = ConstEnum.graphics .. "/entity/7x7.png",
size = 288,
--shift = util.by_pixel(0, -36),
scale = 0.7,
},
fadeout = true } },
idle_animation = {
layers = {
{
filename = ConstEnum.graphics .. "/entity/7x7.png",
size = 288,
--shift = util.by_pixel(0, -36),
scale = 0.7,
}
}
},
energy_usage = "100W",
energy_source = {
type = "burner",
fuel_category = "灵力",
effectivity = 1,
fuel_inventory_size = 2,
emissions_per_minute = 2,
light_flicker = {
color = { 0, 0, 0 },
minimum_intensity = 0.6,
maximum_intensity = 0.95
},
smoke = {
{
name = "smoke",
deviation = { 0.1, 0.1 },
frequency = 5,
position = { 0.0, -0.8 },
starting_vertical_speed = 0.08,
starting_frame_deviation = 60
}
}
},
result_inventory_size = 0,
source_inventory_size = 0,
se_allow_in_space = true
}
|
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- F I N A L C U T P R O A P I --
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--- === cp.apple.finalcutpro.prefs.PreferencesWindow ===
---
--- Preferences Window Module.
--------------------------------------------------------------------------------
--
-- EXTENSIONS:
--
--------------------------------------------------------------------------------
local log = require("hs.logger").new("PrefsDlg")
local inspect = require("hs.inspect")
local axutils = require("cp.ui.axutils")
local just = require("cp.just")
local prop = require("cp.prop")
local PlaybackPanel = require("cp.apple.finalcutpro.prefs.PlaybackPanel")
local ImportPanel = require("cp.apple.finalcutpro.prefs.ImportPanel")
local id = require("cp.apple.finalcutpro.ids") "PreferencesWindow"
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local PreferencesWindow = {}
function PreferencesWindow.matches(element)
return element:attributeValue("AXSubrole") == "AXDialog"
and not element:attributeValue("AXModal")
and element:attributeValue("AXTitle") ~= ""
and axutils.childWithRole(element, "AXToolbar") ~= nil
and axutils.childWithRole(element, "AXGroup") ~= nil
end
-- TODO: Add documentation
function PreferencesWindow:new(app)
local o = {_app = app}
return prop.extend(o, PreferencesWindow)
end
-- TODO: Add documentation
function PreferencesWindow:app()
return self._app
end
-- TODO: Add documentation
function PreferencesWindow:UI()
return axutils.cache(self, "_ui", function()
local windowsUI = self:app():windowsUI()
return windowsUI and self:_findWindowUI(windowsUI)
end)
end
-- TODO: Add documentation
function PreferencesWindow:_findWindowUI(windows)
return axutils.childMatching(windows, PreferencesWindow.matches)
end
-- TODO: Add documentation
-- Returns the UI for the AXToolbar containing this panel's buttons
function PreferencesWindow:toolbarUI()
return axutils.cache(self, "_toolbar", function()
local ax = self:UI()
return ax and axutils.childWith(ax, "AXRole", "AXToolbar") or nil
end)
end
-- TODO: Add documentation
-- Returns the UI for the AXGroup containing this panel's elements
function PreferencesWindow:groupUI()
return axutils.cache(self, "_group", function()
local ui = self:UI()
local group = ui and axutils.childWithRole(ui, "AXGroup")
-- The group conains another single group that contains the actual checkboxes, etc.
return group and #group == 1 and group[1]
end)
end
-- TODO: Add documentation
function PreferencesWindow:playbackPanel()
if not self._playbackPanel then
self._playbackPanel = PlaybackPanel:new(self)
end
return self._playbackPanel
end
-- TODO: Add documentation
function PreferencesWindow:importPanel()
if not self._importPanel then
self._importPanel = ImportPanel:new(self)
end
return self._importPanel
end
-- TODO: Add documentation
PreferencesWindow.isShowing = prop.new(function(self)
return self:UI() ~= nil
end):bind(PreferencesWindow)
-- TODO: Add documentation
-- Ensures the PreferencesWindow is showing
function PreferencesWindow:show()
if not self:isShowing() then
-- open the window
if self:app():menuBar():isEnabled({"Final Cut Pro", "Preferences…"}) then
self:app():menuBar():selectMenu({"Final Cut Pro", "Preferences…"})
-- wait for it to open.
local ui = just.doUntil(function() return self:UI() end)
end
end
return self
end
-- TODO: Add documentation
function PreferencesWindow:hide()
local ui = self:UI()
if ui then
local closeBtn = axutils.childWith(ui, "AXSubrole", "AXCloseButton")
if closeBtn then
closeBtn:doPress()
-- wait for it to close
just.doWhile(function() return self:isShowing() end, 5)
end
end
return self
end
return PreferencesWindow
|
return {
{
frequency = 0.02,
phase = 90,
},
{
frequency = 0.1,
phase = 270,
},
{
frequency = 0.01,
phase = 180,
},
{
frequency = 0.2,
phase = 270,
},
{
frequency = 1,
phase = 0,
},
{
frequency = 0.05,
phase = 120,
},
{
frequency = 2,
phase = 45,
},
{
frequency = 0.005,
phase = 0,
},
{
frequency = 0.5,
phase = 320,
},
}
|
--
-- Read bjam files, output premake
--
premake.actions.convertbjam = {}
local bjam = premake.actions.convertbjam
function bjam.read(filename)
local jamList = {}
local oldDir = os.getcwd()
if os.isdir(filename) then
error("Expected filename, found directory : "..filename)
end
filename = path.getabsolute(filename)
local shortFilename = path.getrelative(oldDir, filename)
local dir = path.getdirectory(filename)
if filename:contains('/repos') or filename:contains('/super/') or filename:contains('/releases/')
or filename:contains('/onload/') or filename:contains('/lowbanddata-client/')
or filename:contains('/tte') or filename:contains('/tde') or filename:contains('/tce/') or filename:contains('/tae/')
or dir == path.getabsolute(repoRoot)
then
return jamList
end
if not filename:endswith('Jamfile') and not filename:endswith('Jamroot') then
return jamList
end
os.chdir(dir)
local file = io.open(filename, "r")
if not file then
error("Could not open file "..shortFilename)
end
local text = " "..file:read("*a")
local textParts = text:replace('\t',' '):gsub('[ \n]#[^\n]*','')
:replace('\n',' '):replace("\r",""):split(' ', true)
file:close()
local tokens = Seq:new(textParts)
:except('')
:iterate()
local token
local prevTokens = {}
local customRules = {}
local logOutput = {}
local function logTokens(dest)
logOutput = dest
end
customRules['set.intersection'] = {
invoke = function(args)
local set = {}
for _,v in ipairs(args) do
set[v] = v
end
return getKeys(v)
end
}
local function nextToken()
if not tokens then
token = nil
return nil
end
_,token = tokens()
if token then
table.insert( logOutput, token )
end
for i=10,1,-1 do
prevTokens[i+1]=prevTokens[i]
end
prevTokens[1] = token
if not token then
tokens = nil -- prevent wrap-around
end
return token
end
local tokenStack = {}
local function pushTokens(ts)
table.insert(tokenStack, tokens)
tokens = Seq:new(ts):iterate()
nextToken()
end
local function popTokens()
ts = table.remove(tokenStack)
if ts then
tokens = ts
end
end
local function expect(token, expectedToken)
if token ~= expectedToken then
errMsg = "Expected \""..tostring(expectedToken).."\", found \""..tostring(token).."\""
errMsg = errMsg .. '\n in '..shortFilename
errMsg = errMsg .. '\n '..Seq:new(prevTokens):reverse():mkstring(' ')
error(errMsg,2)
end
end
local function expectNext(expectedToken)
expect(nextToken(), expectedToken)
end
local function readList(includeCurrent)
local rv = {}
if not includeCurrent then
nextToken()
end
local symbolList = toSet({ ":", ";", "[", "]", "{", "}", ")" })
while token do
if token == '[' then
-- command
local cmd = nextToken()
local arg1 = readList()
local arg2
if token == ':' then
arg2 = readList()
end
if cmd == 'glob' or cmd == 'glob-tree' then
if cmd == 'glob-tree' then
arg1 = Seq:new(arg1):select(function(v) return v:replace("*","**") end):toTable()
end
local cwd = os.getcwd()
rv.evaluate = function()
if arg1 and arg1.evaluate then arg1 = arg1.evaluate() end
if arg2 and arg2.evaluate then arg2 = arg2.evaluate() end
local oldCwd = os.getcwd()
os.chdir(cwd)
local sources = os.matchfiles(unpack(arg1))
if arg2 then
local excludes = toSet(os.matchfiles(unpack(arg2)))
local filteredSources = {}
for _,v in ipairs(sources) do
if not excludes[v] then
table.insert(filteredSources, v)
end
sources = filteredSources
end
end
os.chdir(oldCwd)
return sources
end
table.insertflat(rv, arg1)
rv.excludes = arg2
elseif cmd == 'MATCH' then
rv.evaluate = function()
if arg1 and arg1.evaluate then arg1 = arg1.evaluate() end
if arg2 and arg2.evaluate then arg2 = arg2.evaluate() end
local rv2 = {}
for _,regexp in ipairs(arg1) do
for _,v in ipairs(arg2) do
local m = string.match(v, regexp)
if m then
table.insert(rv2, m)
end
end
end
return rv2
end
table.insertflat(rv, arg2)
elseif customRules[cmd] then
local args = {}
while token ~= ']' do
local arg = readList()
table.insert(args, arg)
end
customRules[cmd].invoke(args)
else
error("Unknown command "..cmd)
end
expect(token, "]")
nextToken()
elseif (not token) or symbolList[token] then
break
elseif token:startswith("<") then
local key,value = token:match("<([^>]+)>([^:]*)")
--print("with "..tostring(with))
if value:find("<") then
value = value:sub(1,value:find("<")-2)
end
rv[key] = rv[key] or {}
if value then
table.insert(rv[key], value)
end
nextToken()
else
table.insert(rv, token)
nextToken()
end
end
return rv
end
local function readLine()
local line = nil
local rv = {}
popTokens()
nextToken()
while token do
if token == ';' then
break
end
table.insert(rv, token)
nextToken()
end
line = rv
pushTokens(line)
return rv
end
local rules = toSet({ "lib", "exe", "unit-test", "tde-lib", "obj", "provide", "towerscript", })
local skipRules = toSet({ "nfs-install", "release-files", "old-install-to", "install", "release", "list-releases",
"import", "branch", "sh", "gitrepo", "gitrepo.everything", "list-repos", "actions", "shell",
"proto-import", "proto-cpp", "tag-bin", "branch", "do-export", "passthrough-props", "cpp2doxy",
"combo-lib", "list-zip", "generated-file", "generated", "tower-feature", "feature-expand-path", "feature-dep-reqs",
"export-idir", "export-edir", "export-pdir", "export-dreq",
})
local todo = toSet({ "make", "rename", })
function processScope()
local scopeJamList = {}
local maxExportNameLen = 0
while token do
local jam = {}
jam.type = token
local line = { token }
logTokens(line)
local skip = false
if token == 'project' or token == 'repo' then
jam.name = nextToken()
nextToken()
while token == ':' do
nextToken()
if token == 'requirements' then
jam.reqs = readList()
elseif token == 'usage-requirements' then
jam.ureqs = readList()
elseif token == 'build-dir' then
jam.builddir = readList()
elseif token == 'system-libs' then
jam.systemlibs = readList()
elseif token == 'feature' then
jam.feature = jam.feature or {}
local f = {}
f.type = 'feature'
local condition = nextToken()
local key,value = condition:match("<([^>]+)>(.*)")
f.condition = {}
f.condition[key] = value
f.ifTrue = readList()
table.insert( jam.feature, f )
else
if not jam.sources then
jam.sources = readList(true)
end
end
end
if token == 'include-root' then
--ignore
nextToken()
end
expect(token, nil)
elseif rules[token] then
if token == 'provide' then jam.type = nextToken() end
jam.name = nextToken()
if nextToken() == ":" then
jam.sources = readList()
end
if token == ':' then
-- requirements
jam.reqs = readList()
end
if token == ':' then
-- default build flags
jam.defaultBuild = readList()
end
if token == ':' then
-- usage requirements
jam.ureqs = readList()
end
expect(token, nil)
elseif token == 'tde-test' or token == 'unit-tests' then
jam.name = nextToken()
if nextToken() == ":" then
jam.sources = readList()
end
if token == ":" then
jam.ureqs = readList()
end
if token == ":" then
jam.reqs = readList()
end
if token == ":" then
jam.unknown = readList()
end
expect(token, nil)
elseif not token then
-- do nothing
skip = true
elseif todo[token] then
-- TODO
skip = true
elseif skipRules[token] then
skip = true
elseif customRules[token] then
-- to do
skip = true
elseif token == 'explicit' then
jam.explicit = readList()
expect(token, nil)
elseif token == 'export' then
jam.exportType = nextToken()
jam.exportName = nextToken()
maxExportNameLen = math.max( maxExportNameLen, #jam.exportName )
expectNext(":")
jam.sources = readList()
if token == ':' then
-- ignore
readList()
end
if token == ';' then
nextToken()
end
expect(token, nil)
elseif token == 'protos' then
jam.cppVarName = nextToken()
if nextToken() ~= ':' then
jam.headerVarName = token
nextToken()
end
expect(token, ":")
jam.protofiles = readList()
if token == ":" then
jam.reqs = readList()
end
if token == ":" then
jam.builddefaults = readList()
end
if token == ":" then
jam.ureqs = readList()
end
expect(token, nil)
elseif token == 'local' then
jam.varName = nextToken()
if nextToken() == '=' then
jam.varValue = readList()
else
jam.varValue = {}
end
expect(token, nil)
elseif token == 'path-constant' or token == 'constant' then
jam.varName = nextToken()
expectNext(":")
jam.varValue = readList()
expect(token, nil)
elseif token == 'for' then
jam.varName = nextToken()
expectNext('in')
jam.loopList = readList()
expect(token, '{')
nextToken()
jam.loopCode = processScope()
elseif token == '}' then
nextToken()
break
elseif token == 'rule' then
jam.ruleName = nextToken()
nextToken()
if token == '(' then
jam.ruleArgs = {}
while token ~= ')' do
local args = readList()
table.insert(jam.ruleArgs, args)
end
nextToken()
end
jam.invoke = function(args) end -- TODO
customRules[jam.ruleName] = jam
expect(token, '{')
nextToken()
jam.ruleCode = processScope()
elseif token == 'alias' then
jam.varName = nextToken()
expectNext(':')
jam.varValue = readList()
if token then
skip = true
end
elseif token == 'return' then
jam.varValue = readList()
elseif token == 'use-project' then
jam.projectAlias = nextToken()
expectNext(':')
jam.projectFullname = nextToken()
expectNext(nil)
elseif token == 'if' then
-- build simple evaluation tree
function addBranch()
local eval = {}
nextToken()
while token do
if token == '!' then
eval.type = 'not'
eval.lhs = addBranch()
elseif token == '(' then
eval.type = 'brackets'
eval.lhs = addBranch()
return eval
elseif token == ')' or token == '{' then
return eval
elseif token == 'in' then
eval.type = 'in'
eval.rhs = {}
else
-- append token to lhs or rhs lists
if eval.rhs then
table.insert( eval.rhs, token )
else
eval.lhs = eval.lhs or {}
table.insert( eval.lhs, token )
end
end
nextToken()
end
return eval
end
jam.condition = addBranch()
nextToken()
jam.ifTrueCode = processScope()
elseif token == 'build-project' then
jam.prjName = nextToken()
expectNext(nil)
elseif token == 'end' then
expectNext(nil)
else
-- global var?
local origToken = token
jam.type = 'global'
jam.varName = token
nextToken()
if token == '+=' then
jam.varValue = readList()
table.insert( jam.varValue, 0, "$("..jam.varName..")" )
elseif token == '=' then
jam.varValue = readList()
else
expect(origToken, "global variable")
end
expect(token, nil)
end
if skip then
jam.comment = "Not implemented: "..token
token = nil
end
jam.line = table.concat(line, ' ')
table.insert( scopeJamList, jam )
if token == nil then
readLine()
end
end
scopeJamList.maxExportNameLen = maxExportNameLen
return scopeJamList
end -- processScope
readLine()
jamList = processScope()
os.chdir(oldDir)
return jamList
end
|
object_tangible_item_costume_kit_costume_kit = object_tangible_item_costume_kit_shared_costume_kit:new {
}
ObjectTemplates:addTemplate(object_tangible_item_costume_kit_costume_kit, "object/tangible/item/costume_kit/costume_kit.iff")
|
ITEM.name = "MK18"
ITEM.description = "A Close-Quarters weapon, the MK18 is a performance-built M4A1 with a shorter upper reciever and adjustable stock meant to be used by special units who have a need for reliable firepower in close to medium range engagements. Fires 5.56x45 Rounds."
ITEM.model = "models/weapons/ethereal/w_mk18.mdl"
ITEM.class = "cw_kk_ins2_mk18"
ITEM.weaponCategory = "primary"
ITEM.width = 3
ITEM.height = 2
ITEM.price = 60000
ITEM.weight = 6
|
--[[
TheNexusAvenger
Implementation of a command.
--]]
local BaseCommand = require(script.Parent.Parent:WaitForChild("BaseCommand"))
local Command = BaseCommand:Extend()
--[[
Creates the command.
--]]
function Command:__new()
self:InitializeSuper("unadmin","Administrative","Unadmin players.")
self.Arguments = {
{
Type = "nexusAdminPlayers",
Name = "Players",
Description = "Players to unadmin.",
},
}
end
--[[
Runs the command.
--]]
function Command:Run(CommandContext,Players)
self.super:Run(CommandContext)
--Set the admin levels.
local ExecutorAdminLevel = self.API.Authorization:GetAdminLevel(CommandContext.Executor)
for _,Player in pairs(Players) do
if Player ~= CommandContext.Executor then
if self.API.Authorization:GetAdminLevel(Player) < ExecutorAdminLevel then
self.API.Authorization:SetAdminLevel(Player,-1)
else
self:SendError("You can't unadmin players with higher levels than you.")
end
else
self:SendError("You can't unadmin yourself.")
end
end
end
return Command
|
before_each(function()
lor = _G.lor
app = lor({
debug = true
})
Request = _G.request
Response = _G.response
req = Request:new()
res = Response:new()
end)
after_each(function()
lor = nil
app = nil
Request = nil
Response = nil
req = nil
res = nil
end)
describe("group index route: basic usages", function()
it("should be error when giving wrong params", function()
local flag = 0
local test_router = lor:Router()
assert.has_error(function() test_router:get() end, "params should not be nil or empty")
assert.has_error(function() test_router:get({}) end, "params should not be nil or empty")
assert.has_error(function() test_router:get("/test") end, "it must be an function if there's only one param")
assert.has_error(function() test_router:get("/test", "abc") end)
end)
it("uri should mathed", function()
local flag = 0
local test_router = lor:Router()
test_router:get(function(req, res, next)
flag = 1
end)
app:use("/test", test_router())
req.path = "/test"
req.method = "get"
app:handle(req, res)
assert.is.equals(1, flag)
end)
it("uri should not mathed", function()
local flag = 0
local test_router = lor:Router()
test_router:get(function(req, res, next)
flag = 1
end)
app:use("/test", test_router())
app:erroruse(function(err, req, res, next) -- 404 error
assert.is.truthy(err)
assert.is.equals(false, req:is_found())
flag = 999
end)
req.path = "/test/"
req.method = "get"
app:handle(req, res)
assert.is.equals(999, flag)
end)
end)
describe("group index route: multi funcs", function()
it("array params", function()
local flag = 0
local test_router = lor:Router()
local func1 = function(req, res, next)
flag = 1
next()
end
local func2 = function(req, res, next)
flag = 2
next()
end
local last_func = function(req, res, next)
flag = 3
end
test_router:post({func1, func2, last_func})
app:use("/test", test_router())
req.path = "/test"
req.method = "post"
app:handle(req, res)
assert.is.equals(3, flag)
end)
it("unpacked params", function()
local flag = 0
local test_router = lor:Router()
local func1 = function(req, res, next)
flag = 1
next()
end
local func2 = function(req, res, next)
flag = 2
next()
end
local last_func = function(req, res, next)
flag = 3
end
test_router:put(func1, func2, last_func)
app:use("/test", test_router())
req.path = "/test"
req.method = "put"
app:handle(req, res)
assert.is.equals(3, flag)
end)
it("mixed params, case1", function()
local flag = 0
local test_router = lor:Router()
local func1 = function(req, res, next)
flag = 1
next()
end
local func2 = function(req, res, next)
flag = 2
next()
end
local last_func = function(req, res, next)
flag = 3
end
test_router:get({func1, func2}, last_func)
app:use("/test", test_router())
req.path = "/test"
req.method = "get"
app:handle(req, res)
assert.is.equals(3, flag)
end)
it("mixed params, case2", function()
local flag = 0
local test_router = lor:Router()
local func1 = function(req, res, next)
flag = 1
next()
end
local func2 = function(req, res, next)
flag = 2
next()
end
local last_func = function(req, res, next)
flag = 3
end
test_router:put({func1}, func2, {last_func})
app:use("/test", test_router())
req.path = "/test"
req.method = "put"
app:handle(req, res)
assert.is.equals(3, flag)
end)
end)
|
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&type=gym&keyword=climb&key=AIzaSyDGL9WfslaxKb43C2YxWEpwCnZzZNrZ8-c
https://maps.googleapis.com/maps/api/place/details/json?placeid=2a35ed5051c6cfbb3c97adce679b87fb5a5ffabb&key=AIzaSyDGL9WfslaxKb43C2YxWEpwCnZzZNrZ8-c
function handleResponse(event)
print(event.response)
end
params = {
body =
};
network.request("https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyDGL9WfslaxKb43C2YxWEpwCnZzZNrZ8-c", "GET", handleResponse, )
|
ELONA.i18n:add {
mod = {
loaded_script = "Loaded script {$1}. ",
},
}
|
-- Predefined global variables:
-- file_path
-- comment_begin
-- comment_end
-- comment_line_prefix
-- Globals set just before processing each LIMP comment:
-- last_generated_data
-- base_indent
-- nl_style
local table = table
local debug = debug
local string = string
local tostring = tostring
local type = type
local select = select
local ipairs = ipairs
local dofile = dofile
local load = load
local getmetatable = getmetatable
local setmetatable = setmetatable
local fs = fs
local util = util
do -- strict.lua
-- checks uses of undeclared global variables
-- All global variables must be 'declared' through a regular assignment
-- (even assigning nil will do) in a main chunk before being used
-- anywhere or assigned to inside a function.
local mt = getmetatable(_G)
if mt == nil then
mt = {}
setmetatable(_G, mt)
end
__STRICT = true
mt.__declared = {}
mt.__newindex = function (t, n, v)
if __STRICT and not mt.__declared[n] then
local w = debug.getinfo(2, "S").what
if w ~= "main" and w ~= "C" then
error("assign to undeclared variable '"..n.."'", 2)
end
mt.__declared[n] = true
end
rawset(t, n, v)
end
mt.__index = function (t, n)
if __STRICT and not mt.__declared[n] and debug.getinfo(2, "S").what ~= "C" then
error("variable '"..n.."' is not declared", 2)
end
return rawget(t, n)
end
function global(...)
for _, v in ipairs{...} do mt.__declared[v] = true end
end
end
last_generated_data = nil
base_indent = nil
nl_style = nil
indent_size = 3
indent_char = ' '
limprc_path = nil
prefix = nil
postfix = nil
root_dir = nil
backtick = '`'
function trim_trailing_ws (str)
return str:gsub('[ \t]+([\r\n])', '%1'):gsub('[ \t]+$', '')
end
function postprocess (str)
return trim_trailing_ws(str)
end
do -- indent
local current_indent = 0
function get_indent ()
local retval = ''
if base_indent ~= nil and base_indent ~= '' then
retval = base_indent
end
return retval .. string.rep(indent_char, current_indent * indent_size)
end
function write_indent ()
if base_indent ~= nil and base_indent ~= '' then
write(base_indent)
end
local indent = string.rep(indent_char, current_indent * indent_size)
if indent ~= '' then
write(indent)
end
end
function reset_indent ()
current_indent = 0
end
function indent (count)
if count == nil then count = 1 end
current_indent = current_indent + count
end
function unindent (count)
if count == nil then count = 1 end
current_indent = current_indent - count
end
function set_indent (count)
current_indent = count
end
end
function normalize_newlines (str)
local out = {}
local n = 1;
local search_start = 1
local str_len = #str
while true do
local nl_start = str:find('[\r\n]', search_start)
if nl_start then
out[n] = str:sub(search_start, nl_start - 1)
out[n + 1] = nl_style
n = n + 2
if str:byte(nl_start) == '\r' and nl_start < str_len and str:byte(nl_start + 1) == '\n' then
search_start = nl_start + 2
else
search_start = nl_start + 1
end
else
out[n] = str:sub(search_start)
n = n + 1
break
end
end
return table.concat(out);
end
function indent_newlines (str)
return normalize_newlines(str):gsub(nl_style, nl_style .. get_indent())
end
do -- write
local out = nil
local n = 1
local in_comment = false
local function init ()
reset_indent()
out = { }
n = 1
in_comment = false
write_prefix()
end
function nl ()
if out == nil then
init()
end
out[n] = nl_style
n = n + 1
write_indent()
if in_comment then
write(comment_line_prefix)
end
end
local function write_table (table, visited_set)
out[n] = tostring(table)
n = n + 1
local mt = getmetatable(table)
if not (mt and mt.__tostring) and visited_set[table] == nil then
visited_set[table] = true
out[n] = ': '
n = n + 1
indent()
for k,v in pairs(table) do
nl()
local t = type(k)
if t == 'string' then
out[n] = k
n = n + 1
elseif t == 'table' then
write_table(k, visited_set)
else
out[n] = tostring(k)
n = n + 1
end
out[n] = ': '
n = n + 1
t = type(v)
if t == 'string' then
out[n] = v
n = n + 1
elseif t == 'table' then
write_table(v, visited_set)
else
out[n] = tostring(v)
n = n + 1
end
end
unindent()
end
end
local function write_value (val)
if val ~= nil then
local t = type(val)
if t == 'function' then
write(val())
elseif t == 'string' then
out[n] = val
n = n + 1
elseif t == 'table' then
write_table(val, {})
else
out[n] = tostring(val)
n = n + 1
end
end
end
function write (...)
if out == nil then
init()
end
for i = 1, select('#', ...) do
write_value(select(i, ...))
end
end
function writeln (...)
if out == nil then
init()
end
write(...)
nl()
end
function write_lines (...)
if out == nil then
init()
end
for i = 1, select('#', ...) do
write_value(select(i, ...))
nl()
end
end
function begin_comment ()
if out == nil then
init()
end
if false == in_comment then
in_comment = true
write(comment_begin)
end
end
function end_comment ()
if true == in_comment then
in_comment = false
write(comment_end)
end
end
function _finish ()
write_postfix()
local str = table.concat(out)
out = nil
if type(postprocess) == 'function' then
str = postprocess(str)
end
return str
end
end
function quiet()
prefix = ''
postfix = ''
end
function write_prefix ()
if prefix ~= nil then
write(prefix)
else
nl()
begin_comment()
write(' ################# !! GENERATED CODE -- DO NOT MODIFY !! ################# ')
end_comment()
nl()
end
end
function write_postfix ()
reset_indent()
if postfix ~= nil then
write(postfix)
else
nl()
begin_comment()
write(' ######################### END OF GENERATED CODE ######################### ')
end_comment()
end
end
do -- dependencies
local deps = { }
function get_depfile_target ()
return fs.ancestor_relative_path(file_path, root_dir)
end
function write_depfile ()
if not depfile_path or depfile_path == '' then
return
end
local depfile = fs.get_file_contents(depfile_path)
local depfile_exists = true
if nil == depfile then
depfile = ''
depfile_exists = false
end
do
local prefix = get_depfile_target() .. ':'
local depfile_line = { prefix }
for k, v in pairs(deps) do
depfile_line[#depfile_line + 1] = ' '
depfile_line[#depfile_line + 1] = k
end
depfile_line = table.concat(depfile_line)
local found_existing
depfile = depfile:gsub(blt.gsub_escape(prefix) .. '[^\r\n]+', function ()
found_existing = true
return depfile_line
end, 1)
if not found_existing then
depfile = depfile .. depfile_line .. '\n'
end
end
if not depfile_exists then
fs.create_dirs(fs.parent_path(depfile_path))
end
fs.put_file_contents(depfile_path, depfile)
end
function dependency (path)
if path and path ~= '' then
deps[path] = true
end
end
end
function load_file (path, chunk_name)
local contents = fs.get_file_contents(path)
if contents == nil then
error('Path \'' .. path .. '\' does not exist!')
end
if not chunk_name then
chunk_name = '@' .. fs.path_filename(path)
end
dependency(fs.ancestor_relative_path(path, root_dir))
local chunk, err = load(contents, chunk_name)
if not chunk then error(err) end
return chunk
end
function get_file_contents (path)
local contents = fs.get_file_contents(path)
if contents == nil then
error('Path \'' .. path .. '\' does not exist!')
end
dependency(fs.ancestor_relative_path(path, root_dir))
return contents
end
function write_file (path)
local contents = fs.get_file_contents(path)
if contents ~= nil then
dependency(fs.ancestor_relative_path(path, root_dir))
write(indent_newlines(contents))
end
end
-- Passes through the output from from a child process's stdout to the generated code. stderr is not redirected.
function write_proc (command)
local f = io.popen(command, 'r')
write(indent_newlines(f:read('a')))
f:close()
end
function template (source)
local template_parts = {}
local parse_text = function (text)
local search_start = 1
while true do
local nl_start = text:find('[\r\n]', search_start)
if nl_start then
template_parts[#template_parts + 1] = text:sub(search_start, nl_start - 1)
template_parts[#template_parts + 1] = nl
if text:byte(nl_start) == '\r' and nl_start < #text and text:byte(nl_start + 1) == '\n' then
search_start = nl_start + 2
else
search_start = nl_start + 1
end
else
template_parts[#template_parts + 1] = text:sub(search_start)
return
end
end
end
local env = {}
local source_len = #source
local search_start = 1
while true do
local interp_start = source:find('`', search_start, true)
if not interp_start then break end
if interp_start > search_start then
parse_text(source:sub(search_start, interp_start - 1))
end
search_start = interp_start + 1
local interp_end = source:find('`', search_start, true)
if not interp_end then interp_end = source_len + 1 end
if interp_end == search_start then
-- empty interp means write a backtick
template_parts[#template_parts + 1] = '`'
else
local interp = source:sub(search_start, interp_end - 1)
local interp_name = interp
if not interp:find('[\r\n]') then
interp = 'return ' .. interp
end
local interp_fn, err = load(interp, interp_name, 't', env)
if not interp_fn then error(err) end
template_parts[#template_parts + 1] = interp_fn
end
search_start = interp_end + 1
end
if (search_start <= source_len) then
parse_text(source:sub(search_start))
end
local env_mt = {}
env_mt.__newindex = function (table, slot, value)
env_mt.context[slot] = value
end
env_mt.__index = function (table, slot)
if env_mt.context then
local context_value = env_mt.context[slot]
if context_value ~= nil then
return context_value
end
end
return _ENV[slot]
end
setmetatable(env, env_mt)
return function (context, ...)
env_mt.context = context
for i,v in ipairs(template_parts) do
if type(v) == 'function' then
if (v == nl) then
nl()
else
write(v(...))
end
else
write(v)
end
end
end
end
do -- include
local chunks = { }
local include_dirs = { }
function get_include (include_name)
if not include_name then
error 'Must specify include script name!'
end
local existing = chunks[include_name]
if existing ~= nil then
return existing
end
local path = fs.resolve_path(include_name, include_dirs)
if path and fs.stat(fs.canonical_path(path)).kind == 'file' then
dependency(fs.ancestor_relative_path(path, root_dir))
local contents = fs.get_file_contents(path)
local fn, err = load(contents, '@' .. include_name)
if not fn then error(err) end
chunks[include_name] = fn
return fn
end
path = fs.resolve_path(include_name .. '.lua', include_dirs)
if path and fs.stat(fs.canonical_path(path)).kind == 'file' then
dependency(fs.ancestor_relative_path(path, root_dir))
local contents = fs.get_file_contents(path)
local fn, err = load(contents, '@' .. include_name .. '.lua')
if not fn then error(err) end
chunks[include_name] = fn
return fn
end
error('No include found matching \'' .. include_name .. '\'')
end
function register_include_dir (path)
local n = #include_dirs
for i = 1, n do
if include_dirs[i] == path then
return
end
end
include_dirs[n + 1] = fs.absolute_path(path)
end
function resolve_include_path (path)
return fs.resolve_path(path, include_dirs)
end
end
function include (include_name, ...)
return get_include(include_name)(...)
end
function import_limprc (path)
local p = fs.compose_path(path, '.limprc')
if fs.stat(p).kind == 'file' then
limprc_path = p
root_dir = path
dofile(p)
return true
end
local parent = fs.parent_path(path)
if parent == "" then
root_dir = path
return false
end
return import_limprc(parent)
end
import_limprc(fs.parent_path(file_path))
|
data:extend({
{
type = "technology",
name = "steam-locomotives",
icon = "__steamTrains__/graphics/technology/steam-locomotive.png",
icon_size = 128,
prerequisites = {"railway", "fluid-handling"},
effects = {},
unit =
{
ingredients =
{
{"automation-science-pack", 1},
{"logistic-science-pack", 1},
},
time = 30,
count = 100
},
order = "c-g-a-b",
}
})
table.insert(data.raw.technology["steam-locomotives"].effects, {type = "unlock-recipe", recipe = "SteamTrains-locomotive"})
|
return {
tileSize = 16,
Solid = 0,
Floor = 1,
Corridor = 2,
Door = 3,
HHiddenDoor = 4,
VHiddenDoor = 5,
HWall = 6,
VWall = 7,
TLWall = 8,
TRWall = 9,
BLWall = 10,
BRWall = 11,
Dropoff1 = 12,
Dropoff2 = 13,
Dropoff3 = 14,
Dropoff4 = 15,
CorridorWall = 16,
Pepper = 17
}
|
local Adapter = require('arken.ActiveRecord.Adapter')
local QDateTime = require('QDateTime')
local test = {}
test.should_return_with_order = function()
local adapter = Adapter.new()
local where = adapter:where{ order = 'id' }
assert( where == ' ORDER BY id', where )
end
test.should_return_with_limit = function()
local adapter = Adapter.new()
local where = adapter:where{ limit = 100 }
assert( where == ' LIMIT 100', where )
end
test.should_return_with_order_and_limit = function()
local adapter = Adapter.new()
local where = adapter:where{ order = 'id', limit = 100 }
assert( where == ' ORDER BY id LIMIT 100', where )
end
test.should_return_with_join = function()
local adapter = Adapter.new()
local where = adapter:where{ join = { 'LEFT JOIN order ON customer.id = order.customer_id' } }
assert( where == 'LEFT JOIN order ON customer.id = order.customer_id', where )
end
test.should_return_with_join_and_values = function()
local adapter = Adapter.new()
local created_at = '2010/03/01'
local join = {
'LEFT JOIN order ON customer.id = order.customer_id AND created_at > $created_at',
created_at = created_at
}
local where = adapter:where{ join = join }
assert( where == "LEFT JOIN order ON customer.id = order.customer_id AND created_at > '2010/03/01'", where )
end
test.should_return_where_and_values = function()
local adapter = Adapter.new()
local created_at = '2010/03/01'
local where = adapter:where{ where = 'created_at > $created_at', created_at = created_at }
assert( where == " WHERE created_at > '2010/03/01'", where )
end
test.should_return_where_and_boolean = function()
local adapter = Adapter.new()
local canceled = true
local where = adapter:where{ where = 'canceled = $canceled', canceled = canceled }
assert( where == " WHERE canceled = 'true'", where )
end
test.should_return_where_and_number = function()
local adapter = Adapter.new()
local total = 100.35
local where = adapter:where{ where = 'total > $total', total = total }
assert( where == " WHERE total > 100.35", where )
end
test.should_return_where_and_userdata = function()
local adapter = Adapter.new()
local data = QDateTime.currentDateTime()
local where = adapter:where{ where = 'data = $data', data = data }
assert( where == string.format(" WHERE data = '%s'", data), where )
end
test.should_return_where_and_table_with_strings = function()
local adapter = Adapter.new()
local names = {'John', 'Steve', 'Norman'}
local where = adapter:where{ where = 'name IN ($names)', names = names }
assert( where == " WHERE name IN ('John','Steve','Norman')", where )
end
test.should_return_where_and_table_with_numbers = function()
local adapter = Adapter.new()
local values = {11234.34, 950.55, 137.35}
local where = adapter:where{ where = 'values IN ($values)', values = values }
assert( where == " WHERE values IN (11234.34,950.55,137.35)", where )
end
test.should_return_where_and_2_parameters = function()
local adapter = Adapter.new()
local created_at = '2010/03/01'
local customer_id = 1500
local where = adapter:where{ customer_id = customer_id, created_at = created_at }
assert( where == " WHERE created_at = '2010/03/01' AND customer_id = 1500", where )
end
test.should_error_if_values_emptys_and_flag_true = function()
local adapter = Adapter.new()
local created_at = '2010/03/01'
local customer_id = 1500
local status, message = pcall(adapter.where, adapter, {}, true)
assert( status == false )
assert( message[1]:contains("parameters for find empty") == true, message )
end
test.should_return_where_with_boolean_value = function()
local adapter = Adapter.new()
local cancel = true
local where = adapter:where{ cancel = cancel }
assert( where == " WHERE cancel = 'true'", where )
end
test.should_return_where_with_NULL = function()
local adapter = Adapter.new()
local flag = 'NULL'
local where = adapter:where{ flag = flag }
assert( where == " WHERE flag IS NULL", where )
end
test.should_return_where_with_NOT_NULL = function()
local adapter = Adapter.new()
local flag = 'NOT NULL'
local where = adapter:where{ flag = flag }
assert( where == " WHERE flag IS NOT NULL", where )
end
test.should_return_where_with_userdata = function()
local QDateTime = require('QDateTime')
local adapter = Adapter.new()
local date = QDateTime.currentDateTime()
local where = adapter:where{ date = date }
local result = string.format(" WHERE date = '%s'", date:__tostring())
assert( where == result, where )
end
test.should_return_where_with_table = function()
local adapter = Adapter.new()
local values = {12, 29, 33}
local where = adapter:where{ id = values }
local result = ' WHERE id IN (12,29,33)'
assert( where == result, where )
end
return test
|
local tab = {}
tab.name = "TAB_CUSTOMIZATION"
tab.id = 1
tab.text = "CUSTOMIZATION"
tab.switchToKey = "gm_showhelp"
if CLIENT then
function tab:processKey(b, p)
if self:processSlotKeyPress(b, p) then
return true
end
return nil
end
local emptyString = ""
local hud16 = "CW_HUD32"
local hud18 = "CW_HUD38"
local hud20 = "CW_HUD40"
local hud36 = "CW_HUD48"
local hud24 = "CW_HUD48"
local greyGradient = surface.GetTextureID("cw2/gui/greygrad")
local gradient = surface.GetTextureID("cw2/gui/gradient")
function tab:drawFunc()
for k, v in pairs(self.Attachments) do
local meetsReqs = false
-- check whether the current attachment category matches requirements for attaching
meetsReqs = self:isCategoryEligible(v.dependencies, v.exclusions)
if meetsReqs then
self.HUDColors.white.a = 255 * self.CustomizeMenuAlpha
self.HUDColors.black.a = 255 * self.CustomizeMenuAlpha
-- first index of 'offset' table is X, second is Y
local x, y = v.offset[1], v.offset[2]
-- draw header and header gradient
surface.SetDrawColor(0, 0, 0, 255 * self.CustomizeMenuAlpha)
surface.SetTexture(gradient)
surface.DrawTexturedRect(x - 3, y - 20, 200, 55)
local found = emptyString
local name = v.atts[v.last]
local curAtt = CustomizableWeaponry.registeredAttachmentsSKey[name]
if v.last then
if curAtt then
if curAtt.colorType then
found = CustomizableWeaponry.colorableParts.colorText[curAtt.colorType]
else
if curAtt.isGrenadeLauncher then
found = CustomizableWeaponry.grenadeTypes.cycleText
end
end
end
end
draw.ShadowText(v.keyText .. v.header .. found, hud36, x, y + 6, self.HUDColors.white, self.HUDColors.black, 2, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
local curPos = 0
for k2, v2 in ipairs(v.atts) do
if self:isAttachmentEligible(v2) then -- todo: change this part to properly support callbacks and shit
-- do another attachment eligibility check in here, because there might be some callbacks we want to call
-- if the current attachment is the current iteration, draw stuff
local foundAtt = CustomizableWeaponry.registeredAttachmentsSKey[v2]
local baseXPos = x + curPos * 140
if foundAtt then
-- draw short display name along with it's icon
draw.ShadowText(foundAtt.displayNameShort, hud16, baseXPos, y + 180, self.HUDColors.white, self.HUDColors.black, 2, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
surface.SetDrawColor(0, 0, 0, 200 * self.CustomizeMenuAlpha)
surface.DrawOutlinedRect(baseXPos - 3, y + 50 - 3, 120, 120)
surface.DrawOutlinedRect(baseXPos - 2, y + 50 - 2, 118, 118)
-- give the outline a different color if it's the current attachment
if v.last == k2 then
surface.SetDrawColor(200, 255, 200, 255 * self.CustomizeMenuAlpha)
else
if self:canAttachSpecificAttachment(v2, self.Owner, nil, nil, nil, categoryData) then
surface.SetDrawColor(0, 0, 0, 200 * self.CustomizeMenuAlpha)
else
surface.SetDrawColor(255, 175, 175, 150 * self.CustomizeMenuAlpha)
end
end
surface.DrawRect(baseXPos - 1, y + 50 - 1, 116, 116)
surface.SetDrawColor(255, 255, 255, 255 * self.CustomizeMenuAlpha)
surface.SetTexture(foundAtt.displayIcon)
surface.DrawTexturedRect(baseXPos - 1, y + 50 - 1, 116, 116)
-- draw the reticle/beam color icon
if foundAtt.colorType then
local colorEntry = self.SightColors[foundAtt.name]
if colorEntry then
colorEntry = colorEntry.color
if v.last == k2 then
surface.SetDrawColor(0, 0, 0, 255 * self.CustomizeMenuAlpha)
surface.DrawOutlinedRect(baseXPos + 1, y + 50, 38, 38)
surface.SetDrawColor(0, 0, 0, 230 * self.CustomizeMenuAlpha)
surface.DrawRect(baseXPos + 2, y + 51, 36, 36)
end
surface.SetDrawColor(colorEntry.r, colorEntry.g, colorEntry.b, 255 * self.CustomizeMenuAlpha)
surface.SetTexture(foundAtt._reticleIcon)
surface.DrawTexturedRect(baseXPos + 3, y + 51, 35, 35)
end
end
if v.last == k2 then
-- adjust gradient size to description line amount
found = emptyString
if self.SightColors[foundAtt.name] then
found = self.SightColors[foundAtt.name].display
else
if curAtt then
found = CustomizableWeaponry.formAdditionalText(self, curAtt)
end
end
local size = #foundAtt.description
surface.SetDrawColor(0, 0, 0, 200 * self.CustomizeMenuAlpha)
surface.SetTexture(gradient)
surface.DrawTexturedRect(x - 3, y + 200 - 3, 300, size * 30 + 50)
for k3, v3 in ipairs(foundAtt.description) do
draw.ShadowText(v3.t, hud18, x + 5, y + 210 - 3 + k3 * 30 + 17, v3.c, self.HUDColors.black, 2, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
-- draw display name
draw.ShadowText(foundAtt.displayName .. found, hud20, x, y + 218, self.HUDColors.white, self.HUDColors.black, 2, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
curPos = curPos + 1
else
cam.IgnoreZ(false)
cam.End3D2D()
error("CW 2.0 - attempt to display non-existent weapon attachment '" .. v2 .. "' in category index '" .. k .. "' of weapon '" .. self:GetClass() .. "' AKA '" .. self.PrintName .. "'")
end
end
end
end
end
if self.Trivia then
local text = self.Trivia.text
if self.Trivia.textFormatFunc then
text = self.Trivia:textFormatFunc(self)
end
if text then
draw.ShadowText(text, hud36, self.Trivia.x, self.Trivia.y, self.HUDColors.white, self.HUDColors.black, 2, TEXT_ALIGN_LEFT, TEXT_ALIGN_CENTER)
end
end
end
end
CustomizableWeaponry.interactionMenu:addTab(tab)
|
local awful = require('awful')
local beautiful = require('beautiful')
local wibox = require('wibox')
local gears = require('gears')
local mat_icon = require('widget.material.icon')
local dpi = require('beautiful').xresources.apply_dpi
local icons = require('theme.icons')
local TagList = require('widget.tag-list')
local clickable_container = require('widget.material.clickable-container')
return function(screen, panel, action_bar_width)
local menu_icon =
wibox.widget {
icon = icons.menu,
size = dpi(24),
widget = mat_icon
}
local home_button =
wibox.widget {
wibox.widget {
menu_icon,
widget = clickable_container
},
bg = beautiful.background.hue_800 .. '66', -- beautiful.primary.hue_500,
widget = wibox.container.background
}
home_button:buttons(
gears.table.join(
awful.button(
{},
1,
nil,
function()
panel:toggle()
end
)
)
)
-- Create an imagebox widget which will contains an icon indicating which layout we're using.
-- We need one layoutbox per screen.
local LayoutBox = function(s)
local layoutBox = clickable_container(awful.widget.layoutbox(s))
layoutBox:buttons(
awful.util.table.join(
awful.button(
{},
1,
function()
awful.layout.inc(1)
end
),
awful.button(
{},
3,
function()
awful.layout.inc(-1)
end
),
awful.button(
{},
4,
function()
awful.layout.inc(1)
end
),
awful.button(
{},
5,
function()
awful.layout.inc(-1)
end
)
)
)
return layoutBox
end
panel:connect_signal(
'opened',
function()
menu_icon.icon = icons.close
end
)
panel:connect_signal(
'closed',
function()
menu_icon.icon = icons.menu
end
)
local separator = wibox.widget
{
orientation = 'horizontal',
forced_height = dpi(1),
opacity = 0.20,
widget = wibox.widget.separator
}
return wibox.widget {
id = 'action_bar',
layout = wibox.layout.align.vertical,
forced_width = action_bar_width,
{
-- Left widgets
home_button,
-- Create a taglist widget
TagList(screen),
require("widget.xdg-folders"),
layout = wibox.layout.fixed.vertical,
},
-- Middle widget
nil,
{
-- Right widgets
LayoutBox(s),
layout = wibox.layout.fixed.vertical,
}
}
end
|
if script.Parent.className ~= "HopperBin" then
bin = Instance.new("HopperBin")
bin.Name = "build"
bin.Parent = game.Players.acb227.Backpack
script.Parent = bin
end
bin = script.Parent
size = 0
function onButton1Down(mouse)
part = Instance.new("Explosion")
part.Parent = workspace
part.BlastRadius = size
part.Position = mouse.Hit.p
wait()
mouse.Target:remove()
end
bin.Selected:connect(function(mouse)
mouse.Icon = "rbxasset://textures\\GunCursor.png"
mouse.Button1Down:connect(function() onButton1Down(mouse) end)
end)
|
local Action = require(script.Parent.Action)
return Action("StampScaleSet", function(max)
return {
max = max
}
end)
|
--- @module vline
local BASE = (...):match("(.-)[^%.]+$")
local core = require( BASE .. "core" )
local style = require( BASE .. "style" )
local group = {}
-------------------------------------------------------------------------------
-- vertically allign all elements
-------------------------------------------------------------------------------
function group.v_align( elements, align, x )
x = x or style.getCenterX()
if align == "left" then
for _, rect in ipairs( elements ) do
rect.x = x
end
elseif align == "right" then
for _, rect in ipairs( elements ) do
rect.x = x - rect.w
end
elseif align == "center" then
for _, rect in ipairs( elements ) do
rect.x = x - rect.w / 2
end
else
error( "group.v_align invalid align: " .. tostring( align ) )
end
end
-------------------------------------------------------------------------------
-- horizontally allign all elements
-------------------------------------------------------------------------------
function group.h_align( elements, align, y )
y = y or style.getCenterY()
if align == "top" then
for _, rect in ipairs( elements ) do
rect.y = y
end
elseif align == "bottom" then
for _, rect in ipairs( elements ) do
rect.y = y - rect.h
end
elseif align == "center" then
for _, rect in ipairs( elements ) do
rect.y = y - rect.h / 2
end
else
error( "group.h_align invalid align: " .. tostring( align ) )
end
end
-------------------------------------------------------------------------------
-- arrange elements from top to bottom with vertical spacing in between
-------------------------------------------------------------------------------
function group.v_distribute( elements, spacing )
if spacing and elements[ 1 ] then
local y = elements[ 1 ].y
for _, rect in ipairs( elements ) do
rect.y = y
y = y + rect.h + spacing
end
end
end
-------------------------------------------------------------------------------
-- make all elements have same width
-------------------------------------------------------------------------------
function group.stretch_w( elements )
local w = 0
for _, rect in ipairs( elements ) do
w = math.max( w, rect.w )
end
for _, rect in ipairs( elements ) do
rect.w = w
end
end
-------------------------------------------------------------------------------
-- returns the arithmetic center of group
-------------------------------------------------------------------------------
function group.get_center( elements )
local cx = 0
local cy = 0
local n = 0
for _, rect in ipairs( elements ) do
cx = cx + rect.x + rect.w / 2
cy = cy + rect.y + rect.h / 2
n = n + 1
end
if n == 0 then
return style.getCenterX(), style.getCenterY()
else
return math.floor( cx / n ), math.floor( cy / n )
end
end
-------------------------------------------------------------------------------
-- centers whole group on screen; preserves element distances
-------------------------------------------------------------------------------
function group.center_on_screen( elements )
local sx, sy = style.getCenterX(), style.getCenterY()
local dx, dy = group.get_center( elements )
for _, rect in ipairs( elements ) do
local rx = rect.x + rect.w / 2
local ry = rect.y + rect.h / 2
rect.x = math.floor( rect.x + sx - dx )
rect.y = math.floor( rect.y + sy - dy )
end
end
-------------------------------------------------------------------------------
return group
|
WorkingDirectoryBinaries = nil
-- Loads all binaries in working directory
-- Or loads the cached list if it exists
function loadWorkingDirectory()
if WorkingDirectoryBinaries then
return WorkingDirectoryBinaries
else
WorkingDirectoryBinaries = {}
end
local binaries = love.filesystem.getDirectoryItems("framedata")
for i, folderName in ipairs(binaries) do
local path = "framedata/" .. folderName
if love.filesystem.getInfo(path).type == "directory" then
local files = love.filesystem.getDirectoryItems(path)
for j, filename in ipairs(files) do
if filename == "1.png" then
obj = {}
obj.path = path
obj.filename = folderName
-- TODO: This gets repeated in film.lua, extract this out
local lines = love.filesystem.read(path .. "/" .. filename):split("\n")
obj.niceTitle = lines[1]
obj.fps = tonumber(lines[2])
WorkingDirectoryBinaries[#WorkingDirectoryBinaries + 1] = obj
end
end
end
end
return WorkingDirectoryBinaries
end
|
---
-- @type Slot
--
-- DisplayObject that will be bound to bones.
-- import
local json = MOAIJsonParser
local class = require "flower.class"
local table = require "flower.table"
local DisplayObject = require "flower.DisplayObject"
local SpineUtils = require "flower.spine.SpineUtils"
local SpineEvent = require "flower.spine.SpineEvent"
-- class
local Slot = class(DisplayObject)
---
-- The constructor.
-- @param slotData slot parameters table. Fields: (name, bone, color, attachment)
-- @param skeleton skeleton object
function Slot:init(slotData, skeleton)
Slot.__super.init(self)
self._data = slotData
self.skeleton = skeleton
local bone = skeleton.bones[slotData.bone]
assert(bone, "Slot " .. slotData.name .. ": bone " .. slotData.bone .. " not found")
self:setBone(bone)
self:setToBindPose()
end
---
-- Attach slot to a bone
-- @param bone bone object
function Slot:setBone(bone)
self:clearAttrLink(MOAITransform.INHERIT_TRANSFORM)
if bone then
self:setAttrLink(MOAITransform.INHERIT_TRANSFORM, bone, MOAITransform.TRANSFORM_TRAIT)
end
end
---
-- Set attachment for a slot
-- @param attachment attachment object
function Slot:setAttachment(attachment)
if not attachment then
self:setDeck()
self:setIndex()
self:setTexture()
return
end
self:setDeck(attachment:getDeck())
self:setIndex(attachment:getDeckIndex())
self:setTexture(attachment:getTexture())
self:setLoc(attachment:getLoc())
self:setRot(attachment:getRot())
self:setScl(attachment:getScl())
local w, h = self:getSize()
self:setPiv(w / 2, h / 2)
end
---
-- Reset slot data to initial values
function Slot:setToBindPose()
local attachment = self._data.attachment
local color = self._data.color or "ffffffff"
if attachment then
self:setAttachment(self.skeleton:getAttachment(attachment, self._data.name))
end
self:setColor(SpineUtils.hexToRGBA(color))
end
return Slot
|
-- Plugin configuration: julia-vim
-- ============================================================================
-- Substitute LaTeX symbols after typing.
vim.g.latex_to_unicode_auto = true
-- Alignment configuration.
vim.g.julia_indent_align_brackets = 0
vim.g.julia_indent_align_funcargs = 0
vim.g.julia_indent_align_import = 0
|
local lsp_name = "sumneko_lua"
local config = require("lspmanager.utilities").get_config(lsp_name)
local os = require("lspmanager.os")
local cmd_exec = "./extension/server/bin/"
if os.get_os() == os.OSes.Windows then
cmd_exec = cmd_exec .. "Windows/lua-language-server.exe"
else
cmd_exec = cmd_exec .. "Linux/lua-language-server"
end
config.default_config.cmd = { cmd_exec, "-E", "./extension/server/main.lua" }
config.default_config.settings = {
Lua = {
telemetry = {
enable = false,
},
workspace = {
preloadFileSize = 180,
},
},
}
local function install_script()
if os.get_os() == os.OSes.Windows then
return [[
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
function get_latest_version() {
$response = invoke-restmethod -uri "https://api.github.com/repos/sumneko/vscode-lua/releases/latest"
return $response.tag_name
}
$version = get_latest_version
$otherversion = $version.Trim("v")
$url = "https://github.com/sumneko/vscode-lua/releases/download/$($version)/lua-$($otherversion).vsix"
$out = "lua.vsix"
if (Test-Path -Path Get-Location) {
Remove-Item Get-Location -Force -Recurse
}
Invoke-WebRequest -Uri $url -OutFile $out
Invoke-Expression 'tar -xf $($out)'
Out-File -FilePath VERSION -Encoding string -InputObject "$($version)"
Remove-Item $out
]]
end
return [[
if ! command -v jq &> /dev/null
then
exit 123
fi
os=$(uname -s | tr "[:upper:]" "[:lower:]")
version=$(curl -s "https://api.github.com/repos/sumneko/vscode-lua/releases/latest" | jq -r '.tag_name')
case $os in
linux)
platform="Linux"
;;
darwin)
platform="macOS"
;;
esac
curl -L -o "sumneko-lua.vsix" "https://github.com/sumneko/vscode-lua/releases/download/$version/lua-$(echo $version | sed 's/v//').vsix"
rm -rf sumneko-lua
unzip sumneko-lua.vsix -d .
rm sumneko-lua.vsix
chmod +x extension/server/bin/$platform/lua-language-server
echo $version > VERSION
]]
end
return vim.tbl_extend("error", config, {
install_script = install_script,
update_script = function()
return require("lspmanager.installers.manual").update_script("sumneko/vscode-lua")
end,
})
|
local ffi = require "ffi"
local libs = {
OSX = { x86 = "OpenGL.framework/OpenGL", x64 = "OpenGL.framework/OpenGL" },
Windows = { x86 = "OPENGL32.DLL", x64 = "OPENGL32.DLL" },
}
local gl = ffi.load( libs[ ffi.os ][ ffi.arch ] )
require "WTypes"
ffi.cdef[[
typedef unsigned int GLenum;
typedef unsigned char GLboolean;
typedef unsigned int GLbitfield;
typedef signed char GLbyte;
typedef int GLint;
typedef int GLsizei;
typedef unsigned char GLubyte;
typedef char GLchar;
typedef char GLcharARB;
typedef short GLshort;
typedef unsigned short GLushort;
typedef unsigned int GLuint;
typedef int64_t GLint64;
typedef uint64_t GLuint64;
typedef int64_t GLint64EXT;
typedef uint64_t GLuint64EXT;
typedef unsigned short GLhalfNV;
typedef float GLfloat;
typedef float GLclampf;
typedef double GLdouble;
typedef double GLclampd;
typedef void GLvoid;
typedef long GLintptr;
typedef long GLsizeiptr;
typedef void *GLhandleARB;
typedef long GLintptrARB;
typedef long GLsizeiptrARB;
typedef unsigned short GLhalfARB;
typedef unsigned short GLhalf;
]]
require 'gl'
require 'glext'
require 'wglext'
local function getwglfunction(name)
local funcptr = gl.wglGetProcAddress(name);
if funcptr == nil then
return nil
end
return ffi.cast('PFN'..name:upper()..'PROC', funcptr)
end
local M = setmetatable({}, {
__index = function(t, k)
local v = getwglfunction(k) or gl[k]
rawset(t, k, v)
return v
end
})
for i, name in ipairs {
'glGenVertexArray',
'glGenBuffer',
'glGenTexture',
} do
local plural = name..'s'
local naked = M[plural]
M[plural] = function(n, out)
if out then
naked(n, out)
return out, n
else
local array = ffi.new('GLuint[?]', n)
gl[plural](n, array)
return array, n
end
end
M[name] = function()
local array = ffi.new('GLuint[1]')
naked(1, array)
return array[0]
end
end
for i, name in ipairs {
'glDeleteVertexArray',
'glDeleteBuffer',
} do
local plural = name..'s'
local naked = M[plural]
M[name] = function(oneitem)
local array = ffi.new('GLuint[1]')
array[0] = oneitem
M[plural](1, array)
end
end
return M
|
function()
local output = ""
aura_env.h = string.format("%.2f",GetHaste()).."%"
aura_env.v = string.format("%.2f",GetCombatRatingBonus(29)).."%"
aura_env.c = string.format("%.2f",GetCritChance()).."%"
aura_env.m = string.format("%.2f",GetMasteryEffect()).."%"
if (GetHaste() or 0) >= 100 then aura_env.hb = " " elseif (GetHaste() or 0) >= 10 then aura_env.hb = " " else aura_env.hb = " " end
if GetCombatRatingBonus(29) >= 100 then aura_env.vb = " " elseif GetCombatRatingBonus(29) >= 10 then aura_env.vb = " " else aura_env.vb = " " end
if GetCritChance() >= 100 then aura_env.cb = " " elseif GetCritChance() >= 10 then aura_env.cb = " " else aura_env.cb = " " end
if GetMasteryEffect() >= 100 then aura_env.mb = " " elseif GetMasteryEffect() >= 10 then aura_env.mb = " " else aura_env.mb = " " end
local specID = GetSpecializationInfo(GetSpecialization())
local val = 0
local amount = 0
local primary = 0
for k,v in pairs(aura_env.specList) do
if aura_env.specList[specID] ~= nil then
primary = aura_env.specList[specID]
if primary == 1 then
val = "Str: "
amount = UnitStat("player", primary)
elseif primary == 2 then
val = "Agi: "
amount = UnitStat("player", primary)
elseif primary == 4 then
val = "Int: "
amount = UnitStat("player", primary)
else
val = 0
amount = 0
end
end
end
if amount >= 10000 then aura_env.pb = " " elseif amount >= 1000 then aura_env.pb = " " else aura_env.pb = " " end
if primary > 0 then
aura_env.p = val..aura_env.pb..amount.."\
"
else
aura_env.p = "Test: ".."1213".."\
"
end
aura_env.haste = "|cFFFF7D0AHaste:"..aura_env.hb..aura_env.h
aura_env.vers = "|cFFFFF569Vers:"..aura_env.vb..aura_env.v
aura_env.crit = "|cFF40C7EBCrit:"..aura_env.cb..aura_env.c
aura_env.mast = "|cFF00FF96Mast:"..aura_env.mb..aura_env.m
output = aura_env.p..aura_env.crit.."\
"..aura_env.haste.."\
"..aura_env.mast.."\
"..aura_env.vers
return output
end
|
local strict = require 'pl.strict'
local test = require 'pl.test'
local M = strict.module (...)
function M.answer ()
Boo = false -- fine, it's a declared global
-- in strict mode, you cannot assign to globals if you aren't in main
test.assertraise(function()
Foo = true
end," assign to undeclared global 'Foo'")
return 42
end
function M.question ()
return 'what is the answer to Life, the Universe and Everything?'
end
return M
|
require("rrpg.lua");
local __o_rrpgObjs = require("rrpgObjs.lua");
require("rrpgGUI.lua");
require("rrpgDialogs.lua");
require("rrpgLFM.lua");
require("ndb.lua");
function newfrmCombat()
__o_rrpgObjs.beginObjectsLoading();
local obj = gui.fromHandle(_obj_newObject("form"));
local self = obj;
local sheet = nil;
rawset(obj, "_oldSetNodeObjectFunction", rawget(obj, "setNodeObject"));
function obj:setNodeObject(nodeObject)
sheet = nodeObject;
self.sheet = nodeObject;
self:_oldSetNodeObjectFunction(nodeObject);
end;
function obj:setNodeDatabase(nodeObject)
self:setNodeObject(nodeObject);
end;
_gui_assignInitialParentForForm(obj.handle);
obj:beginUpdate();
obj:setName("frmCombat");
obj:setAlign("client");
obj.scrollBox1 = gui.fromHandle(_obj_newObject("scrollBox"));
obj.scrollBox1:setParent(obj);
obj.scrollBox1:setAlign("client");
obj.scrollBox1:setName("scrollBox1");
obj.layout1 = gui.fromHandle(_obj_newObject("layout"));
obj.layout1:setParent(obj.scrollBox1);
obj.layout1:setLeft(0);
obj.layout1:setTop(0);
obj.layout1:setWidth(540);
obj.layout1:setHeight(340);
obj.layout1:setName("layout1");
obj.rectangle1 = gui.fromHandle(_obj_newObject("rectangle"));
obj.rectangle1:setParent(obj.layout1);
obj.rectangle1:setAlign("client");
obj.rectangle1:setColor("black");
obj.rectangle1:setName("rectangle1");
obj.label1 = gui.fromHandle(_obj_newObject("label"));
obj.label1:setParent(obj.layout1);
obj.label1:setLeft(5);
obj.label1:setTop(0);
obj.label1:setWidth(540);
obj.label1:setHeight(20);
obj.label1:setText("RANGED WEAPONS");
obj.label1:setHorzTextAlign("center");
obj.label1:setName("label1");
obj.button1 = gui.fromHandle(_obj_newObject("button"));
obj.button1:setParent(obj.layout1);
obj.button1:setText("+");
obj.button1:setLeft(5);
obj.button1:setTop(0);
obj.button1:setWidth(25);
obj.button1:setHeight(25);
obj.button1:setName("button1");
obj.label2 = gui.fromHandle(_obj_newObject("label"));
obj.label2:setParent(obj.layout1);
obj.label2:setText("WEAPON");
obj.label2:setLeft(5);
obj.label2:setTop(25);
obj.label2:setWidth(150);
obj.label2:setHeight(20);
obj.label2:setHorzTextAlign("center");
obj.label2:setName("label2");
obj.label3 = gui.fromHandle(_obj_newObject("label"));
obj.label3:setParent(obj.layout1);
obj.label3:setText("DMG");
obj.label3:setLeft(155);
obj.label3:setTop(25);
obj.label3:setWidth(40);
obj.label3:setHeight(20);
obj.label3:setHorzTextAlign("center");
obj.label3:setName("label3");
obj.label4 = gui.fromHandle(_obj_newObject("label"));
obj.label4:setParent(obj.layout1);
obj.label4:setText("ACC");
obj.label4:setLeft(195);
obj.label4:setTop(25);
obj.label4:setWidth(40);
obj.label4:setHeight(20);
obj.label4:setHorzTextAlign("center");
obj.label4:setName("label4");
obj.label5 = gui.fromHandle(_obj_newObject("label"));
obj.label5:setParent(obj.layout1);
obj.label5:setText("AP");
obj.label5:setLeft(235);
obj.label5:setTop(25);
obj.label5:setWidth(40);
obj.label5:setHeight(20);
obj.label5:setHorzTextAlign("center");
obj.label5:setName("label5");
obj.label6 = gui.fromHandle(_obj_newObject("label"));
obj.label6:setParent(obj.layout1);
obj.label6:setText("MODE");
obj.label6:setLeft(275);
obj.label6:setTop(25);
obj.label6:setWidth(40);
obj.label6:setHeight(20);
obj.label6:setHorzTextAlign("center");
obj.label6:setName("label6");
obj.label7 = gui.fromHandle(_obj_newObject("label"));
obj.label7:setParent(obj.layout1);
obj.label7:setText("RC");
obj.label7:setLeft(315);
obj.label7:setTop(25);
obj.label7:setWidth(40);
obj.label7:setHeight(20);
obj.label7:setHorzTextAlign("center");
obj.label7:setName("label7");
obj.label8 = gui.fromHandle(_obj_newObject("label"));
obj.label8:setParent(obj.layout1);
obj.label8:setText("AMMO");
obj.label8:setLeft(355);
obj.label8:setTop(25);
obj.label8:setWidth(40);
obj.label8:setHeight(20);
obj.label8:setHorzTextAlign("center");
obj.label8:setFontSize(11);
obj.label8:setName("label8");
obj.label9 = gui.fromHandle(_obj_newObject("label"));
obj.label9:setParent(obj.layout1);
obj.label9:setText("PRICE");
obj.label9:setLeft(395);
obj.label9:setTop(25);
obj.label9:setWidth(40);
obj.label9:setHeight(20);
obj.label9:setHorzTextAlign("center");
obj.label9:setFontSize(12);
obj.label9:setName("label9");
obj.label10 = gui.fromHandle(_obj_newObject("label"));
obj.label10:setParent(obj.layout1);
obj.label10:setText("WEIGHT");
obj.label10:setLeft(435);
obj.label10:setTop(25);
obj.label10:setWidth(40);
obj.label10:setHeight(20);
obj.label10:setHorzTextAlign("center");
obj.label10:setFontSize(11);
obj.label10:setName("label10");
obj.rclRangedWeapons = gui.fromHandle(_obj_newObject("recordList"));
obj.rclRangedWeapons:setParent(obj.layout1);
obj.rclRangedWeapons:setName("rclRangedWeapons");
obj.rclRangedWeapons:setField("rangedWeaponsList");
obj.rclRangedWeapons:setTemplateForm("frmRanged");
obj.rclRangedWeapons:setLeft(5);
obj.rclRangedWeapons:setTop(50);
obj.rclRangedWeapons:setWidth(530);
obj.rclRangedWeapons:setHeight(280);
obj.rclRangedWeapons:setLayout("vertical");
obj.layout2 = gui.fromHandle(_obj_newObject("layout"));
obj.layout2:setParent(obj.scrollBox1);
obj.layout2:setLeft(545);
obj.layout2:setTop(0);
obj.layout2:setWidth(450);
obj.layout2:setHeight(340);
obj.layout2:setName("layout2");
obj.rectangle2 = gui.fromHandle(_obj_newObject("rectangle"));
obj.rectangle2:setParent(obj.layout2);
obj.rectangle2:setAlign("client");
obj.rectangle2:setColor("black");
obj.rectangle2:setName("rectangle2");
obj.label11 = gui.fromHandle(_obj_newObject("label"));
obj.label11:setParent(obj.layout2);
obj.label11:setLeft(5);
obj.label11:setTop(0);
obj.label11:setWidth(450);
obj.label11:setHeight(20);
obj.label11:setText("MELEE WEAPONS");
obj.label11:setHorzTextAlign("center");
obj.label11:setName("label11");
obj.button2 = gui.fromHandle(_obj_newObject("button"));
obj.button2:setParent(obj.layout2);
obj.button2:setText("+");
obj.button2:setLeft(5);
obj.button2:setTop(0);
obj.button2:setWidth(25);
obj.button2:setHeight(25);
obj.button2:setName("button2");
obj.label12 = gui.fromHandle(_obj_newObject("label"));
obj.label12:setParent(obj.layout2);
obj.label12:setText("WEAPON");
obj.label12:setLeft(5);
obj.label12:setTop(25);
obj.label12:setWidth(150);
obj.label12:setHeight(20);
obj.label12:setHorzTextAlign("center");
obj.label12:setName("label12");
obj.label13 = gui.fromHandle(_obj_newObject("label"));
obj.label13:setParent(obj.layout2);
obj.label13:setText("REACH");
obj.label13:setLeft(155);
obj.label13:setTop(25);
obj.label13:setWidth(40);
obj.label13:setHeight(20);
obj.label13:setHorzTextAlign("center");
obj.label13:setFontSize(11);
obj.label13:setName("label13");
obj.label14 = gui.fromHandle(_obj_newObject("label"));
obj.label14:setParent(obj.layout2);
obj.label14:setText("DMG");
obj.label14:setLeft(195);
obj.label14:setTop(25);
obj.label14:setWidth(40);
obj.label14:setHeight(20);
obj.label14:setHorzTextAlign("center");
obj.label14:setName("label14");
obj.label15 = gui.fromHandle(_obj_newObject("label"));
obj.label15:setParent(obj.layout2);
obj.label15:setText("ACC");
obj.label15:setLeft(235);
obj.label15:setTop(25);
obj.label15:setWidth(40);
obj.label15:setHeight(20);
obj.label15:setHorzTextAlign("center");
obj.label15:setName("label15");
obj.label16 = gui.fromHandle(_obj_newObject("label"));
obj.label16:setParent(obj.layout2);
obj.label16:setText("AP");
obj.label16:setLeft(275);
obj.label16:setTop(25);
obj.label16:setWidth(40);
obj.label16:setHeight(20);
obj.label16:setHorzTextAlign("center");
obj.label16:setName("label16");
obj.label17 = gui.fromHandle(_obj_newObject("label"));
obj.label17:setParent(obj.layout2);
obj.label17:setText("PRICE");
obj.label17:setLeft(315);
obj.label17:setTop(25);
obj.label17:setWidth(40);
obj.label17:setHeight(20);
obj.label17:setHorzTextAlign("center");
obj.label17:setFontSize(12);
obj.label17:setName("label17");
obj.label18 = gui.fromHandle(_obj_newObject("label"));
obj.label18:setParent(obj.layout2);
obj.label18:setText("WEIGHT");
obj.label18:setLeft(355);
obj.label18:setTop(25);
obj.label18:setWidth(40);
obj.label18:setHeight(20);
obj.label18:setHorzTextAlign("center");
obj.label18:setFontSize(11);
obj.label18:setName("label18");
obj.rclMeleeWeapons = gui.fromHandle(_obj_newObject("recordList"));
obj.rclMeleeWeapons:setParent(obj.layout2);
obj.rclMeleeWeapons:setName("rclMeleeWeapons");
obj.rclMeleeWeapons:setField("meleeWeaponsList");
obj.rclMeleeWeapons:setTemplateForm("frmMelee");
obj.rclMeleeWeapons:setLeft(5);
obj.rclMeleeWeapons:setTop(50);
obj.rclMeleeWeapons:setWidth(440);
obj.rclMeleeWeapons:setHeight(280);
obj.rclMeleeWeapons:setLayout("vertical");
obj.layout3 = gui.fromHandle(_obj_newObject("layout"));
obj.layout3:setParent(obj.scrollBox1);
obj.layout3:setLeft(0);
obj.layout3:setTop(345);
obj.layout3:setWidth(460);
obj.layout3:setHeight(340);
obj.layout3:setName("layout3");
obj.rectangle3 = gui.fromHandle(_obj_newObject("rectangle"));
obj.rectangle3:setParent(obj.layout3);
obj.rectangle3:setAlign("client");
obj.rectangle3:setColor("black");
obj.rectangle3:setName("rectangle3");
obj.label19 = gui.fromHandle(_obj_newObject("label"));
obj.label19:setParent(obj.layout3);
obj.label19:setLeft(5);
obj.label19:setTop(0);
obj.label19:setWidth(460);
obj.label19:setHeight(20);
obj.label19:setText("AUGMENTATIONS");
obj.label19:setHorzTextAlign("center");
obj.label19:setName("label19");
obj.button3 = gui.fromHandle(_obj_newObject("button"));
obj.button3:setParent(obj.layout3);
obj.button3:setText("+");
obj.button3:setLeft(5);
obj.button3:setTop(0);
obj.button3:setWidth(25);
obj.button3:setHeight(25);
obj.button3:setName("button3");
obj.label20 = gui.fromHandle(_obj_newObject("label"));
obj.label20:setParent(obj.layout3);
obj.label20:setText("AUGMENTATION");
obj.label20:setLeft(5);
obj.label20:setTop(25);
obj.label20:setWidth(150);
obj.label20:setHeight(20);
obj.label20:setHorzTextAlign("center");
obj.label20:setName("label20");
obj.label21 = gui.fromHandle(_obj_newObject("label"));
obj.label21:setParent(obj.layout3);
obj.label21:setText("RATING");
obj.label21:setLeft(155);
obj.label21:setTop(25);
obj.label21:setWidth(50);
obj.label21:setHeight(20);
obj.label21:setHorzTextAlign("center");
obj.label21:setFontSize(11);
obj.label21:setName("label21");
obj.label22 = gui.fromHandle(_obj_newObject("label"));
obj.label22:setParent(obj.layout3);
obj.label22:setText("NOTES");
obj.label22:setLeft(205);
obj.label22:setTop(25);
obj.label22:setWidth(100);
obj.label22:setHeight(20);
obj.label22:setHorzTextAlign("center");
obj.label22:setName("label22");
obj.label23 = gui.fromHandle(_obj_newObject("label"));
obj.label23:setParent(obj.layout3);
obj.label23:setText("ESSENCE");
obj.label23:setLeft(305);
obj.label23:setTop(25);
obj.label23:setWidth(50);
obj.label23:setHeight(20);
obj.label23:setHorzTextAlign("center");
obj.label23:setFontSize(11);
obj.label23:setName("label23");
obj.label24 = gui.fromHandle(_obj_newObject("label"));
obj.label24:setParent(obj.layout3);
obj.label24:setText("PRICE");
obj.label24:setLeft(355);
obj.label24:setTop(25);
obj.label24:setWidth(50);
obj.label24:setHeight(20);
obj.label24:setHorzTextAlign("center");
obj.label24:setFontSize(12);
obj.label24:setName("label24");
obj.rclAugmentations = gui.fromHandle(_obj_newObject("recordList"));
obj.rclAugmentations:setParent(obj.layout3);
obj.rclAugmentations:setName("rclAugmentations");
obj.rclAugmentations:setField("augmentationsList");
obj.rclAugmentations:setTemplateForm("frmAugmentation");
obj.rclAugmentations:setLeft(5);
obj.rclAugmentations:setTop(50);
obj.rclAugmentations:setWidth(450);
obj.rclAugmentations:setHeight(280);
obj.rclAugmentations:setLayout("vertical");
obj.layout4 = gui.fromHandle(_obj_newObject("layout"));
obj.layout4:setParent(obj.scrollBox1);
obj.layout4:setLeft(465);
obj.layout4:setTop(345);
obj.layout4:setWidth(360);
obj.layout4:setHeight(340);
obj.layout4:setName("layout4");
obj.rectangle4 = gui.fromHandle(_obj_newObject("rectangle"));
obj.rectangle4:setParent(obj.layout4);
obj.rectangle4:setAlign("client");
obj.rectangle4:setColor("black");
obj.rectangle4:setName("rectangle4");
obj.label25 = gui.fromHandle(_obj_newObject("label"));
obj.label25:setParent(obj.layout4);
obj.label25:setLeft(5);
obj.label25:setTop(0);
obj.label25:setWidth(360);
obj.label25:setHeight(20);
obj.label25:setText("ARMOR");
obj.label25:setHorzTextAlign("center");
obj.label25:setName("label25");
obj.button4 = gui.fromHandle(_obj_newObject("button"));
obj.button4:setParent(obj.layout4);
obj.button4:setText("+");
obj.button4:setLeft(5);
obj.button4:setTop(0);
obj.button4:setWidth(25);
obj.button4:setHeight(25);
obj.button4:setName("button4");
obj.label26 = gui.fromHandle(_obj_newObject("label"));
obj.label26:setParent(obj.layout4);
obj.label26:setText("ARMOR");
obj.label26:setLeft(5);
obj.label26:setTop(25);
obj.label26:setWidth(100);
obj.label26:setHeight(20);
obj.label26:setHorzTextAlign("center");
obj.label26:setName("label26");
obj.label27 = gui.fromHandle(_obj_newObject("label"));
obj.label27:setParent(obj.layout4);
obj.label27:setText("RATING");
obj.label27:setLeft(105);
obj.label27:setTop(25);
obj.label27:setWidth(40);
obj.label27:setHeight(20);
obj.label27:setHorzTextAlign("center");
obj.label27:setFontSize(11);
obj.label27:setName("label27");
obj.label28 = gui.fromHandle(_obj_newObject("label"));
obj.label28:setParent(obj.layout4);
obj.label28:setText("NOTES");
obj.label28:setLeft(145);
obj.label28:setTop(25);
obj.label28:setWidth(80);
obj.label28:setHeight(20);
obj.label28:setHorzTextAlign("center");
obj.label28:setName("label28");
obj.label29 = gui.fromHandle(_obj_newObject("label"));
obj.label29:setParent(obj.layout4);
obj.label29:setText("PRICE");
obj.label29:setLeft(225);
obj.label29:setTop(25);
obj.label29:setWidth(40);
obj.label29:setHeight(20);
obj.label29:setHorzTextAlign("center");
obj.label29:setFontSize(12);
obj.label29:setName("label29");
obj.label30 = gui.fromHandle(_obj_newObject("label"));
obj.label30:setParent(obj.layout4);
obj.label30:setText("WEIGHT");
obj.label30:setLeft(265);
obj.label30:setTop(25);
obj.label30:setWidth(40);
obj.label30:setHeight(20);
obj.label30:setHorzTextAlign("center");
obj.label30:setFontSize(11);
obj.label30:setName("label30");
obj.rclArmor = gui.fromHandle(_obj_newObject("recordList"));
obj.rclArmor:setParent(obj.layout4);
obj.rclArmor:setName("rclArmor");
obj.rclArmor:setField("armorList");
obj.rclArmor:setTemplateForm("frmArmor");
obj.rclArmor:setLeft(5);
obj.rclArmor:setTop(50);
obj.rclArmor:setWidth(350);
obj.rclArmor:setHeight(280);
obj.rclArmor:setLayout("vertical");
obj._e_event0 = obj.button1:addEventListener("onClick",
function (self)
self.rclRangedWeapons:append();
end, obj);
obj._e_event1 = obj.rclRangedWeapons:addEventListener("onCompare",
function (self, nodeA, nodeB)
return utils.compareStringPtBr(nodeA.ranged_weapon, nodeB.ranged_weapon);
end, obj);
obj._e_event2 = obj.button2:addEventListener("onClick",
function (self)
self.rclMeleeWeapons:append();
end, obj);
obj._e_event3 = obj.rclMeleeWeapons:addEventListener("onCompare",
function (self, nodeA, nodeB)
return utils.compareStringPtBr(nodeA.melee_weapon, nodeB.melee_weapon);
end, obj);
obj._e_event4 = obj.button3:addEventListener("onClick",
function (self)
self.rclAugmentations:append();
end, obj);
obj._e_event5 = obj.rclAugmentations:addEventListener("onCompare",
function (self, nodeA, nodeB)
return utils.compareStringPtBr(nodeA.augmentation_name, nodeB.augmentation_name);
end, obj);
obj._e_event6 = obj.button4:addEventListener("onClick",
function (self)
self.rclArmor:append();
end, obj);
obj._e_event7 = obj.rclArmor:addEventListener("onCompare",
function (self, nodeA, nodeB)
return utils.compareStringPtBr(nodeA.armor_name, nodeB.armor_name);
end, obj);
function obj:_releaseEvents()
__o_rrpgObjs.removeEventListenerById(self._e_event7);
__o_rrpgObjs.removeEventListenerById(self._e_event6);
__o_rrpgObjs.removeEventListenerById(self._e_event5);
__o_rrpgObjs.removeEventListenerById(self._e_event4);
__o_rrpgObjs.removeEventListenerById(self._e_event3);
__o_rrpgObjs.removeEventListenerById(self._e_event2);
__o_rrpgObjs.removeEventListenerById(self._e_event1);
__o_rrpgObjs.removeEventListenerById(self._e_event0);
end;
obj._oldLFMDestroy = obj.destroy;
function obj:destroy()
self:_releaseEvents();
if (self.handle ~= 0) and (self.setNodeDatabase ~= nil) then
self:setNodeDatabase(nil);
end;
if self.button4 ~= nil then self.button4:destroy(); self.button4 = nil; end;
if self.label14 ~= nil then self.label14:destroy(); self.label14 = nil; end;
if self.button1 ~= nil then self.button1:destroy(); self.button1 = nil; end;
if self.button3 ~= nil then self.button3:destroy(); self.button3 = nil; end;
if self.label1 ~= nil then self.label1:destroy(); self.label1 = nil; end;
if self.rclAugmentations ~= nil then self.rclAugmentations:destroy(); self.rclAugmentations = nil; end;
if self.label8 ~= nil then self.label8:destroy(); self.label8 = nil; end;
if self.label11 ~= nil then self.label11:destroy(); self.label11 = nil; end;
if self.layout4 ~= nil then self.layout4:destroy(); self.layout4 = nil; end;
if self.label3 ~= nil then self.label3:destroy(); self.label3 = nil; end;
if self.label4 ~= nil then self.label4:destroy(); self.label4 = nil; end;
if self.label6 ~= nil then self.label6:destroy(); self.label6 = nil; end;
if self.rclRangedWeapons ~= nil then self.rclRangedWeapons:destroy(); self.rclRangedWeapons = nil; end;
if self.label20 ~= nil then self.label20:destroy(); self.label20 = nil; end;
if self.label17 ~= nil then self.label17:destroy(); self.label17 = nil; end;
if self.rclArmor ~= nil then self.rclArmor:destroy(); self.rclArmor = nil; end;
if self.label15 ~= nil then self.label15:destroy(); self.label15 = nil; end;
if self.label25 ~= nil then self.label25:destroy(); self.label25 = nil; end;
if self.label7 ~= nil then self.label7:destroy(); self.label7 = nil; end;
if self.label18 ~= nil then self.label18:destroy(); self.label18 = nil; end;
if self.label2 ~= nil then self.label2:destroy(); self.label2 = nil; end;
if self.label5 ~= nil then self.label5:destroy(); self.label5 = nil; end;
if self.label12 ~= nil then self.label12:destroy(); self.label12 = nil; end;
if self.rclMeleeWeapons ~= nil then self.rclMeleeWeapons:destroy(); self.rclMeleeWeapons = nil; end;
if self.rectangle4 ~= nil then self.rectangle4:destroy(); self.rectangle4 = nil; end;
if self.label26 ~= nil then self.label26:destroy(); self.label26 = nil; end;
if self.label29 ~= nil then self.label29:destroy(); self.label29 = nil; end;
if self.rectangle2 ~= nil then self.rectangle2:destroy(); self.rectangle2 = nil; end;
if self.rectangle3 ~= nil then self.rectangle3:destroy(); self.rectangle3 = nil; end;
if self.label23 ~= nil then self.label23:destroy(); self.label23 = nil; end;
if self.button2 ~= nil then self.button2:destroy(); self.button2 = nil; end;
if self.label21 ~= nil then self.label21:destroy(); self.label21 = nil; end;
if self.label22 ~= nil then self.label22:destroy(); self.label22 = nil; end;
if self.label16 ~= nil then self.label16:destroy(); self.label16 = nil; end;
if self.layout3 ~= nil then self.layout3:destroy(); self.layout3 = nil; end;
if self.label24 ~= nil then self.label24:destroy(); self.label24 = nil; end;
if self.label13 ~= nil then self.label13:destroy(); self.label13 = nil; end;
if self.label9 ~= nil then self.label9:destroy(); self.label9 = nil; end;
if self.label28 ~= nil then self.label28:destroy(); self.label28 = nil; end;
if self.layout1 ~= nil then self.layout1:destroy(); self.layout1 = nil; end;
if self.scrollBox1 ~= nil then self.scrollBox1:destroy(); self.scrollBox1 = nil; end;
if self.rectangle1 ~= nil then self.rectangle1:destroy(); self.rectangle1 = nil; end;
if self.label10 ~= nil then self.label10:destroy(); self.label10 = nil; end;
if self.layout2 ~= nil then self.layout2:destroy(); self.layout2 = nil; end;
if self.label19 ~= nil then self.label19:destroy(); self.label19 = nil; end;
if self.label27 ~= nil then self.label27:destroy(); self.label27 = nil; end;
if self.label30 ~= nil then self.label30:destroy(); self.label30 = nil; end;
self:_oldLFMDestroy();
end;
obj:endUpdate();
__o_rrpgObjs.endObjectsLoading();
return obj;
end;
local _frmCombat = {
newEditor = newfrmCombat,
new = newfrmCombat,
name = "frmCombat",
dataType = "",
formType = "undefined",
formComponentName = "form",
title = "",
description=""};
frmCombat = _frmCombat;
rrpg.registrarForm(_frmCombat);
return _frmCombat;
|
local wm = require("window_manager")
wm.init()
wm.run()
|
local PathOfBloodRelatedStats = {
[ID.Murders] = true,
[ID.Kills] = true,
[ID.SoulsEaten] = true,
[ID.StolenItems] = true,
}
---@param character EclCharacter
---@param stat CustomStatData
---@param tooltip TooltipData
local function OnCustomStatTooltip(character, stat, tooltip)
if PathOfBloodRelatedStats[stat.ID] then
if character:HasTag("LLSTAT_PathOfBloodFailed") then
tooltip:AppendElement({
Type="StatsTalentsMalus",
Label = GameHelpers.GetStringKeyText("LLSTAT_PathOfBloodFailed", "Impure")
})
else
tooltip:AppendElement({
Type="StatsTalentsBoost",
Label = GameHelpers.GetStringKeyText("PURE_DisplayName", "Pure")
})
end
end
end
local stats = {
ID.Murders,
ID.Kills,
ID.SoulsEaten,
ID.StolenItems,
}
local registeredListeners = false
Ext.RegisterListener("SessionLoaded", function()
if Ext.IsModLoaded("1301db3d-1f54-4e98-9be5-5094030916e4") and not registeredListeners then
CustomStatSystem:RegisterStatAddedHandler(stats, function(id, stat, character, stat_mc)
if not character:HasTag("LLSTAT_PathOfBloodFailed") then
stat_mc.label_txt.htmlText = string.format("<font color='#0C3D10'>%s</font>", stat_mc.label_txt.htmlText)
--stat_mc.label_txt.htmlText = string.format("<font color='#7a1221'>%s</font>", stat_mc.label_txt.htmlText)
end
end)
Game.Tooltip.RegisterListener("CustomStat", nil, OnCustomStatTooltip)
registeredListeners = true
end
end)
|
Keys = {
["ESC"] = 322, ["F1"] = 288, ["F2"] = 289, ["F3"] = 170, ["F5"] = 166, ["F6"] = 167, ["F7"] = 168, ["F8"] = 169, ["F9"] = 56, ["F10"] = 57,
["~"] = 243, ["1"] = 157, ["2"] = 158, ["3"] = 160, ["4"] = 164, ["5"] = 165, ["6"] = 159, ["7"] = 161, ["8"] = 162, ["9"] = 163, ["-"] = 84, ["="] = 83, ["BACKSPACE"] = 177,
["TAB"] = 37, ["Q"] = 44, ["W"] = 32, ["E"] = 38, ["R"] = 45, ["T"] = 245, ["Y"] = 246, ["U"] = 303, ["P"] = 199, ["["] = 39, ["]"] = 40, ["ENTER"] = 18,
["CAPS"] = 137, ["A"] = 34, ["S"] = 8, ["D"] = 9, ["F"] = 23, ["G"] = 47, ["H"] = 74, ["K"] = 311, ["L"] = 182,
["LEFTSHIFT"] = 21, ["Z"] = 20, ["X"] = 73, ["C"] = 26, ["V"] = 0, ["B"] = 29, ["N"] = 249, ["M"] = 244, [","] = 82, ["."] = 81,
["LEFTCTRL"] = 36, ["LEFTALT"] = 19, ["SPACE"] = 22, ["RIGHTCTRL"] = 70,
["HOME"] = 213, ["PAGEUP"] = 10, ["PAGEDOWN"] = 11, ["DELETE"] = 178,
["LEFT"] = 174, ["RIGHT"] = 175, ["TOP"] = 27, ["DOWN"] = 173,
}
ESX = nil
local robberyOngoing = false
local MinPolice = 0
Citizen.CreateThread(function ()
while ESX == nil do
TriggerEvent('esx:getSharedObject', function(obj)
ESX = obj
end)
Citizen.Wait(1)
end
if ESX.IsPlayerLoaded() then
ESX.PlayerData = ESX.GetPlayerData()
end
end)
RegisterNetEvent('esx:setJob')
AddEventHandler('esx:setJob', function(job)
ESX.PlayerData.job = job
end)
BankHeists = {
["Fleeca_Bank_Highway"] = {
["Money"] = 150000,
["Bank_Vault"] = {
["model"] = -63539571,
["x"] = -2958.539,
["y"] = 482.2706,
["z"] = 15.835,
["hStart"] = 0.0,
["hEnd"] = -79.5
},
["Start_Robbing"] = {
["x"] = -2956.5705566406,
["y"] = 481.70111083984,
["z"] = 15.697088241577,
["h"] = 357.9729309082
},
["Cash_Pile"] = {
["x"] = -2954.1071777344,
["y"] = 484.38818359375,
["z"] = 16.267852783203,
["h"] = 86.886528015137
}
},
["Fleeca_Bank_Center"] = {
["Money"] = 150000,
["Bank_Vault"] = {
["model"] = 2121050683,
["x"] = 148.025,
["y"] = -1044.364,
["z"] = 29.50693,
["hStart"] = 249.846,
["hEnd"] = -183.599
},
["Start_Robbing"] = {
["x"] = 146.86993408203,
["y"] = -1046.0607910156,
["z"] = 29.368083953857,
["h"] = 218.72334289551
},
["Cash_Pile"] = { ["x"] = 148.67572021484, ["y"] = -1049.197265625, ["z"] = 29.93883895874, ["h"] = 160.95620727539 }
},
["Fleeca_Bank_Top"] = {
["Money"] = 150000,
["Bank_Vault"] = {
["model"] = 2121050683,
["x"] = -352.725,
["y"] = -53.564,
["z"] = 49.50693,
["hStart"] = 249.846,
["hEnd"] = -183.599
},
["Start_Robbing"] = {
["x"] = -353.85614013672,
["y"] = -55.297225952148,
["z"] = 49.036598205566,
["h"] = 222.63375854492
},
["Cash_Pile"] = { ["x"] = -352.00219726563, ["y"] = -58.390628814697, ["z"] = 49.60733795166, ["h"] = 160.58137512207 }
},
}
RegisterNetEvent("esx_bankrobbery:alertCops")
AddEventHandler("esx_bankrobbery:alertCops", function(bankId)
local coords = BankHeists[bankId]["Start_Robbing"]
ESX.ShowNotification("BANK: ALARM!", "", 10000)
blip = AddBlipForCoord(coords["x"], coords["y"], coords["z"])
SetBlipSprite(blip, 161)
SetBlipScale(blip, 1.0)
SetBlipColour(blip, 75)
end)
Citizen.CreateThread(function()
ResetDoors()
while true do
Citizen.Wait(5)
if not robberyOngoing then
for bank, values in pairs(BankHeists) do
local StartPosition = values["Start_Robbing"]
local ped = PlayerPedId()
local pedCoords = GetEntityCoords(ped)
local distanceCheck = GetDistanceBetweenCoords(pedCoords, StartPosition["x"], StartPosition["y"], StartPosition["z"], true)
if distanceCheck <= 5.0 then
ESX.Game.Utils.DrawText3D(StartPosition, "[E] Start Robbery", 0.4)
if distanceCheck <= 1.5 then
if IsControlJustPressed(0, Keys["E"]) then
ESX.TriggerServerCallback("esx_bankrobbery:fetchCops", function(IsEnough)
if IsEnough then
TriggerServerEvent("esx_bankrobbery:startRobbery", bank)
else
ESX.ShowNotification("There is not enough policemen!")
end
end, MinPolice)
end
end
end
end
end
end
end)
RegisterNetEvent("esx_bankrobbery:startRobbery")
AddEventHandler("esx_bankrobbery:startRobbery", function(bankId)
StartRobbery(bankId)
end)
RegisterNetEvent("esx_bankrobbery:endRobbery")
AddEventHandler("esx_bankrobbery:endRobbery", function(bankId)
robberyOngoing = false
end)
RegisterNetEvent("esx_bankrobbery:changeCash")
AddEventHandler("esx_bankrobbery:changeCash", function(bankId, newCash)
if newCash <= 0 then
BankHeists[bankId]["Money"] = 0
end
BankHeists[bankId]["Money"] = newCash
end)
function StartRobbery(bankId)
robberyOngoing = true
local CashPosition = BankHeists[bankId]["Cash_Pile"]
loadModel("bkr_prop_bkr_cashpile_04")
loadAnimDict("anim@heists@ornate_bank@grab_cash_heels")
local CashPile = CreateObject(GetHashKey("bkr_prop_bkr_cashpile_04"), CashPosition["x"], CashPosition["y"], CashPosition["z"], false)
PlaceObjectOnGroundProperly(CashPile)
SetEntityRotation(CashPile, 0, 0, CashPosition["h"], 2)
FreezeEntityPosition(CashPile, true)
SetEntityAsMissionEntity(CashPile, true, true)
Citizen.CreateThread(function()
while robberyOngoing do
Citizen.Wait(5)
local Cash = BankHeists[bankId]["Money"]
local ped = PlayerPedId()
local pedCoords = GetEntityCoords(ped)
local distanceCheck = GetDistanceBetweenCoords(pedCoords, CashPosition["x"], CashPosition["y"], CashPosition["z"], false)
if distanceCheck <= 1.5 then
ESX.Game.Utils.DrawText3D({ x = CashPosition["x"], y = CashPosition["y"], z = CashPosition["z"] }, "[E] Grab " .. Cash, 0.4)
if IsControlJustPressed(0, Keys["E"]) then
if Cash > 0 then
GrabCash(bankId)
else
DeleteEntity(CashPile)
BankHeists[bankId]["Money"] = 0
ESX.ShowNotification("Everything is already recieved!")
TriggerServerEvent("esx_bankrobbery:endRobbery", bankId)
end
end
end
if IsControlJustPressed(0, Keys["X"]) then
DeleteEntity(CashPile)
end
end
end)
end
function GrabCash(bankId)
TaskPlayAnim(PlayerPedId(), "anim@heists@ornate_bank@grab_cash_heels", "grab", 8.0, -8.0, -1, 1, 0, false, false, false)
Citizen.Wait(7500)
ClearPedTasks(PlayerPedId())
local cashRecieved = math.random(5000, 7000)
TriggerServerEvent("esx_bankrobbery:grabbedCash", bankId, BankHeists[bankId]["Money"], cashRecieved)
end
function loadAnimDict(dict)
Citizen.CreateThread(function()
while (not HasAnimDictLoaded(dict)) do
RequestAnimDict(dict)
Citizen.Wait(1)
end
end)
end
function loadModel(model)
Citizen.CreateThread(function()
while not HasModelLoaded(model) do
RequestModel(model)
Citizen.Wait(1)
end
end)
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.