content stringlengths 5 1.05M |
|---|
PLUGIN.name = "Item Spawn Menu"
PLUGIN.author = "Robot"
PLUGIN.description = "Adds an item spawn menu for SuperAdmin usage."
if (CLIENT) then
function PLUGIN:InitializedPlugins(client)
RunConsoleCommand("spawnmenu_reload")
end
end |
local module = {}
local function biter(t, i)
i -= 1
local v = t[i]
if v ~= nil then
return i, v
end
end
local function msiter(t, i)
i += 1
local arr = {}
for j = 1, t.n do
local v = t.args[j][i]
if v == nil then
return
end
arr[j] = v
end
return i, unpack(arr)
end
local function mliter(t, i)
i += 1
local arr = {}
local flag = false
for j = 1, t.n do
local v = t.args[j][i]
if v ~= nil then
flag = true
end
arr[j] = v
end
return flag and i or nil, unpack(arr, 1, t.n)
end
local function viter(t, i)
i += 1
if i <= t.n then
return i, t.args[i]
end
end
local function cnext(t, k)
local k1, v1 = next(t.args[t.i], k)
if k1 ~= nil then
return k1, v1
elseif t.i < t.n then
t.i += 1
return cnext(t, nil)
end
end
function module.vpairs(...) -- varadic pairs, pass a variadic and it will iterate over it while being nil safe, e.g. loops until select('#', ...) instead of until first nil
return viter, {args = {...}, n = select('#', ...)}, 0
end
function module.msipairs(...) -- multi shortest ipairs (stops at first nil)
return msiter, {args = {...}, n = select('#', ...)}, 0
end
function module.mlipairs(...) -- multi longest ipairs (stops when every array is nil)
return mliter, {args = {...}, n = select('#', ...)}, 0
end
function module.cpairs(...) -- chained pairs ()
return cnext, {args = {...}, n = select('#', ...), i = 1}, nil
end
function module.bipairs(t) -- backwards ipairs
return biter, t, #t + 1
end
return module |
local cjson = require("core.utils.json")
local IO = require "core.utils.io"
local _M = {}
local env_ngr_conf_path = os.getenv("NGR_CONF_PATH")
_M.default_ngr_conf_path = env_ngr_conf_path or ngx.config.prefix() .."/conf/ngr.json"
function _M.load(config_path)
config_path = config_path or _M.default_ngr_conf_path
local config_contents = IO.read_file(config_path)
if not config_contents then
ngx.log(ngx.ERR, "No configuration file at: ", config_path)
os.exit(1)
end
local config = cjson.decode(config_contents)
return config, config_path
end
return _M |
--[[
Copyright 2021 Todd Austin
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.
DESCRIPTION
Common UPnP library routines (used across modules)
Several of these routines heavily borrowed from SmartThings example LAN drivers; much credit to Patrick Barrett
--]]
-- Generate discovery message to be sent
local function create_msearch_msg(searchtarget, waitsecs)
return table.concat(
{
'M-SEARCH * HTTP/1.1',
'HOST: 239.255.255.250:1900',
'MAN: "ssdp:discover"',
'MX: ' .. waitsecs,
'ST: ' .. searchtarget,
'CPFN.UPNP.ORG: SmartThingsHub',
'\r\n'
},
"\r\n"
)
end
-- Create table of msg headers from SSDP response
local function process_response(resp, types)
local info = {}
local prefix = string.match(resp, "^([%g ]*)\r\n", 1)
local match = false
for _, resptype in ipairs(types) do
if string.find(prefix, resptype, nil, "plaintext") ~= nil then
match = true
end
end
if match then
local resp2 = string.gsub(resp, "^([%g ]*)\r\n", "")
for k, v in string.gmatch(resp2, "([%g]*):([%g ]*)\r\n") do
v = string.gsub(v, "^ *", "", 1) -- strip off any leading spaces
info[string.lower(k)] = v
end
return info
else
return nil
end
end
-- Update UPnP meta data attributes
local function set_meta_attrs(deviceobj, headers)
local loc = headers["location"]
local ip = loc:match("http://([^,/:]+)")
local port = loc:match(":([^/]+)") or ''
deviceobj.location = loc
deviceobj.ip = ip
deviceobj.port = port
if not deviceobj.description.URLBase then
deviceobj.URLBase = string.match(headers['location'], '^(http://[%d.:]*)')
else
deviceobj.URLBase = deviceobj.description.URLBase
end
deviceobj.bootid = headers["bootid.upnp.org"]
deviceobj.configid = headers["configid.upnp.org"]
end
-- Return service section of device description for a given serviceId
local function find_service(serviceid, section)
if section then
for _, data in ipairs(section) do
for key, value in pairs(data) do
if key == 'serviceId' then
if value == serviceid then
return data
end
end
end
end
end
return nil
end
local function scan_subdevices(serviceid, section)
for _, data in ipairs(section) do
for key, data in pairs(data) do
if key == 'services' then
local result = find_service(serviceid, data)
if result then return result end
elseif key == 'subdevices' then
local result = scan_subdevices(serviceid, data)
if result then return result end
end
end
end
return nil
end
local function scan_for_service(devobj, serviceid)
if devobj.description.device.services then
local result = find_service(serviceid, devobj.description.device.services)
if result then return result end
end
if devobj.description.device.subdevices then
local result = scan_subdevices(serviceid, devobj.description.device.subdevices)
if result then return result end
end
return nil
end
-- credit: Samsung SmartThings/Patrick Barrett
local function tablefind(t, path)
local pathelements = string.gmatch(path, "([^.]+)%.?")
local item = t
for element in pathelements do
if type(item) ~= "table" then
item = nil; break end
item = item[element]
end
return item
end
local function is_array(t)
local i = 0
for _ in pairs(t) do
i = i + 1
if t[i] == nil then return false end
end
return true
end
return {
create_msearch_msg = create_msearch_msg,
process_response = process_response,
set_meta_attrs = set_meta_attrs,
scan_for_service = scan_for_service,
tablefind = tablefind,
is_array = is_array,
}
|
-- Load credentials, 'SSID' and 'PASSWORD' declared and initialised in there
local app = require "application"
require "config"
-- Define WiFi station event callbacks
wifi_connect_event = function(T)
if DEBUG then
print("[d] Connection to AP ("..T.SSID..") established!")
print("[d] Waiting for IP address...")
end
end
wifi_got_ip_event = function(T)
if DEBUG then
print("[d] Wifi connection is ready! IP address is: "..T.IP)
print("[d] Waiting one second before starting program")
tmr.create():alarm(1000, tmr.ALARM_SINGLE, app.run)
return
end
app.run()
end
-- We are rebooting constantly, so run the GC less often
node.egc.setmode(node.egc.ON_ALLOC_FAILURE)
-- Register WiFi Station event callbacks
wifi.eventmon.register(wifi.eventmon.STA_CONNECTED, wifi_connect_event)
wifi.eventmon.register(wifi.eventmon.STA_GOT_IP, wifi_got_ip_event)
if DEBUG then
print("[d] Connecting to WiFi access point...")
end
wifi.setmode(wifi.STATION)
wifi.sta.config({ssid=SSID, pwd=PASSWORD})
if ALWAYS_RESET_AFTER_SECONDS ~= nil then
-- If the program takes too long to run, just restart
tmr.create():alarm(1000*ALWAYS_RESET_AFTER_SECONDS, tmr.ALARM_SINGLE, function()
print(ALWAYS_RESET_AFTER_SECONDS .. " timeout reached, forcing restart")
node.restart()
end)
end
|
SB.Include(Path.Join(SB.DIRS.SRC, 'view/fields/field.lua'))
--- BooleanField module.
--- BooleanField class.
-- @type BooleanField
BooleanField = Field:extends{}
function BooleanField:Update(source)
-- if source ~= self.checkBox then
-- if self.checkBox.checked ~= self.value then
-- self.checkBox:Toggle()
-- end
-- self.checkBox:Invalidate()
-- end
if source ~= self.toggleButton then
self.toggleButton.checked = self.value
self.toggleButton:Invalidate()
end
end
--- BooleanField constructor.
-- @function BooleanField()
-- @see field.Field
-- @tparam table opts Table
-- @tparam string opts.title Title.
-- @usage
-- BooleanField({
-- name = "myBooleanField",
-- value = true,
-- title = "My field",
-- })
function BooleanField:init(field)
self:__SetDefault("width", 200)
self:__SetDefault("value", false)
Field.init(self, field)
-- self.checkBox = Checkbox:New {
-- caption = self.title or "",
-- width = self.width,
-- height = self.height,
-- checked = self.value,
-- tooltip = self.tooltip,
-- OnChange = {
-- function(_, checked)
-- self:Set(checked, self.checkBox)
-- end
-- }
-- }
-- self.components = {
-- self.checkBox,
-- }
self.toggleButton = Button:New {
caption = self.title or "",
width = self.width,
height = self.height,
checked = self.value,
tooltip = self.tooltip,
classname = "toggle_button",
OnClick = {
function()
self:__Toggle()
end
}
}
self.components = {
self.toggleButton,
}
end
function BooleanField:__Toggle()
self.toggleButton.checked = not self.toggleButton.checked
self.toggleButton:Invalidate()
self:Set(self.toggleButton.checked, self.toggleButton)
end
|
require('telescope').setup{
defaults = {
mappings = {
i = {
["<C-k>"] = require('telescope.actions').move_selection_previous,
["<C-j>"] = require('telescope.actions').move_selection_next,
["<esc>"] = require('telescope.actions').close,
}
}
},
pickers = {},
extensions = {
project = { hidden_files = true }
}
}
|
object_ship_firespray_tier7 = object_ship_shared_firespray_tier7:new {
}
ObjectTemplates:addTemplate(object_ship_firespray_tier7, "object/ship/firespray_tier7.iff")
|
-- not really required, but makes it obvious it is loaded
-- so we can copy ngx object and compare it later to check modifications
require('resty.core')
-- so test can't exit and can verify the return status easily
ngx.exit = function(...) return ... end
local busted = require('busted')
local misc = require('resty.core.misc')
local tablex = require('pl.tablex')
local inspect = require('inspect')
local spy = require('luassert.spy')
local deepcopy = tablex.deepcopy
local copy = tablex.copy
local pairs = pairs
local ngx_original = copy(ngx)
local ngx_var_original = deepcopy(ngx.var)
local ngx_ctx_original = deepcopy(ngx.ctx)
local ngx_shared_original = deepcopy(ngx.shared)
local ngx_header_original = deepcopy(ngx.header)
local register_getter = misc.register_ngx_magic_key_getter
local register_setter = misc.register_ngx_magic_key_setter
local function getlocal(fn, var)
local i = 1
while true do
local name, val = debug.getupvalue(fn, i)
if name == var then
return val
elseif not name then
break
end
i = i + 1
end
end
local get_status = getlocal(register_getter, 'ngx_magic_key_getters').status
local set_status = getlocal(register_setter, 'ngx_magic_key_setters').status
local get_headers_sent = getlocal(register_getter, 'ngx_magic_key_getters').headers_sent
local set_headers_sent = getlocal(register_setter, 'ngx_magic_key_setters').headers_sent
local function reset_ngx_shared(state)
local shared = ngx.shared
for name, dict in pairs(state) do
shared[name] = dict
end
for name, _ in pairs(shared) do
shared[name] = state[name]
end
end
--- ngx keys that are going to be reset in between tests.
local ngx_reset = {
var = ngx_var_original,
ctx = ngx_ctx_original,
header = ngx_header_original,
}
local function reset_ngx_state()
for key, val in pairs(ngx_reset) do
ngx[key] = deepcopy(val)
end
-- We can't replace the whole table, as some code like resty.limit.req takes reference to it when loading.
reset_ngx_shared(ngx_shared_original)
end
local function cleanup()
register_getter('status', get_status)
register_setter('status', set_status)
register_getter('headers_sent', get_headers_sent)
register_setter('headers_sent', set_headers_sent)
reset_ngx_state()
end
local function setup()
-- Register getters and setters for ngx vars used in the tests.
local status, headers_sent
register_setter('status', function(newstatus)
status = newstatus
end)
register_getter('status', function() return status end)
register_setter('headers_sent', function(new_headers_sent)
headers_sent = new_headers_sent
end)
register_getter('headers_sent', function() return headers_sent end)
end
--- Verify ngx global variable against unintentional changes.
--- Some specs could be for example setting `ngx.req = { }` and leak
--- to other tests.
busted.subscribe({ 'it', 'end' }, function ()
for key, value in pairs(ngx_original) do
if ngx[key] ~= value and not ngx_reset[key] and not spy.is_spy(ngx[key]) then
ngx[key] = value
busted.fail('ngx.' .. key .. ' changed from ' .. inspect(value) .. ' to ' .. inspect(ngx[key]))
end
end
return nil, true -- continue executing callbacks
end)
busted.after_each(cleanup)
busted.teardown(cleanup)
busted.before_each(setup)
|
local SETTINGS_CONFIG = {
MeshSettings = {
forceLod = 0,
globalLodScale = 1000,
shadowDistanceScale = 1000
},
WorldRenderSettings = {
shadowmapResolution = 4096,
shadowmapViewDistance = 500,
shadowmapQuality = 0
},
VegetationSystemSettings = {
maxActiveDistance = 4000,
shadowMeshEnable = true
}
}
g_Prints = false
return SETTINGS_CONFIG
|
local key = love.keyboard
local can_play = false
sound_bounce = love.audio.newSource('bounce.wav')
sound_loss = love.audio.newSource('loss.wav')
-- Load some default values for our rectangle.
function love.load()
big_font = love.graphics.newFont(32)
score_pos = 10
score_linePos = 30+32
score_height = 1
max_pos = score_linePos + score_height
p1 = {}
p1 = spawnPlayer(p1, 0, max_pos)
width = 10
height = 100
speed = 10
getHeight = love.graphics.getHeight( ) - height
getWidth = love.graphics.getWidth( ) - width
screenHeight = love.graphics.getHeight()
screenWidth = love.graphics.getWidth()
p2 = {}
p2 = spawnPlayer(p2, getWidth, max_pos)
spawnBall()
end
function spawnPlayer(self, x, y)
self.score = 0
self.x = x or 0
self.y = y or 0
return self
end
function spawnBall()
ball={
math.random(getWidth/2 - getWidth/3, getWidth/2 + getWidth/3),
math.random(max_pos, getHeight-5)
}
ball.w = 10
ball.h = 10
ball.speed=math.random(3,5)
ball.ascension=math.random(-8,8)
ball.direction = math.random(1,2)
end
-- Draw a coloured rectangle.
function love.draw()
love.graphics.setColor(255,255,255)
if can_play == false then
love.graphics.setFont(big_font)
love.graphics.printf("Press space to play", 0, screenHeight/2, screenWidth, "center")
end
-- draw line division
love.graphics.rectangle("fill", 0, score_linePos, screenWidth, score_height)
-- draw players
-- love.graphics.setColor(0,255,0) -- color green
love.graphics.rectangle("fill", p1.x, p1.y, width, height) -- player 1
love.graphics.rectangle("fill", p2.x, p2.y, width, height) -- player 2
-- draw ball
if can_play == true then
love.graphics.setColor(255,255,255)
else
love.graphics.setColor(255,255,51)
end
love.graphics.rectangle("fill", ball[1], ball[2], ball.w, ball.h)
-- draw score
love.graphics.setColor(255,0,0,255)
-- love.graphics.setFont(big_font)
love.graphics.printf(p1.score .. " | ".. p2.score, 0, score_pos, screenWidth, "center")
end
-- Increase the size of the rectangle every frame.
function love.update(dt)
-- we will use awsd for player 1 and arrows for player 2
if key.isDown("space") and can_play == false then
can_play = true
end
-- keyboard
-- player 1 controls
if key.isDown("w") then
p1.y = p1.y - 1 * speed
if p1.y < max_pos then p1.y = max_pos end
elseif key.isDown("s") then
p1.y = p1.y + 1 + speed
if p1.y > getHeight then p1.y = getHeight end
end
-- player 2 controls
if key.isDown("up") then
p2.y = p2.y - 1 * speed
if p2.y < max_pos then p2.y = max_pos end
elseif key.isDown("down") then
p2.y = p2.y + 1 + speed
if p2.y > getHeight then p2.y = getHeight end
end
--joystick
if can_play == true then
-- ball movement right
if ball.direction == 1 then
ball[1]=ball[1]-ball.speed
else
ball[1]=ball[1]+ball.speed
end
ball[2]=ball[2]+ball.ascension
end
-- Collision detection
if ball[1] >= screenWidth-20 and ball[2] >= p2.y and ball[2] <= p2.y+45 then
ball.direction=1
ball.speed=ball.speed+1
ball.ascension=math.random(-2,2)
-- play bounce sound
love.audio.play(sound_bounce)
elseif ball[1] >= screenWidth-20 and ball[2] >= p2.y+45 and ball[2] <= p2.y+90 then
ball.direction=1
ball.speed=ball.speed+1
ball.ascension=math.random(-2,2)
-- play bounce sound
love.audio.play(sound_bounce)
elseif ball[1] <= 20 and ball[2] >= p1.y+45 and ball[2] <= p1.y+90 then
ball.direction=2
ball.speed=ball.speed+1
-- play bounce sound
love.audio.play(sound_bounce)
elseif ball[1] <= 20 and ball[2] >= p1.y and ball[2] <= p1.y+45 then
ball.direction=2
ball.speed=ball.speed+1
-- play bounce sound
love.audio.play(sound_bounce)
elseif ball[2] > screenHeight-(ball.h/2) then -- we need collision for borders too
ball.ascension=ball.ascension*-1
ball.speed=ball.speed+1
-- play bounce sound
love.audio.play(sound_bounce)
elseif ball[2] < max_pos then -- we need collision for borders too
ball.ascension=ball.ascension*-1
ball.speed=ball.speed+1
-- play bounce sound
love.audio.play(sound_bounce)
end
if ball.speed > 10 then
ball.speed = 10
end
-- score points
if ball[1] > screenWidth+(ball.w/2) then
p1.score = p1.score + 1
-- play loss sound
love.audio.play(sound_loss)
can_play = false
spawnBall ()
elseif ball[1] < -(ball.w/2) then
p2.score = p2.score + 1
-- play loss sound
love.audio.play(sound_loss)
can_play = false
spawnBall ()
end
end
|
local present, packer = pcall(require, "plugins.packerInit")
if not present then
return false
end
local get_plugins_list = function()
local list = {}
local tmp = vim.split(vim.fn.globpath(__editor_global.modules_dir, "*/plugins.lua"), "\n")
for _, f in ipairs(tmp) do
list[#list + 1] = f:sub(#__editor_global.modules_dir - 6, -1)
end
return list
end
local get_plugins_mapping = function()
local plugins = {}
local plugins_ = get_plugins_list()
for _, m in ipairs(plugins_) do
local repos = require(m:sub(0, #m - 4))
for repo, conf in pairs(repos) do
plugins[#plugins + 1] = vim.tbl_extend("force", { repo }, conf)
end
end
return plugins
end
local required_plugins = function(use)
use({ "RishabhRD/popfix" })
use({ "nvim-lua/plenary.nvim" })
use({ "lewis6991/impatient.nvim" })
use({
"nathom/filetype.nvim",
config = function()
require("filetype").setup({})
end,
})
use({ "wbthomason/packer.nvim", opt = true })
use({
"kyazdani42/nvim-web-devicons",
config = function()
local colors = require("core.colors").get().base_30
require("nvim-web-devicons").setup({
-- your personnal icons can go here (to override)
-- you can specify color or cterm_color instead of specifying both of them
-- DevIcon will be appended to `name`
override = {
zsh = {
icon = "",
color = "#428850",
cterm_color = "65",
name = "Zsh",
},
c = {
icon = "",
color = colors.blue,
name = "c",
},
css = {
icon = "",
color = colors.blue,
name = "css",
},
deb = {
icon = "",
color = colors.cyan,
name = "deb",
},
Dockerfile = {
icon = "",
color = colors.cyan,
name = "Dockerfile",
},
html = {
icon = "",
color = colors.baby_pink,
name = "html",
},
jpeg = {
icon = "",
color = colors.dark_purple,
name = "jpeg",
},
jpg = {
icon = "",
color = colors.dark_purple,
name = "jpg",
},
js = {
icon = "",
color = colors.sun,
name = "js",
},
kt = {
icon = "",
color = colors.orange,
name = "kt",
},
lock = {
icon = "",
color = colors.red,
name = "lock",
},
lua = {
icon = "",
color = colors.blue,
name = "lua",
},
mp3 = {
icon = "",
color = colors.white,
name = "mp3",
},
mp4 = {
icon = "",
color = colors.white,
name = "mp4",
},
out = {
icon = "",
color = colors.white,
name = "out",
},
png = {
icon = "",
color = colors.dark_purple,
name = "png",
},
py = {
icon = "",
color = colors.cyan,
name = "py",
},
["robots.txt"] = {
icon = "ﮧ",
color = colors.red,
name = "robots",
},
toml = {
icon = "",
color = colors.blue,
name = "toml",
},
ts = {
icon = "ﯤ",
color = colors.teal,
name = "ts",
},
ttf = {
icon = "",
color = colors.white,
name = "TrueTypeFont",
},
rb = {
icon = "",
color = colors.pink,
name = "rb",
},
rpm = {
icon = "",
color = colors.orange,
name = "rpm",
},
vue = {
icon = "﵂",
color = colors.vibrant_green,
name = "vue",
},
woff = {
icon = "",
color = colors.white,
name = "WebOpenFontFormat",
},
woff2 = {
icon = "",
color = colors.white,
name = "WebOpenFontFormat2",
},
xz = {
icon = "",
color = colors.sun,
name = "xz",
},
zip = {
icon = "",
color = colors.sun,
name = "zip",
},
},
-- globally enable default icons (default to false)
-- will get overriden by `get_icons` option
default = true,
})
end,
})
-- colorscheme
use({
"rose-pine/neovim",
as = "rose-pine",
config = function()
require("rose-pine").setup({
---@usage 'main'|'moon'
dark_variant = __editor_config.schemeopt.rosepine.variant,
bold_vert_split = false,
dim_nc_background = false,
disable_background = false,
disable_float_background = false,
disable_italics = false,
---@usage string hex value or named color from rosepinetheme.com/palette
groups = {
background = "base",
panel = "surface",
border = "highlight_med",
comment = "muted",
link = "iris",
punctuation = "subtle",
error = "love",
hint = "iris",
info = "foam",
warn = "gold",
headings = {
h1 = "iris",
h2 = "foam",
h3 = "rose",
h4 = "gold",
h5 = "pine",
h6 = "foam",
},
-- or set all headings at once
-- headings = 'subtle'
},
-- Change specific vim highlight groups
highlight_groups = {
ColorColumn = { bg = "rose" },
},
})
end,
})
use({
"catppuccin/nvim",
as = "catppuccin",
config = function()
require("catppuccin").setup({
transparent_background = true,
term_colors = true,
styles = {
comments = "italic",
conditionals = "italic",
loops = "italic",
functions = "italic",
},
integrations = {
treesitter = true,
native_lsp = {
enabled = true,
virtual_text = {
errors = "italic",
hints = "italic",
warnings = "italic",
information = "italic",
},
underlines = {
errors = "underline",
hints = "underline",
warnings = "underline",
information = "underline",
},
},
lsp_trouble = true,
cmp = true,
lsp_saga = true,
gitgutter = true,
gitsigns = true,
telescope = true,
nvimtree = {
enabled = true,
show_root = true,
transparent_panel = true,
},
which_key = true,
indent_blankline = {
enabled = true,
colored_indent_levels = true,
},
dashboard = false,
neogit = false,
vim_sneak = false,
fern = false,
barbar = false,
bufferline = true,
markdown = true,
lightspeed = false,
ts_rainbow = true,
hop = false,
notify = true,
telekasten = true,
symbols_outline = true,
},
})
vim.g.catppuccin_flavour = __editor_config.schemeopt.catppuccin.flavour
end,
})
use({ "stevearc/dressing.nvim", after = "nvim-web-devicons" })
-- tpope
use({ "tpope/vim-repeat" })
use({ "tpope/vim-sleuth" })
use({ "tpope/vim-surround" })
use({ "tpope/vim-commentary" })
end
return packer.startup(function(use)
required_plugins(use)
for _, repo in ipairs(get_plugins_mapping()) do
use(repo)
end
end)
|
fysiks.ContactConstraint = fysiks.Constraint:new()
fysiks.ContactConstraint.__index = fysiks.ContactConstraint
function fysiks.ContactConstraint:new(jacobian, bias, a, b, con)
local c = setmetatable(fysiks.Constraint:new(jacobian, bias, a, b), self)
c.clampTop = false
c.clampTopVal = 0
c.clampBottom = true
c.clampBottomVal = 0
c.contact = con
return c
end
function fysiks.ContactConstraint:clampLagMult()
fysiks.Constraint.clampLagMult(self)
self.contact:setTangentClamp(self.lagMultSum:get(1, 1))
end
|
registerGlobalSignals ( {
"ui.viewmapping.change"
} )
|
-- invalid code
-- rename(old="temp.lua", new="temp1.lua")
--valid
--rename{old="temp.lua", new="temp1.lua"}
function rename (arg)
return os.rename(arg.old, arg.new)
end
|
--[[
This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:25' using the latest game version.
NOTE: This file should only be used as IDE support; it should NOT be distributed with addons!
****************************************************************************
CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC.
****************************************************************************
]]
local DATA_TYPE_ITEM = 1
local LIST_ENTRY_HEIGHT = 52
-----------------------------
-- Companion Equipment
-----------------------------
ZO_CompanionEquipment_Keyboard = ZO_InitializingObject:Subclass()
function ZO_CompanionEquipment_Keyboard:Initialize(control)
self.control = control
self.playerGoldLabel = control:GetNamedChild("InfoBarMoney")
self.freeSlotsLabel = control:GetNamedChild("InfoBarFreeSlots")
self.list = control:GetNamedChild("List")
self.emptyLabel = control:GetNamedChild("Empty")
self.sortHeadersControl = control:GetNamedChild("SortBy")
self.sortHeaders = ZO_SortHeaderGroup:New(self.sortHeadersControl, true)
self.tabs = control:GetNamedChild("Tabs")
self.subTabs = control:GetNamedChild("SearchFiltersSubTabs")
self.activeTabLabel = self.tabs:GetNamedChild("Active")
self:SetupCategoryFlashAnimation()
-- gold display
local function OnGoldUpdated(eventId, newAmount, oldAmount, reason)
self:SetPlayerGoldAmount(newAmount)
end
control:RegisterForEvent(EVENT_MONEY_UPDATE, OnGoldUpdated)
self:SetPlayerGoldAmount(GetCurrencyAmount(CURT_MONEY, CURRENCY_LOCATION_CHARACTER))
-- inventory list
local DEFAULT_HIDE_CALLBACK = nil
local DEFAULT_SELECT_SOUND = nil
ZO_ScrollList_AddDataType(self.list, DATA_TYPE_ITEM, "ZO_PlayerInventorySlot", LIST_ENTRY_HEIGHT, function(rowControl, data) self:SetupItemRow(rowControl, data) end, DEFAULT_HIDE_CALLBACK, DEFAULT_SELECT_SOUND, ZO_InventorySlot_OnPoolReset)
-- tabs
local FILTER_KEYS =
{
ITEM_TYPE_DISPLAY_CATEGORY_JEWELRY, ITEM_TYPE_DISPLAY_CATEGORY_ARMOR, ITEM_TYPE_DISPLAY_CATEGORY_WEAPONS, ITEM_TYPE_DISPLAY_CATEGORY_ALL,
}
self.filters = {}
for _, key in ipairs(FILTER_KEYS) do
local filterData = ZO_ItemFilterUtils.GetItemTypeDisplayCategoryFilterDisplayInfo(key)
local filter = self:CreateNewTabFilterData(filterData.filterType, filterData.filterString, filterData.icons.up, filterData.icons.down, filterData.icons.over)
filter.control = ZO_MenuBar_AddButton(self.tabs, filter)
table.insert(self.filters, filter)
end
local IS_SUB_FILTER = true
local function GetSearchFilters(searchFilterKeys)
local searchFilters = {}
for filterId, subFilters in pairs(searchFilterKeys) do
searchFilters[filterId] = {}
local searchFilterAtId = searchFilters[filterId]
for _, subfilterKey in ipairs(subFilters) do
local filterData = ZO_ItemFilterUtils.GetSearchFilterData(filterId, subfilterKey)
local filter = self:CreateNewTabFilterData(filterData.filterType, filterData.filterString, filterData.icons.up, filterData.icons.down, filterData.icons.over, IS_SUB_FILTER)
table.insert(searchFilterAtId, filter)
end
end
return searchFilters
end
local SEARCH_FILTER_KEYS =
{
[ITEM_TYPE_DISPLAY_CATEGORY_ALL] =
{
ITEM_TYPE_DISPLAY_CATEGORY_ALL,
},
[ITEM_TYPE_DISPLAY_CATEGORY_WEAPONS] =
{
EQUIPMENT_FILTER_TYPE_RESTO_STAFF, EQUIPMENT_FILTER_TYPE_DESTRO_STAFF, EQUIPMENT_FILTER_TYPE_BOW,
EQUIPMENT_FILTER_TYPE_TWO_HANDED, EQUIPMENT_FILTER_TYPE_ONE_HANDED, EQUIPMENT_FILTER_TYPE_NONE,
},
[ITEM_TYPE_DISPLAY_CATEGORY_ARMOR] =
{
EQUIPMENT_FILTER_TYPE_SHIELD, EQUIPMENT_FILTER_TYPE_HEAVY, EQUIPMENT_FILTER_TYPE_MEDIUM,
EQUIPMENT_FILTER_TYPE_LIGHT, EQUIPMENT_FILTER_TYPE_NONE,
},
[ITEM_TYPE_DISPLAY_CATEGORY_JEWELRY] =
{
EQUIPMENT_FILTER_TYPE_RING, EQUIPMENT_FILTER_TYPE_NECK, EQUIPMENT_FILTER_TYPE_NONE,
},
}
self.subFilters = GetSearchFilters(SEARCH_FILTER_KEYS, INVENTORY_BACKPACK)
-- sort headers
local sortKeys = ZO_Inventory_GetDefaultHeaderSortKeys()
self.sortFunction = function(entry1, entry2)
local sortKey = self.currentFilter.sortKey
local sortOrder = self.currentFilter.sortOrder
return ZO_TableOrderingFunction(entry1.data, entry2.data, sortKey, sortKeys, sortOrder)
end
local function OnSortHeaderClicked(key, order)
self.currentFilter.sortKey = key
self.currentFilter.sortOrder = order
self:SortData()
end
self.sortHeaders:RegisterCallback(ZO_SortHeaderGroup.HEADER_CLICKED, OnSortHeaderClicked)
self.sortHeaders:AddHeadersFromContainer()
local SUPPRESS_CALLBACKS = true
self.sortHeaders:SelectHeaderByKey("statusSortOrder", SUPPRESS_CALLBACKS)
ZO_MenuBar_SelectDescriptor(self.tabs, ITEM_TYPE_DISPLAY_CATEGORY_ALL)
self.searchBox = control:GetNamedChild("SearchFiltersTextSearchBox");
local function OnTextSearchTextChanged(editBox)
ZO_EditDefaultText_OnTextChanged(editBox)
TEXT_SEARCH_MANAGER:SetSearchText("companionEquipmentTextSearch", editBox:GetText())
end
self.searchBox:SetHandler("OnTextChanged", OnTextSearchTextChanged)
local SUPPRESS_TEXT_CHANGED_CALLBACK = true
local function OnListTextFilterComplete()
if COMPANION_EQUIPMENT_KEYBOARD_FRAGMENT:IsShowing() then
self.searchBox:SetText(TEXT_SEARCH_MANAGER:GetSearchText("companionEquipmentTextSearch"), SUPPRESS_TEXT_CHANGED_CALLBACK)
self:UpdateList()
end
end
TEXT_SEARCH_MANAGER:RegisterCallback("UpdateSearchResults", OnListTextFilterComplete)
-- inventory updates
local function HandleInventoryChanged()
if not control:IsHidden() then
self:UpdateList()
self:UpdateFreeSlots()
end
end
local function RefreshSlotLocked(slotIndex, locked)
local scrollData = ZO_ScrollList_GetDataList(self.list)
for i, dataEntry in ipairs(scrollData) do
local data = dataEntry.data
if data.slotIndex == slotIndex then
data.locked = locked
ZO_ScrollList_RefreshVisible(self.list)
break
end
end
end
local function HandleInventorySlotLocked(_, bagId, slotIndex)
if bagId == BAG_BACKPACK then
RefreshSlotLocked(slotIndex, true)
end
end
local function HandleInventorySlotUnlocked(_, bagId, slotIndex)
if bagId == BAG_BACKPACK then
RefreshSlotLocked(slotIndex, false)
end
end
control:RegisterForEvent(EVENT_INVENTORY_FULL_UPDATE, HandleInventoryChanged)
control:RegisterForEvent(EVENT_INVENTORY_SINGLE_SLOT_UPDATE, HandleInventoryChanged)
control:RegisterForEvent(EVENT_INVENTORY_SLOT_LOCKED, HandleInventorySlotLocked)
control:RegisterForEvent(EVENT_INVENTORY_SLOT_UNLOCKED, HandleInventorySlotUnlocked)
control:RegisterForEvent(EVENT_LEVEL_UPDATE, HandleInventoryChanged)
control:AddFilterForEvent(EVENT_LEVEL_UPDATE, REGISTER_FILTER_UNIT_TAG, "companion")
-- inventory landing area
self.landingAreaControl = self.list:GetNamedChild("LandingArea")
local function HandleCursorPickup(_, cursorType)
if cursorType == MOUSE_CONTENT_EQUIPPED_ITEM then
ZO_InventoryLandingArea_SetHidden(self.landingAreaControl, false)
end
end
local function HandleCursorCleared()
ZO_InventoryLandingArea_SetHidden(self.landingAreaControl, true)
end
control:RegisterForEvent(EVENT_CURSOR_PICKUP, HandleCursorPickup)
control:RegisterForEvent(EVENT_CURSOR_DROPPED, HandleCursorCleared)
-- fragment
COMPANION_EQUIPMENT_KEYBOARD_FRAGMENT = ZO_FadeSceneFragment:New(control)
COMPANION_EQUIPMENT_KEYBOARD_FRAGMENT:RegisterCallback("StateChange", function(oldState, newState)
if newState == SCENE_FRAGMENT_SHOWING then
TEXT_SEARCH_MANAGER:ActivateTextSearch("companionEquipmentTextSearch")
self:UpdateList()
self:UpdateFreeSlots()
elseif newState == SCENE_FRAGMENT_HIDDEN then
TEXT_SEARCH_MANAGER:DeactivateTextSearch("companionEquipmentTextSearch")
self:ClearNewStatusOnItemsThePlayerHasSeen()
self.newItemData = {}
end
end)
SHARED_INVENTORY:RegisterCallback("SlotAdded", function(bagId, slotIndex, newSlotData, suppressItemAlert)
if bagId == BAG_BACKPACK then
self:OnInventoryItemAdded(inventory, bagId, slotIndex, newSlotData, suppressItemAlert)
end
end)
end
function ZO_CompanionEquipment_Keyboard:OnInventoryItemAdded(inventoryType, bagId, slotIndex, newSlotData, suppressItemAlert)
-- play a brief flash animation on all the filter tabs that match this item's filterTypes
if COMPANION_EQUIPMENT_KEYBOARD_FRAGMENT:IsShowing() and newSlotData.brandNew then
self:PlayItemAddedAlert(newSlotData)
end
end
function ZO_CompanionEquipment_Keyboard:SetPlayerGoldAmount(value)
ZO_CurrencyControl_SetSimpleCurrency(self.playerGoldLabel, CURT_MONEY, value, ZO_KEYBOARD_CURRENCY_OPTIONS)
end
function ZO_CompanionEquipment_Keyboard:UpdateFreeSlots()
local numUsedSlots, numSlots = PLAYER_INVENTORY:GetNumSlots(INVENTORY_BACKPACK)
if numUsedSlots < numSlots then
self.freeSlotsLabel:SetText(zo_strformat(SI_INVENTORY_BACKPACK_REMAINING_SPACES, numUsedSlots, numSlots))
else
self.freeSlotsLabel:SetText(zo_strformat(SI_INVENTORY_BACKPACK_COMPLETELY_FULL, numUsedSlots, numSlots))
end
end
function ZO_CompanionEquipment_Keyboard:SetupItemRow(control, data)
local nameControl = control:GetNamedChild("Name")
local displayColor = GetItemQualityColor(data.displayQuality)
nameControl:SetText(displayColor:Colorize(data.name))
local sellPriceControl = control:GetNamedChild("SellPrice")
sellPriceControl:SetHidden(false)
ZO_CurrencyControl_SetSimpleCurrency(sellPriceControl, CURT_MONEY, data.stackSellPrice, ITEM_SLOT_CURRENCY_OPTIONS)
local inventorySlot = control:GetNamedChild("Button")
ZO_Inventory_BindSlot(inventorySlot, data.slotType, data.slotIndex, data.bagId)
ZO_PlayerInventorySlot_SetupSlot(control, data.stackCount, data.iconFile, data.meetsUsageRequirement, data.locked or IsUnitDead("player"))
ZO_UpdateStatusControlIcons(control, data)
end
function ZO_CompanionEquipment_Keyboard:CreateNewTabFilterData(filterType, text, normal, pressed, highlight, isSubFilter)
local tabData =
{
-- Custom data
activeTabText = text,
tooltipText = text,
sortKey = "statusSortOrder",
sortOrder = ZO_SORT_ORDER_DOWN,
isSubFilter = isSubFilter,
-- Menu bar data
descriptor = filterType,
normal = normal,
pressed = pressed,
highlight = highlight,
callback = function(filterData) self:ChangeFilter(filterData) end,
}
return tabData
end
function ZO_CompanionEquipment_Keyboard:ChangeFilter(filterData)
local activeTabText
local activeSubTabText
local formattedTabText
if self.currentFilter and filterData.isSubFilter then
local currentFilter
for _, filter in pairs(self.filters) do
if filter.descriptor == self.currentFilter.descriptor then
currentFilter = filter
break
end
end
self.currentFilter = currentFilter
self.currentSubFilter = filterData
formattedTabText = zo_strformat(SI_INVENTORY_FILTER_WITH_SUB_TAB, currentFilter.activeTabText, filterData.activeTabText)
else
self.currentFilter = filterData
self.currentSubFilter = nil
formattedTabText = filterData.activeTabText
end
local currentFilterType = self.currentFilter.descriptor
if not filterData.isSubFilter then
local menuBar = self.subTabs
if menuBar then
for _, button in ZO_MenuBar_ButtonControlIterator(menuBar) do
local flash = button:GetNamedChild("Flash")
flash:SetAlpha(0)
self:RemoveCategoryFlashAnimationControl(flash)
end
ZO_MenuBar_ClearButtons(menuBar)
if self.subFilters then
if self.subFilters[currentFilterType] then
for _, data in ipairs(self.subFilters[currentFilterType]) do
data.control = ZO_MenuBar_AddButton(menuBar, data)
end
ZO_MenuBar_SelectDescriptor(menuBar, ITEM_TYPE_DISPLAY_CATEGORY_ALL)
end
end
end
elseif #self.flashingSlots > 0 then
for _, flashingSlot in ipairs(self.flashingSlots) do
for _, subFilter in pairs(self.subFilters[currentFilterType]) do
if ZO_ItemFilterUtils.IsCompanionSlotInItemTypeDisplayCategoryAndSubcategory(flashingSlot, currentFilterType, subFilter.descriptor) then
self:AddCategoryFlashAnimationControl(subFilter.control:GetNamedChild("Flash"))
end
end
end
end
ZO_ScrollList_ResetToTop(self.list)
self:UpdateList()
self.sortHeaders:SelectAndResetSortForKey(filterData.sortKey)
end
function ZO_CompanionEquipment_Keyboard:SortData()
local scrollData = ZO_ScrollList_GetDataList(self.list)
table.sort(scrollData, self.sortFunction)
ZO_ScrollList_Commit(self.list)
end
do
local function DoesSlotPassAdditionalFilter(slot, currentFilter, additionalFilter)
if type(additionalFilter) == "function" then
return additionalFilter(slot)
elseif type(additionalFilter) == "number" then
return ZO_ItemFilterUtils.IsCompanionSlotInItemTypeDisplayCategoryAndSubcategory(slot, currentFilter, additionalFilter)
end
return true
end
function ZO_CompanionEquipment_Keyboard:ShouldAddItemToList(itemData)
if not DoesSlotPassAdditionalFilter(itemData, self.currentFilter.descriptor, self.currentSubFilter.descriptor) then
return false
end
if not DoesSlotPassAdditionalFilter(itemData, self.currentFilter.descriptor, self.additionalFilter) then
return false
end
return ZO_ItemFilterUtils.IsCompanionSlotInItemTypeDisplayCategoryAndSubcategory(itemData, self.currentFilter.descriptor, self.currentSubFilter.descriptor) and TEXT_SEARCH_MANAGER:IsItemInSearchTextResults("companionEquipmentTextSearch", BACKGROUND_LIST_FILTER_TARGET_BAG_SLOT, itemData.bagId, itemData.slotIndex)
end
end
function ZO_CompanionEquipment_Keyboard:UpdateList()
local scrollData = ZO_ScrollList_GetDataList(self.list)
local newItemData = {}
ZO_ScrollList_Clear(self.list)
for slotIndex in ZO_IterateBagSlots(BAG_BACKPACK) do
local slotData = SHARED_INVENTORY:GenerateSingleSlotData(BAG_BACKPACK, slotIndex)
if slotData and slotData.stackCount > 0 and slotData.actorCategory == GAMEPLAY_ACTOR_CATEGORY_COMPANION then
local itemData = ZO_EntryData:New(slotData)
itemData.slotType = SLOT_TYPE_ITEM
if itemData.brandNew then
newItemData[slotIndex] = itemData
if self.newItemData[slotIndex] then
newItemData[slotIndex].clearAgeOnClose = self.newItemData[slotIndex].clearAgeOnClose
else
--Only play the item added alert once
--If item data is already stored for this, then we've already played the alert
self:PlayItemAddedAlert(slotData)
end
end
if self:ShouldAddItemToList(itemData) then
table.insert(scrollData, ZO_ScrollList_CreateDataEntry(DATA_TYPE_ITEM, itemData))
end
end
end
self.newItemData = newItemData
table.sort(scrollData, self.sortFunction)
ZO_ScrollList_Commit(self.list)
local isListEmpty = #scrollData == 0
self.sortHeadersControl:SetHidden(isListEmpty)
self.emptyLabel:SetHidden(not isListEmpty)
end
do
local function TryClearNewStatus(slot)
if slot and slot.clearAgeOnClose then
slot.clearAgeOnClose = nil
SHARED_INVENTORY:ClearNewStatus(slot.bagId, slot.slotIndex)
return true
else
return false
end
end
function ZO_CompanionEquipment_Keyboard:ClearNewStatusOnItemsThePlayerHasSeen(inventoryType)
local anyNewStatusCleared = false
for slotIndex, dataEntry in pairs(self.newItemData) do
local newStatusCleared = TryClearNewStatus(dataEntry)
anyNewStatusCleared = anyNewStatusCleared or newStatusCleared
end
if anyNewStatusCleared then
if self.list then
ZO_ScrollList_RefreshVisible(self.list, nil, ZO_UpdateStatusControlIcons)
end
COMPANION_KEYBOARD:UpdateSceneGroupButtons()
COMPANION_CHARACTER_KEYBOARD:RefreshCategoryStatusIcons()
end
end
end
function ZO_CompanionEquipment_Keyboard:SetupCategoryFlashAnimation()
self.categoryFlashAnimationTimeline = ANIMATION_MANAGER:CreateTimelineFromVirtual("ZO_CompanionEquipment_Keyboard_NewItemCategory_FlashAnimation")
self.flashingSlots = {}
self.listeningControls = {}
local function OnStop()
self.flashingSlots = {}
self.listeningControls = {}
end
self.categoryFlashAnimationTimeline:SetHandler("OnStop", OnStop)
end
function ZO_CompanionEquipment_Keyboard:AddCategoryFlashAnimationControl(control)
local controlName = control:GetName()
self.listeningControls[controlName] = control
end
function ZO_CompanionEquipment_Keyboard:RemoveCategoryFlashAnimationControl(control)
local controlName = control:GetName()
self.listeningControls[controlName] = nil
end
do
local FLASH_ANIMATION_MIN_ALPHA = 0
local FLASH_ANIMATION_MAX_ALPHA = 0.5
function ZO_CompanionEquipment_Keyboard:UpdateCategoryFlashAnimation(timeline, progress)
local remainingPlaybackLoops = self.categoryFlashAnimationTimeline:GetPlaybackLoopsRemaining()
local currentAlpha
local alphaDelta = progress * (FLASH_ANIMATION_MAX_ALPHA - FLASH_ANIMATION_MIN_ALPHA)
if remainingPlaybackLoops % 2 then
-- Fading out
currentAlpha = alphaDelta + FLASH_ANIMATION_MIN_ALPHA
else
-- Fading in
currentAlpha = FLASH_ANIMATION_MAX_ALPHA - alphaDelta
end
for _, control in pairs(self.listeningControls) do
control:SetAlpha(currentAlpha)
end
end
end
function ZO_CompanionEquipment_Keyboard:PlayItemAddedAlert(slot)
local isSlotAdded = false
for _, filter in pairs(self.filters) do
if ZO_ItemFilterUtils.IsSlotInItemTypeDisplayCategoryAndSubcategory(slot, ITEM_TYPE_DISPLAY_CATEGORY_COMPANION, filter.descriptor) then
self:AddCategoryFlashAnimationControl(filter.control:GetNamedChild("Flash"))
if not self.categoryFlashAnimationTimeline:IsPlaying() then
self.categoryFlashAnimationTimeline:PlayFromStart()
end
if not isSlotAdded then
table.insert(self.flashingSlots, slot)
slotAdded = true
end
end
end
local currentFilter = self.currentFilter
for _, subFilter in pairs(self.subFilters[currentFilter.descriptor]) do
if ZO_ItemFilterUtils.IsCompanionSlotInItemTypeDisplayCategoryAndSubcategory(slot, currentFilter.descriptor, subFilter.descriptor) then
self:AddCategoryFlashAnimationControl(subFilter.control:GetNamedChild("Flash"))
if not self.categoryFlashAnimationTimeline:IsPlaying() then
self.categoryFlashAnimationTimeline:PlayFromStart()
end
if not isSlotAdded then
table.insert(self.flashingSlots, slot)
slotAdded = true
end
end
end
end
-----------------------------
-- Global XML Functions
-----------------------------
function ZO_CompanionEquipment_Keyboard_OnInitialize(control)
COMPANION_EQUIPMENT_KEYBOARD = ZO_CompanionEquipment_Keyboard:New(control)
end
function ZO_CompanionEquipment_Keyboard_NewItemCategory_FlashAnimation_OnUpdate(self, progress)
COMPANION_EQUIPMENT_KEYBOARD:UpdateCategoryFlashAnimation(self, progress)
end |
--
-- This is file `lualibs-basic.lua',
-- generated with the docstrip utility.
--
-- The original source files were:
--
-- lualibs.dtx (with options: `basic')
-- This is a generated file.
--
-- Copyright (C) 2009--2021 by
-- PRAGMA ADE / ConTeXt Development Team
-- The LaTeX Project Team
--
-- See ConTeXt's mreadme.pdf for the license.
--
-- This work consists of the main source file lualibs.dtx
-- and the derived files lualibs.lua, lualibs-basic.lua,
-- and lualibs-extended.lua.
--
-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
lualibs = lualibs or { }
local info = lualibs.info
local loadmodule = lualibs.loadmodule
local lualibs_basic_module = {
name = "lualibs-basic",
version = "2.74", --TAGVERSION
date = "2021-05-20", --TAGDATE
description = "ConTeXt Lua libraries -- basic collection.",
author = "Hans Hagen, PRAGMA-ADE, Hasselt NL & Elie Roux & Philipp Gesang",
copyright = "PRAGMA ADE / ConTeXt Development Team",
license = "See ConTeXt's mreadme.pdf for the license",
}
local loaded = false --- track success of package loading
if lualibs.prefer_merged then
info"Loading merged package for collection “basic”."
loaded = loadmodule('lualibs-basic-merged.lua')
else
info"Ignoring merged packages."
info"Falling back to individual libraries from collection “basic”."
end
if loaded == false then
loadmodule("lualibs-lua.lua")
loadmodule("lualibs-package.lua")
loadmodule("lualibs-lpeg.lua")
loadmodule("lualibs-function.lua")
loadmodule("lualibs-string.lua")
loadmodule("lualibs-table.lua")
loadmodule("lualibs-boolean.lua")
loadmodule("lualibs-number.lua")
loadmodule("lualibs-math.lua")
loadmodule("lualibs-io.lua")
loadmodule("lualibs-os.lua")
loadmodule("lualibs-file.lua")
loadmodule("lualibs-gzip.lua")
loadmodule("lualibs-md5.lua")
loadmodule("lualibs-dir.lua")
loadmodule("lualibs-unicode.lua")
loadmodule("lualibs-url.lua")
loadmodule("lualibs-set.lua")
end
lualibs.basic_loaded = true
-- vim:tw=71:sw=2:ts=2:expandtab
-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--
-- End of File `lualibs-basic.lua'.
|
Ship = Ship or {}
--- mark that a ship is part of a fleet
--- @internal
--- @param self
--- @param ship CpuShip
--- @param fleet Fleet
--- @return CpuShip
Ship.withFleet = function(self, ship, fleet)
if not isEeShip(ship) then error("Expected ship to be Ship, but got " .. typeInspect(ship), 2) end
if Ship:hasFleet(ship) then error("Ship already has a fleet", 2) end
if not Fleet:isFleet(fleet) then error("Expected fleet to be a fleet, but got " .. typeInspect(fleet), 2) end
--- get the fleet this ship is belonging to
--- @param self
--- @return Fleet
ship.getFleet = function(self) return fleet end
--- get the fleet leader of the ships fleet
--- @param self
--- @return CpuShip|nil
ship.getFleetLeader = function(self) return fleet:getLeader() end
--- check if the current ship is leader of a fleet
--- @param self
--- @return boolean
ship.isFleetLeader = function(self) return fleet:getLeader():isValid() and fleet:getLeader() == self end
return ship
end
--- check if a ship is part of a fleet
--- @param self
--- @param ship any
--- @return boolean
Ship.hasFleet = function(self, ship)
return isEeShip(ship) and
isFunction(ship.getFleet) and
isFunction(ship.getFleetLeader) and
isFunction(ship.isFleetLeader)
end |
print('testing i/o')
assert(io.input(io.stdin) == io.stdin)
assert(io.output(io.stdout) == io.stdout)
assert(type(io.input()) == "userdata" and io.type(io.output()) == "file")
assert(io.type(8) == nil)
local a = {}; setmetatable(a, {})
assert(io.type(a) == nil)
local a, b, c = io.open('xuxu_nao_existe')
assert(not a and type(b) == "string" and type(c) == "number")
a, b, c = io.open('/a/b/c/d', 'w')
assert(not a and type(b) == "string" and type(c) == "number")
local file = os.tmpname()
local otherfile = os.tmpname()
assert(os.setlocale('C', 'all'))
io.input(io.stdin); io.output(io.stdout);
os.remove(file)
assert(loadfile(file) == nil)
assert(io.open(file) == nil)
io.output(file)
assert(io.output() ~= io.stdout)
assert(io.output():seek() == 0)
assert(io.write("alo alo"))
assert(io.output():seek() == string.len("alo alo"))
assert(io.output():seek("cur", -3) == string.len("alo alo") - 3)
assert(io.write("joao"))
assert(io.output():seek("end") == string.len("alo joao"))
assert(io.output():seek("set") == 0)
assert(io.write('"�lo"', "{a}\n", "second line\n", "third line \n"))
assert(io.write('�fourth_line'))
io.output(io.stdout)
collectgarbage() -- file should be closed by GC
assert(io.input() == io.stdin and rawequal(io.output(), io.stdout))
print('+')
-- test GC for files
collectgarbage()
for i = 1, 120 do
for i = 1, 5 do
io.input(file)
assert(io.open(file, 'r'))
io.lines(file)
end
collectgarbage()
end
assert(os.rename(file, otherfile))
assert(os.rename(file, otherfile) == nil)
io.output(io.open(otherfile, "a"))
assert(io.write("\n\n\t\t 3450\n"));
io.close()
-- test line generators
assert(os.rename(otherfile, file))
io.output(otherfile)
local f = io.lines(file)
while f() do end;
assert(not pcall(f)) -- read lines after EOF
assert(not pcall(f)) -- read lines after EOF
-- copy from file to otherfile
for l in io.lines(file) do io.write(l, "\n") end
io.close()
-- copy from otherfile back to file
local f = assert(io.open(otherfile))
assert(io.type(f) == "file")
io.output(file)
assert(io.output():read() == nil)
for l in f:lines() do io.write(l, "\n") end
assert(f:close()); io.close()
assert(not pcall(io.close, f)) -- error trying to close again
assert(tostring(f) == "file (closed)", tostring(f))
assert(io.type(f) == "closed file")
io.input(file)
f = io.open(otherfile):lines()
for l in io.lines() do assert(l == f()) end
assert(os.remove(otherfile))
--[[
io.input(file)
do -- test error returns
local a, b, c = io.input():write("xuxu")
assert(not a and type(b) == "string" and type(c) == "number")
end
assert(io.read(0) == "") -- not eof
assert(io.read(5, '*l') == '"�lo"')
assert(io.read(0) == "")
assert(io.read() == "second line")
local x = io.input():seek()
assert(io.read() == "third line ")
assert(io.input():seek("set", x))
assert(io.read('*l') == "third line ")
assert(io.read(1) == "�")
assert(io.read(string.len "fourth_line") == "fourth_line")
assert(io.input():seek("cur", -string.len "fourth_line"))
assert(io.read() == "fourth_line")
assert(io.read() == "") -- empty line
assert(io.read('*n') == 3450)
assert(io.read(1) == '\n')
assert(io.read(0) == nil) -- end of file
assert(io.read(1) == nil) -- end of file
assert(({ io.read(1) })[2] == nil)
assert(io.read() == nil) -- end of file
assert(({ io.read() })[2] == nil)
assert(io.read('*n') == nil) -- end of file
assert(({ io.read('*n') })[2] == nil)
assert(io.read('*a') == '') -- end of file (OK for `*a')
assert(io.read('*a') == '') -- end of file (OK for `*a')
collectgarbage()
print('+')
io.close(io.input())
assert(not pcall(io.read))
]]
assert(os.remove(file))
local t = '0123456789'
for i = 1, 12 do t = t .. t; end
assert(string.len(t) == 10 * 2 ^ 12)
io.output(file)
io.write("alo\n")
io.close()
assert(not pcall(io.write))
local f = io.open(file, "a")
io.output(f)
collectgarbage()
assert(io.write(' ' .. t .. ' '))
assert(io.write(';', 'end of file\n'))
f:flush(); io.flush()
f:close()
print('+')
io.input(file)
local l = io.read()
assert(l == "alo", ("%q"):format(l or ""))
assert(io.read(1) == ' ')
assert(io.read(string.len(t)) == t)
assert(io.read(1) == ' ')
assert(io.read(0))
assert(io.read('*a') == ';end of file\n')
--assert(io.read(0) == nil)
assert(io.close(io.input()))
assert(os.remove(file))
print('+')
local x1 = "string\n\n\\com \"\"''coisas [[estranhas]] ]]'"
io.output(file)
assert(io.write(string.format("x2 = %q\n-- comment without ending EOS", x1)))
io.close()
assert(loadfile(file))()
assert(x1 == x2)
print('+')
assert(os.remove(file))
assert(os.remove(file) == nil)
assert(os.remove(otherfile) == nil)
io.output(file)
assert(io.write("qualquer coisa\n"))
assert(io.write("mais qualquer coisa"))
io.close()
io.output(assert(io.open(otherfile, 'wb')))
assert(io.write("outra coisa\0\1\3\0\0\0\0\255\0"))
io.close()
local filehandle = assert(io.open(file, 'r'))
local otherfilehandle = assert(io.open(otherfile, 'rb'))
assert(filehandle ~= otherfilehandle)
assert(type(filehandle) == "userdata")
assert(filehandle:read('*l') == "qualquer coisa")
io.input(otherfilehandle)
assert(io.read(string.len "outra coisa") == "outra coisa")
assert(filehandle:read('*l') == "mais qualquer coisa")
filehandle:close();
assert(type(filehandle) == "userdata")
io.input(otherfilehandle)
assert(io.read(4) == "\0\1\3\0")
assert(io.read(3) == "\0\0\0")
assert(io.read(0) == "") -- 255 is not eof
assert(io.read(1) == "\255")
assert(io.read('*a') == "\0")
--assert(not io.read(0))
assert(otherfilehandle == io.input())
otherfilehandle:close()
assert(os.remove(file))
assert(os.remove(otherfile))
collectgarbage()
io.output(file)
io.write [[
123.4 -56e-2 not a number
second line
third line
and the rest of the file
]]
io.close()
io.input(file)
local _, a, b, c, d, e, h, __ = io.read(1, '*n', '*n', '*l', '*l', '*l', '*a', 10)
assert(io.close(io.input()))
assert(_ == ' ' and __ == nil)
assert(type(a) == 'number' and a == 123.4 and b == -56e-2)
assert(d == 'second line' and e == 'third line')
assert(h == [[
and the rest of the file
]])
assert(os.remove(file))
collectgarbage()
-- testing buffers
--[[ do
local f = assert(io.open(file, "w"))
local fr = assert(io.open(file, "r"))
assert(f:setvbuf("full", 2000))
f:write("x")
assert(fr:read("*all") == "") -- full buffer; output not written yet
f:close()
fr:seek("set")
assert(fr:read("*all") == "x") -- `close' flushes it
f = assert(io.open(file), "w")
assert(f:setvbuf("no"))
f:write("x")
fr:seek("set")
assert(fr:read("*all") == "x") -- no buffer; output is ready
f:close()
f = assert(io.open(file, "a"))
assert(f:setvbuf("line"))
f:write("x")
fr:seek("set", 1)
assert(fr:read("*all") == "") -- line buffer; no output without `\n'
f:write("a\n")
fr:seek("set", 1)
assert(fr:read("*all") == "xa\n") -- now we have a whole line
f:close(); fr:close()
end]]
-- testing large files (> BUFSIZ)
io.output(file)
for i = 1, 5001 do io.write('0123456789123') end
io.write('\n12346')
io.close()
io.input(file)
local x = io.read('*a')
io.input():seek('set', 0)
local y = io.read(30001) .. io.read(1005) .. io.read(0) .. io.read(1) .. io.read(100003)
assert(x == y and string.len(x) == 5001 * 13 + 6)
io.input():seek('set', 0)
y = io.read() -- huge line
assert(x == y .. '\n' .. io.read())
assert(io.read() == nil)
io.close(io.input())
assert(os.remove(file))
x = nil; y = nil
x, y = pcall(io.popen, "ls")
if x then
assert(y:read("*a"))
assert(y:close())
else
(Message or print)('\a\n >>> popen not available<<<\n\a')
end
print '+'
local t = os.time()
T = os.date("*t", t)
loadstring(os.date([[assert(T.year==%Y and T.month==%m and T.day==%d and
T.hour==%H and T.min==%M and T.sec==%S and
T.wday==%w+1 and T.yday==%j and type(T.isdst) == 'boolean')]], t))()
assert(os.time(T) == t)
T = os.date("!*t", t)
loadstring(os.date([[!assert(T.year==%Y and T.month==%m and T.day==%d and
T.hour==%H and T.min==%M and T.sec==%S and
T.wday==%w+1 and T.yday==%j and type(T.isdst) == 'boolean')]], t))()
do
local T = os.date("*t")
local t = os.time(T)
assert(type(T.isdst) == 'boolean')
T.isdst = nil
local t1 = os.time(T)
assert(t == t1) -- if isdst is absent uses correct default
end
t = os.time(T)
T.year = T.year - 1;
local t1 = os.time(T)
-- allow for leap years
assert(math.abs(os.difftime(t, t1) / (24 * 3600) - 365) < 2)
t = os.time()
t1 = os.time(os.date("*t"))
assert(os.difftime(t1, t) <= 2)
local t1 = os.time { year = 2000, month = 10, day = 1, hour = 23, min = 12, sec = 17 }
local t2 = os.time { year = 2000, month = 10, day = 1, hour = 23, min = 10, sec = 19 }
assert(os.difftime(t1, t2) == 60 * 2 - 2)
io.output(io.stdout)
local d = os.date('%d')
local m = os.date('%m')
local a = os.date('%Y')
local ds = os.date('%w') + 1
local h = os.date('%H')
local min = os.date('%M')
local s = os.date('%S')
io.write(string.format('test done on %2.2d/%2.2d/%d', d, m, a))
io.write(string.format(', at %2.2d:%2.2d:%2.2d\n', h, min, s))
io.write(string.format('%s\n', _VERSION))
|
--MoveCurve
--H_Yuzuru/curve_Attack2_1 curve_Attack2_1
return
{
filePath = "H_Yuzuru/curve_Attack2_1",
startTime = Fixed64(0) --[[0]],
startRealTime = Fixed64(0) --[[0]],
endTime = Fixed64(92274688) --[[88]],
endRealTime = Fixed64(1107296) --[[1.056]],
isZoom = false,
isCompensate = false,
curve = {
[1] = {
time = 0 --[[0]],
value = 0 --[[0]],
inTangent = 244729 --[[0.2333914]],
outTangent = 244729 --[[0.2333914]],
},
[2] = {
time = 283116 --[[0.27]],
value = 524288 --[[0.5]],
inTangent = 333484 --[[0.3180351]],
outTangent = 333484 --[[0.3180351]],
},
[3] = {
time = 918651 --[[0.8760937]],
value = 563114 --[[0.5370277]],
inTangent = 286535 --[[0.273261]],
outTangent = 286535 --[[0.273261]],
},
},
} |
LIMIT = 100
for i = 1, LIMIT do
if i % 15 == 0 then
io.write("FizzBuzz")
elseif i % 3 == 0 then
io.write("Fizz")
elseif i % 5 == 0 then
io.write("Buzz")
else
io.write(i)
end
if i < LIMIT then
io.write(", ")
end
end
print()
|
-----------------------------------
--
-- tpz.effect.AGGRESSOR
--
-----------------------------------
require("scripts/globals/status")
-----------------------------------
function onEffectGain(target,effect)
local power = effect:getPower()
target:addMod(tpz.mod.ACC, power)
target:addMod(tpz.mod.EVA, -power)
-- Aggresive Aim
local subpower = effect:getSubPower()
target:addMod(tpz.mod.RACC, subpower)
end
function onEffectTick(target,effect)
end
function onEffectLose(target,effect)
local power = effect:getPower()
target:delMod(tpz.mod.RACC, power)
target:delMod(tpz.mod.EVA, -power)
-- Aggresive Aim
local subpower = effect:getSubPower()
target:delMod(tpz.mod.ACC, subpower)
end
|
local function check(condition, ...)
if condition then return condition end
io.stderr:write(string.format(...), "\n")
os.exit(1)
end
check(#arg >= 1, "usage:\n "..arg[0].." <topic> [<server> [<port> [<username> [<password>]]]]")
local mq = require"mosquitto"
io.stderr:write("libmosquitto version "..table.concat({mq.lib_version()}, ".").."\n")
local client = mq.new("ffi_mosquitto example")
if arg[4] then
client:username_pw_set(arg[4], arg[5])
end
client:connect(arg[2], arg[3])
client:subscribe_message_callback(arg[1], nil, function(message)
print(message)
end)
client:loop_forever()
|
package("hiredis")
set_homepage("https://github.com/redis/hiredis")
set_description("Minimalistic C client for Redis >= 1.2")
set_license("BSD-3-Clause")
add_urls("https://github.com/redis/hiredis/archive/refs/tags/$(version).tar.gz",
"https://github.com/redis/hiredis.git")
add_versions('v1.0.2', 'e0ab696e2f07deb4252dda45b703d09854e53b9703c7d52182ce5a22616c3819')
if is_plat("windows", "mingw") then
add_configs("shared", {description = "Build shared library.", default = true, type = "boolean", readonly = true})
add_configs("vs_runtime", {description = "Set vs compiler runtime.", default = "MD", readonly = true})
end
add_configs("openssl", {description = "with openssl library", default = false, type = "boolean"})
add_deps("cmake")
on_load(function (package)
if package:config("openssl") then
package:add("deps", "openssl")
end
end)
on_install(function (package)
if not package:config("shared") then
if package:version():eq("v1.0.2") then
-- Following change is required for package user to call `find_package(hiredis)` to work.
io.replace("CMakeLists.txt", "ADD_LIBRARY(hiredis SHARED", "ADD_LIBRARY(hiredis", {plain = true})
io.replace("CMakeLists.txt", "ADD_LIBRARY(hiredis_ssl SHARED", "ADD_LIBRARY(hiredis_ssl", {plain = true})
end
end
local configs = {
"-DDISABLE_TESTS=ON",
"-DENABLE_SSL_TESTS=OFF",
}
table.insert(configs, "-DCMAKE_BUILD_TYPE=" .. (package:debug() and "Debug" or "Release"))
table.insert(configs, "-DENABLE_SSL=" .. (package:config("openssl") and "ON" or "OFF"))
import("package.tools.cmake").install(package, configs)
-- hiredis cmake builds static and shared library at the same time.
-- Remove unneeded one after install.
if package:config("shared") then
os.tryrm(path.join(package:installdir("lib"), "*.a"))
else
os.tryrm(path.join(package:installdir("lib"), "*.so"))
os.tryrm(path.join(package:installdir("lib"), "*.so.*"))
os.tryrm(path.join(package:installdir("lib"), "*.dylib"))
end
end)
on_test(function (package)
assert(package:has_cfuncs("redisCommand", {includes = "hiredis/hiredis.h"}))
end)
|
local module = {Name = "Null"}
local WeaponDataBase = {
{
ID = 1,
WeaponName = "Proof of Awakening",
Description = "The idea of awakening is conceptual. There is no physical form to show.",
Rarity = 1,
LevelReq = 1,
MaxUpgrades = 0,
MaxEnchantments = 0,
SellPrice = 0,
Model = nil,
Skills = { --up to 5
},
Stats = {
HP = 2,
ATK = 0,
DEF = 1,
STAM = 0,
CRIT = 0,
CRITDEF = 0 ---- IFRAME DURATIONS PERCENTAGE
},
StatsPerLevel = {
HP = 0,
ATK = 0,
DEF = 0,
STAM = 0,
CRIT = 0,
CRITDEF = 0
}
}
}
local LootList = {
NormalLoots = {
["Nothing"] = 0
},
HeroLoots = {
["Nothing"] = 0
},
EMDLoots = {
["Nothing"] = 0
}
}
function module:ReturnMapLootList(MapName, Difficulty)
--- Rarity Weight / Total WEight
if typeof(MapName) == "string" and typeof(Difficulty) == "string" then
local Total = 0
local NewList = {}
if Difficulty == "HeroesMustDie" then
for b,v in pairs(LootList.EMDLoots) do
Total = Total + v
local NewItem = {}
NewItem.ID = b
NewItem.Chance = v
table.insert(NewList, NewItem)
end
return NewList, Total
elseif Difficulty == "Hero" then
for b,v in pairs(LootList.HeroLoots) do
Total = Total + v
local NewItem = {}
NewItem.ID = b
NewItem.Chance = v
table.insert(NewList, NewItem)
end
return NewList, Total
else
for b,v in pairs(LootList.NormalLoots) do
Total = Total + v
local NewItem = {}
NewItem.ID = b
NewItem.Chance = v
table.insert(NewList, NewItem)
end
return NewList, Total
end
end
end
function module:ReturnTrophyList()
return WeaponDataBase
end
return module
|
--
-- Created by David Lannan
-- User: grover
-- Date: 6/03/13
-- Time: 12:07 AM
-- Copyright 2013 Developed for use with the byt3d engine.
--
------------------------------------------------------------------------------------------------------------
-- State - Editor main icon panel
--
-- Decription: Displays the new editor icon dropdown panel.
-- Icons may be exploders or sliders or buttons.
------------------------------------------------------------------------------------------------------------
local PEditorMain = NewState()
------------------------------------------------------------------------------------------------------------
-- Load in the new asset management panel - should slide in.
function IconAssets( obj )
if obj.meta.flags["assets_last"] == "RequestClose" then
obj.meta.flags["assets"] = "RequestOpen"
obj.meta.flags["assets_last"] = "RequestOpen"
else
obj.meta.flags["assets"] = "RequestClose"
obj.meta.flags["assets_last"] = "RequestClose"
end
end
------------------------------------------------------------------------------------------------------------
function IconClose( obj )
obj.meta.flags["close"] = true
end
------------------------------------------------------------------------------------------------------------
function PEditorMain:Begin()
-- List of flags used to determine what to do
self.flags = {}
self.flags["close"] = false
self.flags["assets"] = nil
self.flags["assets_last"] = "RequestClose"
-- Add all the icons here that we will use.
self.icons = {}
self.icons["generic"] = Gcairo:LoadImage("icon_generic", "byt3d/data/icons/generic_64.png")
self.icons["main"] = Gcairo:LoadImage("main", "byt3d/data/icons/generic_64.png")
self.icons["assets"] = Gcairo:LoadImage("assets", "byt3d/data/icons/generic_obj_folder_64.png")
self.icons["nodes"] = Gcairo:LoadImage("nodes", "byt3d/data/icons/generic_obj_list_64.png")
self.icons["m3"] = Gcairo:LoadImage("m3", "byt3d/data/icons/generic_obj_attach_64.png")
self.icons["m4"] = Gcairo:LoadImage("m4", "byt3d/data/icons/generic_obj_box_64.png")
self.icons["m5"] = Gcairo:LoadImage("m5", "byt3d/data/icons/generic_obj_config_64.png")
self.icons["m6"] = Gcairo:LoadImage("m6", "byt3d/data/icons/generic_obj_doc_64.png")
self.icons["close"] = Gcairo:LoadImage("close", "byt3d/data/icons/generic_obj_close_64.png")
end
------------------------------------------------------------------------------------------------------------
function PEditorMain:Update(mxi, myi, buttons)
local saved = Gcairo.style.button_color
local fontsize = 16
local iconsize = 22
local tcolor = { r=1.0, b=1.0, g=1.0, a=1.0 }
local iconlist = Gcairo:List("", 0, 0, 220, fontsize + 10)
local editor = self
local line1 = {
{ name = " ", ntype=CAIRO_TYPE.TEXT, size=1 },
{ name="i_assets", ntype=CAIRO_TYPE.IMAGE, image=self.icons["assets"], size=iconsize, color=tcolor, meta=editor, callback=IconAssets },
{ name = " ", ntype=CAIRO_TYPE.TEXT, size=1 },
{ name="i_nodes", ntype=CAIRO_TYPE.IMAGE, image=self.icons["nodes"], size=iconsize, color=tcolor },
{ name = " ", ntype=CAIRO_TYPE.TEXT, size=1 },
{ name="test3", ntype=CAIRO_TYPE.IMAGE, image=self.icons["m3"], size=iconsize, color=tcolor },
{ name = " ", ntype=CAIRO_TYPE.TEXT, size=1 },
{ name="test4", ntype=CAIRO_TYPE.IMAGE, image=self.icons["m4"], size=iconsize, color=tcolor },
{ name = " ", ntype=CAIRO_TYPE.TEXT, size=1 },
{ name="test5", ntype=CAIRO_TYPE.IMAGE, image=self.icons["m5"], size=iconsize, color=tcolor },
{ name = " ", ntype=CAIRO_TYPE.TEXT, size=1 },
{ name="test6", ntype=CAIRO_TYPE.IMAGE, image=self.icons["m6"], size=iconsize, color=tcolor },
{ name = " ", ntype=CAIRO_TYPE.TEXT, size=8 },
{ name="i_close", ntype=CAIRO_TYPE.IMAGE, image=self.icons["close"], size=iconsize, color=tcolor, meta=editor, callback=IconClose }
}
-- A Content window of 'stuff' to show
local snodes = {}
snodes[1] = { name = " ", ntype=CAIRO_TYPE.TEXT, size=1 }
snodes[2] = { name = "line1", ntype=CAIRO_TYPE.HLINE, size=fontsize + 4 , nodes=line1 }
iconlist.nodes = snodes
Gcairo.style.border_width = 0.0
Gcairo.style.button_color = CAIRO_STYLE.METRO.LBLUE
Gcairo.style.button_color.a = 1
Gcairo:Exploder("emain", self.icons["main"], CAIRO_UI.RIGHT, 245, 1, 24, 24, 0, iconlist)
Gcairo.style.button_color = saved
end
------------------------------------------------------------------------------------------------------------
function PEditorMain:Render()
end
------------------------------------------------------------------------------------------------------------
function PEditorMain:Finish()
end
------------------------------------------------------------------------------------------------------------
return PEditorMain
------------------------------------------------------------------------------------------------------------ |
object_tangible_collection_col_force_shui_table_03 = object_tangible_collection_shared_col_force_shui_table_03:new {
gameObjectType = 8211,}
ObjectTemplates:addTemplate(object_tangible_collection_col_force_shui_table_03, "object/tangible/collection/col_force_shui_table_03.iff") |
T = require( "t" )
Pack = require( "t.Pack" )
Buffer = require( "t.Buffer" )
utl = T.require( "t_pck_utl" )
-- >I3 <i2 b B >I5 <I4 h
-- aBc De ü HiJkL mNoP ö
expect = { 6373987, 25924, -61, 188, 311004130124, 1349471853, -18749 }
b = Buffer( 'aBcDeüHiJkLmNoPö' )
fmts = '>I3<i2bB>I5<I4h'
print( b:toHex(), '', '', #b, b:read() )
print( string.unpack( fmts, b:read() ) )
s = Pack( fmts )
print( "Sequence:", #s , s )
print( "-------------------------------------------------------------")
utl.get(s,b)
b1 = Buffer( #b ) -- create empty buffer of #b length
print( b1:toHex(), '', '', #b1 )
utl.set(s,b1,expect) -- fill with except values
print( b1:toHex(), '', '', #b1, b1:read() ) -- expecting same as buffer b
assert( b1 == b, "The buffer shall be identical" )
|
package("pkgconf")
set_kind("binary")
set_homepage("http://pkgconf.org")
set_description("A program which helps to configure compiler and linker flags for development frameworks.")
add_urls("https://distfiles.dereferenced.org/pkgconf/pkgconf-$(version).tar.xz")
add_versions("1.7.4", "d73f32c248a4591139a6b17777c80d4deab6b414ec2b3d21d0a24be348c476ab")
if is_plat("windows") then
add_deps("meson", "ninja")
end
on_install("linux", "bsd", function(package)
local configs = {}
table.insert(configs, "--enable-shared=" .. (package:config("shared") and "yes" or "no"))
table.insert(configs, "--enable-static=" .. (package:config("shared") and "no" or "yes"))
if package:config("pic") ~= false then
table.insert(configs, "--with-pic")
end
import("package.tools.autoconf").install(package, configs)
end)
on_install("windows", function(package)
import("package.tools.meson").install(package, {"-Dtests=false"})
end)
on_test(function (package)
os.vrun("pkgconf --version")
end)
|
local metric = {}
function metric.new(spec)
local instance = spec.metric or { counts = {}, sets = {} }
spec.metric = instance
instance.count = function(name, inc)
instance.counts[name] = (instance.counts[name] or 0) + (inc or 1)
end
instance.set = function(name, value)
instance.sets[name] = value
end
return instance
end
return metric
|
function main()
local all=0
local t=os.clock()
for i=1,100000000 do
all=all+i
end
print(os.clock()-t,all)
end
main() |
---------------------------------------------------------------------------
--- Timer objects and functions.
--
-- @usage
-- -- Create a widget and update its content using the output of a shell
-- -- command every 10 seconds:
-- local mybatterybar = wibox.widget {
-- {
-- min_value = 0,
-- max_value = 100,
-- value = 0,
-- paddings = 1,
-- border_width = 1,
-- forced_width = 50,
-- border_color = "#0000ff",
-- id = "mypb",
-- widget = wibox.widget.progressbar,
-- },
-- {
-- id = "mytb",
-- text = "100%",
-- widget = wibox.widget.textbox,
-- },
-- layout = wibox.layout.stack,
-- set_battery = function(self, val)
-- self.mytb.text = tonumber(val).."%"
-- self.mypb.value = tonumber(val)
-- end,
-- }
--
-- gears.timer {
-- timeout = 10,
-- call_now = true,
-- autostart = true,
-- callback = function()
-- -- You should read it from `/sys/class/power_supply/` (on Linux)
-- -- instead of spawning a shell. This is only an example.
-- awful.spawn.easy_async(
-- {"sh", "-c", "acpi | sed -n 's/^.*, \([0-9]*\)%/\1/p'"},
-- function(out)
-- mybatterybar.battery = out
-- end
-- )
-- end
-- }
--
-- @author Uli Schlachter
-- @copyright 2014 Uli Schlachter
-- @coreclassmod gears.timer
---------------------------------------------------------------------------
local capi = { awesome = awesome }
local ipairs = ipairs
local pairs = pairs
local setmetatable = setmetatable
local table = table
local tonumber = tonumber
local traceback = debug.traceback
local unpack = unpack or table.unpack -- luacheck: globals unpack (compatibility with Lua 5.1)
local glib = require("lgi").GLib
local object = require("gears.object")
local protected_call = require("gears.protected_call")
local gdebug = require("gears.debug")
--- Timer objects. This type of object is useful when triggering events repeatedly.
-- The timer will emit the "timeout" signal every N seconds, N being the timeout
-- value. Note that a started timer will not be garbage collected. Call `:stop`
-- to enable garbage collection.
-- @tfield number timeout Interval in seconds to emit the timeout signal.
-- Can be any value, including floating point ones (e.g. 1.5 seconds).
-- @tfield boolean started Read-only boolean field indicating if the timer has been
-- started.
-- @table timer
--- When the timer is started.
-- @signal start
--- When the timer is stopped.
-- @signal stop
--- When the timer had a timeout event.
-- @signal timeout
local timer = { mt = {} }
--- Start the timer.
-- @method start
-- @emits start
function timer:start()
if self.data.source_id ~= nil then
gdebug.print_error(traceback("timer already started"))
return
end
self.data.source_id = glib.timeout_add(glib.PRIORITY_DEFAULT, self.data.timeout * 1000, function()
protected_call(self.emit_signal, self, "timeout")
return true
end)
self:emit_signal("start")
end
--- Stop the timer.
--
-- Does nothing if the timer isn't running.
--
-- @method stop
-- @emits stop
function timer:stop()
if self.data.source_id == nil then
return
end
glib.source_remove(self.data.source_id)
self.data.source_id = nil
self:emit_signal("stop")
end
--- Restart the timer.
-- This is equivalent to stopping the timer if it is running and then starting
-- it.
-- @method again
-- @emits start
-- @emits stop
function timer:again()
if self.data.source_id ~= nil then
self:stop()
end
self:start()
end
--- The timer is started.
-- @property started
-- @param boolean
--- The timer timeout value.
-- **Signal:** property::timeout
-- @property timeout
-- @param number
-- @propemits true false
local timer_instance_mt = {
__index = function(self, property)
if property == "timeout" then
return self.data.timeout
elseif property == "started" then
return self.data.source_id ~= nil
end
return timer[property]
end,
__newindex = function(self, property, value)
if property == "timeout" then
self.data.timeout = tonumber(value)
self:emit_signal("property::timeout", value)
end
end
}
--- Create a new timer object.
-- @tparam table args Arguments.
-- @tparam number args.timeout Timeout in seconds (e.g. 1.5).
-- @tparam[opt=false] boolean args.autostart Automatically start the timer.
-- @tparam[opt=false] boolean args.call_now Call the callback at timer creation.
-- @tparam[opt=nil] function args.callback Callback function to connect to the
-- "timeout" signal.
-- @tparam[opt=false] boolean args.single_shot Run only once then stop.
-- @treturn timer
-- @constructorfct gears.timer
function timer.new(args)
args = args or {}
local ret = object()
ret.data = { timeout = 0 } --TODO v5 rename to ._private
setmetatable(ret, timer_instance_mt)
for k, v in pairs(args) do
ret[k] = v
end
if args.autostart then
ret:start()
end
if args.callback then
if args.call_now then
args.callback()
end
ret:connect_signal("timeout", args.callback)
end
if args.single_shot then
ret:connect_signal("timeout", function() ret:stop() end)
end
return ret
end
--- Create a simple timer for calling the `callback` function continuously.
--
-- This is a small wrapper around `gears.timer`, that creates a timer based on
-- `callback`.
-- The timer will run continuously and call `callback` every `timeout` seconds.
-- It is stopped when `callback` returns `false`, when `callback` throws an
-- error or when the `:stop()` method is called on the return value.
--
-- @tparam number timeout Timeout in seconds (e.g. 1.5).
-- @tparam function callback Function to run.
-- @treturn timer The new timer object.
-- @staticfct gears.timer.start_new
-- @see gears.timer.weak_start_new
function timer.start_new(timeout, callback)
local t = timer.new({ timeout = timeout })
t:connect_signal("timeout", function()
local cont = protected_call(callback)
if not cont then
t:stop()
end
end)
t:start()
return t
end
--- Create a simple timer for calling the `callback` function continuously.
--
-- This function is almost identical to `gears.timer.start_new`. The only
-- difference is that this does not prevent the callback function from being
-- garbage collected.
-- In addition to the conditions in `gears.timer.start_new`,
-- this timer will also stop if `callback` was garbage collected since the
-- previous run.
--
-- @tparam number timeout Timeout in seconds (e.g. 1.5).
-- @tparam function callback Function to start.
-- @treturn timer The new timer object.
-- @staticfct gears.timer.weak_start_new
-- @see gears.timer.start_new
function timer.weak_start_new(timeout, callback)
local indirection = setmetatable({}, { __mode = "v" })
indirection.callback = callback
return timer.start_new(timeout, function()
local cb = indirection.callback
if cb then
return cb()
end
end)
end
local delayed_calls = {}
--- Run all pending delayed calls now. This function should best not be used at
-- all, because it means that less batching happens and the delayed calls run
-- prematurely.
-- @staticfct gears.timer.run_delayed_calls_now
function timer.run_delayed_calls_now()
for _, callback in ipairs(delayed_calls) do
protected_call(unpack(callback))
end
delayed_calls = {}
end
--- Call the given function at the end of the current GLib event loop iteration.
-- @tparam function callback The function that should be called
-- @param ... Arguments to the callback function
-- @staticfct gears.timer.delayed_call
function timer.delayed_call(callback, ...)
assert(type(callback) == "function", "callback must be a function, got: " .. type(callback))
table.insert(delayed_calls, { callback, ... })
end
capi.awesome.connect_signal("refresh", timer.run_delayed_calls_now)
function timer.mt.__call(_, ...)
return timer.new(...)
end
--
--- Disconnect from a signal.
-- @tparam string name The name of the signal.
-- @tparam function func The callback that should be disconnected.
-- @method disconnect_signal
-- @baseclass gears.object
--- Emit a signal.
--
-- @tparam string name The name of the signal.
-- @param ... Extra arguments for the callback functions. Each connected
-- function receives the object as first argument and then any extra
-- arguments that are given to emit_signal().
-- @method emit_signal
-- @baseclass gears.object
--- Connect to a signal.
-- @tparam string name The name of the signal.
-- @tparam function func The callback to call when the signal is emitted.
-- @method connect_signal
-- @baseclass gears.object
--- Connect to a signal weakly.
--
-- This allows the callback function to be garbage collected and
-- automatically disconnects the signal when that happens.
--
-- **Warning:**
-- Only use this function if you really, really, really know what you
-- are doing.
-- @tparam string name The name of the signal.
-- @tparam function func The callback to call when the signal is emitted.
-- @method weak_connect_signal
-- @baseclass gears.object
return setmetatable(timer, timer.mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
|
-- Vps Blocker
local http = minetest.request_http_api()
assert(http ~= nil, "You need to add vps_blocker to secure.http_mods")
local kick_message = minetest.settings:get("vps_kick_message") or "You are using a proxy, vpn or other hosting services, please disable them to play on this server."
vps_blocker = {}
local cache = {}
local storage = minetest.get_mod_storage()
--[[
cache of ip == nil not checked yet
== 1 checked allow
== 2 checked deny
]]
local checkers = {}
--[[
vps_blocker.register_check(check):
passed check is a array:
getreq(ip) return req, callback or nil, err for failed
callback func will get the result of the req and is supposed
to return true for allow and false for denying the client
nil, err for failed requests
active = true
If the checker is currently working is true by default
The checker can store any other data inside this table.
]]
function vps_blocker.register_checker(check)
assert(type(check) == "table")
check.active = true
assert(type(check.getreq) == "function")
-- Dummy testing function:
local req, call = check.getreq("0.0.0.0")
assert(type(req) == "table")
assert(type(req.url == "string"))
assert(type(call) == "function")
table.insert(checkers, check)
end
-- Load checkers
dofile(minetest.get_modpath(minetest.get_current_modname()).. "/checker.lua")
-- Add the main ipcheckup function
local function check_ip(name, ip, hash)
-- Loop throught the list of checkers and use one
local checked = false
for _, check in pairs(checkers) do
if check.active then
local req, call = check.getreq(ip)
if req then
local function callback(result)
local pass, err = call(result)
if pass then
cache[hash] = 1
minetest.log("action", "vps_blocker: Passing good-ip-player "..name.." ["..ip.."]")
elseif pass == false then
cache[hash] = 2
minetest.log("action", "vps_blocker: Kicking bad-ip-player "..name.." ["..ip.."]")
else minetest.log("error", "vps_blocker: Callback-Error "..err.." while checking "..name.." ["..ip.."]!")
end
end
http.fetch(req, callback)
checked = true
break
else minetest.log("error", "vps_blocker: Checker failed to create requests for "..name.." ["..ip.."]!")
end
end
end
-- Report error if no working was found
if not checked then
minetest.log("error", "vps_blocker: No working checker found!")
end
end
-- Add a function which handels what do do(check, kick, nth...)
function vps_blocker.handle_player(name, ip)
if not ip or not name then
return
end
local iphash = minetest.sha1(ip)
if not iphash then
return
end
if cache[iphash] == 1 or storage:get_int(name) == 1 then
return
end
if not cache[iphash] then
check_ip(name, ip, iphash)
return
end
if cache[iphash] == 2 then
local player = minetest.get_player_by_name(name)
if player then
-- Kick after a server step, to prevent other on_joinplayer to crash
minetest.after(0, function()
minetest.kick_player(name, kick_message)
end)
else return kick_message
end
end
end
-- Do handle_player on prejoin and normal join
minetest.register_on_prejoinplayer(vps_blocker.handle_player)
minetest.register_on_joinplayer(function(player)
local name = player:get_player_name()
local ip = minetest.get_player_ip(name)
vps_blocker.handle_player(name, ip)
end)
-- Add a command to whitelist players
minetest.register_chatcommand("vps_wl", {
description = "Allow a player to use vps services.",
params = "<add or remove> <name>",
privs = {server=true},
func = function(name, params)
local p = string.split(params, " ")
if p[1] == "add" then
storage:set_int(p[2], 1)
return true, "Added "..p[2].." to the whitelist."
elseif p[1] == "remove" then
storage:set_int(p[2], 0)
return true, "Removed "..p[2].." from the whitelist."
else return false, "Invalid Input"
end
end
})
|
local API_NPC = require(script:GetCustomProperty("API_NPC"))
local API_D = require(script:GetCustomProperty("APIDamage"))
local RANGE = 220.0
local COOLDOWN = 11.0
local SMASH_RANGE = 2000.0
local DAMAGE = 110.0
function GetPriority(npc, taskHistory)
return 1.0
end
function OnTaskStart(npc, threatTable)
local target = API_NPC.GetTarget(npc)
API_NPC.LookAtTargetWithoutPitch(npc, target:GetWorldPosition())
return 3.0
end
function OnTaskEnd(npc, interrupted)
if not interrupted then
for _, player in pairs(Game.FindPlayersInSphere(npc:GetWorldPosition(), SMASH_RANGE, {ignoreDead = true})) do
local offset = player:GetWorldPosition() - npc:GetWorldPosition()
offset.z = 0.0
local dot = offset:GetNormalized() .. (npc:GetWorldRotation() * Vector3.FORWARD)
if dot > 0.707 then -- 90 degree frontal cone
API_D.ApplyDamage(npc, player, DAMAGE, API_D.TAG_AOE)
end
end
end
end
API_NPC.RegisterTaskServer("large_melee_elemental_smash", RANGE, COOLDOWN, GetPriority, OnTaskStart, OnTaskEnd)
|
-- painting - in-game painting for minetest
local items =
{
wood = "default:wood",
stick = "default:stick",
brush_head = "farming:cotton",
canvas_source = "default:paper",
}
if minetest.get_modpath("mcl_core") then
items.wood = "mcl_core:wood"
items.stick = "mcl_core:stick"
items.brush_head = "mcl_mobitems:string"
items.canvas_source = "mcl_core:paper"
elseif minetest.get_modpath("hades_core") then
items.wood = "group:wood"
items.stick = "hades_core:stick"
items.brush_head = "hades_farming:cotton"
items.canvas_source = "hades_core:paper"
if minetest.get_modpath("hades_extrafarming") then
items.brush_head = "hades_extrafarming:cotton"
end
if minetest.get_modpath("hades_clothing") then
items.canvas_source = "hades_clothing:fabric_white"
end
if minetest.get_modpath("hades_animals") then
local hairball = minetest.settings:get("mobs_hairball")
items.brush_head = "mobs:hairball"
end
else
if minetest.get_modpath("clothing") then
items.canvas_source = "clothing:fabric_white"
end
if minetest.get_modpath("mobs_animal") then
local hairball = minetest.settings:get("mobs_hairball")
items.brush_head = "mobs:hairball"
end
end
minetest.register_craft({
output = 'painting:easel 1',
recipe = {
{ '', items.wood, '' },
{ '', items.wood, '' },
{ items.stick,'', items.stick },
}})
minetest.register_craft({
output = 'painting:brush 1',
recipe = {
{ items.brush_head },
{ items.stick },
{ items.stick },
}})
minetest.register_craft({
output = 'painting:canvas_16 1',
recipe = {
{ '', '', '' },
{ '', '', '' },
{ items.canvas_source, '', '' },
}})
minetest.register_craft({
output = 'painting:canvas_32 1',
recipe = {
{ '', '', '' },
{ items.canvas_source, items.canvas_source, '' },
{ items.canvas_source, items.canvas_source, '' },
}})
minetest.register_craft({
output = 'painting:canvas_64 1',
recipe = {
{ items.canvas_source, items.canvas_source, items.canvas_source },
{ items.canvas_source, items.canvas_source, items.canvas_source },
{ items.canvas_source, items.canvas_source, items.canvas_source },
}})
|
if _G.f_debug ~= nil then _G.f_debug.more_info("Preconditions test scripts run.") end
|
map_editor = {
cast = function(player)
map_editor.enter(player)
end,
click = function(player, npc)
player.dialogType = 0
local opts = {}
if player.registry["map_editor"] == 0 then
table.insert(opts, "Edit Mode")
else
table.insert(opts, "Quit Editor")
table.insert(opts, "Save Map")
end
txt = "<b>[Map Editor]\n"
txt = txt .. "MapName: " .. player.mapTitle .. " (Id: " .. player.m .. ")\n"
-- txt = txt.."MapFile: "..getMapFolder(player.m)..""
menu = player:menuString(txt, opts)
if menu == "Edit Mode" then
map_editor.enter(player)
elseif menu == "Quit Editor" then
map_editor.quit(player)
elseif menu == "Save Map" then
confirm = player:menuString(
txt .. "\nAre you sure to save change in map?",
{"Yes", "No"}
)
if confirm == "Yes" then
saveMap(player.m, "../rtkmaps/Accepted/" .. player.mapfile)
player:sendMinitext("Map saved!")
gm = player:getUsers()
for i = 1, #gm do
if gm[i].gmLevel > 0 then
gm[i]:msg(
4,
player.name .. " has made changes to " .. player.mapTitle .. " map (Id: " .. player.m .. ") and saved the map file!",
gm[i].ID
)
gm[i]:msg(
4,
"[SAVED]: " .. player.mapTitle .. " to " .. player.mapfile .. "",
gm[i].ID
)
end
end
end
end
end,
enter = function(player)
local spells = player:getSpells()
local add = {
"editor_exit",
"tile_next",
"tile_prev",
"toggle_pass",
"obj_next",
"obj_prev",
"tile_copy",
"tile_paste",
"obj_copy",
"obj_paste",
"tile_check",
"tile_find",
"obj_check",
"obj_find",
"toggle_pass",
"editor_save",
"toggle_highlight_pass"
}
for i = 1, 255 do
player.registry["spells_" .. i] = 0
end
if #spells > 0 then
for i = 1, #spells do
player.registry["spells_" .. i] = spells[i]
end
end
cspells(player)
for i = 1, #add do
player:addSpell(add[i] .. "")
end
player.registry["map_editor"] = 1
player:sendMinitext("Active Map Editor")
end,
quit = function(player)
cspells(player)
for i = 1, 52 do
if player.registry["spells_" .. i] > 0 then
player:addSpell(player.registry["spells_" .. i] .. "")
end
end
if player:hasDuration("toggle_highlight_pass") then
player:setDuration("toggle_highlight_pass", 0)
end
player.registry["map_editor"] = 0
player:sendMinitext("Quit Map Editor")
end
}
tile = {
option = function(player, type, num)
local m, x, y, num = player.m, player.x, player.y, tonumber(num)
if player.side == 0 then
y = y - 1
end
if player.side == 1 then
x = x + 1
end
if player.side == 2 then
y = y + 1
end
if player.side == 3 then
x = x - 1
end
local tile = getTile(m, x, y)
if type == "copy" then
player.registry["saved_tile"] = tile
player:talkSelf(
0,
"<Saved> Tile : " .. player.registry["saved_tile"] .. ""
)
return
elseif type == "paste" then
setTile(m, x, y, player.registry["saved_tile"])
player:talkSelf(
0,
"<Pasted> Tile : " .. player.registry["saved_tile"] .. ""
)
return
elseif type == "next" then
if tile + 1 <= 47919 then
setTile(m, x, y, tile + 1)
end
player:talkSelf(0, "<Next> Tile : " .. tile)
elseif type == "previous" then
if tile - 1 >= 0 then
setTile(m, x, y, tile - 1)
end
player:talkSelf(0, "<Prev> Tile : " .. tile)
elseif type == "jump" and num ~= nil then
setTile(m, x, y, num)
player:talkSelf(0, "Tile : " .. tile)
elseif type == "check" then
player:talkSelf(0, "Tile : " .. tile)
end
player:selfAnimationXY(player.ID, 235, x, y)
end,
}
object = {
option = function(player, type, num)
local m, x, y, num = player.m, player.x, player.y, tonumber(num)
if player.side == 0 then
y = y - 1
end
if player.side == 1 then
x = x + 1
end
if player.side == 2 then
y = y + 1
end
if player.side == 3 then
x = x - 1
end
local obj = getObject(m, x, y)
if type == "copy" then
player.registry["saved_obj"] = obj
player:talkSelf(
0,
"<Saved> Object : " .. player.registry["saved_obj"] .. ""
)
return
elseif type == "paste" then
setObject(m, x, y, player.registry["saved_obj"])
player:talkSelf(
0,
"<Pasted> Object : " .. player.registry["saved_obj"] .. ""
)
return
elseif type == "next" then
if obj + 1 <= 19542 then
setObject(m, x, y, obj + 1)
end
player:talkSelf(0, "<Next> Object : " .. obj)
elseif type == "previous" then
if obj - 1 >= 0 then
setObject(m, x, y, obj - 1)
end
player:talkSelf(0, "<Prev> Object : " .. obj)
elseif type == "jump" and num ~= nil then
setObject(m, x, y, num)
player:talkSelf(0, "Object: " .. obj)
elseif type == "check" then
player:talkSelf(0, "Object: " .. obj)
end
player:selfAnimationXY(player.ID, 228, x, y)
end,
}
tile_next = {
cast = function(player)
local m, x, y, num = player.m, player.x, player.y, tonumber(num)
if player.side == 0 then
y = y - 1
end
if player.side == 1 then
x = x + 1
end
if player.side == 2 then
y = y + 1
end
if player.side == 3 then
x = x - 1
end
local tile = getTile(m, x, y)
if tile + 1 <= 47919 then
setTile(m, x, y, tile + 1)
end
player:talkSelf(0, "<Next> Tile : " .. tile)
player:selfAnimationXY(player.ID, 235, x, y)
end
}
tile_prev = {
cast = function(player)
local m, x, y, num = player.m, player.x, player.y, tonumber(num)
if player.side == 0 then
y = y - 1
end
if player.side == 1 then
x = x + 1
end
if player.side == 2 then
y = y + 1
end
if player.side == 3 then
x = x - 1
end
local tile = getTile(m, x, y)
if tile - 1 >= 0 then
setTile(m, x, y, tile - 1)
end
player:talkSelf(0, "<Prev> Tile : " .. tile)
player:selfAnimationXY(player.ID, 235, x, y)
end
}
tile_check = {
cast = function(player)
local m, x, y, num = player.m, player.x, player.y, tonumber(num)
if player.side == 0 then
y = y - 1
end
if player.side == 1 then
x = x + 1
end
if player.side == 2 then
y = y + 1
end
if player.side == 3 then
x = x - 1
end
local tile = getTile(m, x, y)
player:talkSelf(0, "Tile : " .. tile)
player:selfAnimationXY(player.ID, 235, x, y)
end
}
tile_copy = {
cast = function(player)
local m, x, y, num = player.m, player.x, player.y, tonumber(num)
if player.side == 0 then
y = y - 1
end
if player.side == 1 then
x = x + 1
end
if player.side == 2 then
y = y + 1
end
if player.side == 3 then
x = x - 1
end
local tile = getTile(m, x, y)
player.registry["saved_tile"] = tile
player:talkSelf(
0,
"<Saved> Tile : " .. player.registry["saved_tile"] .. ""
)
end
}
tile_paste = {
cast = function(player)
local m, x, y, num = player.m, player.x, player.y, tonumber(num)
if player.side == 0 then
y = y - 1
end
if player.side == 1 then
x = x + 1
end
if player.side == 2 then
y = y + 1
end
if player.side == 3 then
x = x - 1
end
local tile = getTile(m, x, y)
setTile(m, x, y, player.registry["saved_tile"])
player:talkSelf(
0,
"<Pasted> Tile : " .. player.registry["saved_tile"] .. ""
)
end
}
tile_find = {
cast = function(player)
local input = tonumber(player.question)
if (not input) then
anim(player, "Number only!")
return
else
if input > 47919 then
anim(player, "Max tile: 47919")
return
else
tile.option(player, "jump", input)
end
end
end
}
obj_next = {
cast = function(player)
object.option(player, "next")
end
}
obj_prev = {
cast = function(player)
object.option(player, "previous")
end
}
obj_check = {
cast = function(player)
object.option(player, "check")
end
}
obj_copy = {
cast = function(player)
object.option(player, "copy")
end
}
obj_paste = {
cast = function(player)
object.option(player, "paste")
end
}
obj_find = {
cast = function(player)
local input = tonumber(player.question)
if (not input) then
anim(player, "Number only!")
return
else
if input > 19542 then
anim(player, "Max Object: 19542")
return
else
object.option(player, "jump", input)
end
end
end
}
set_pass = {
cast = function(player)
local m, x, y = player.m, player.x, player.y
local input = tonumber(player.question)
if player.side == 0 then
y = y - 1
end
if player.side == 1 then
x = x + 1
end
if player.side == 2 then
y = y + 1
end
if player.side == 3 then
x = x - 1
end
if (not input) then
anim(player, "Number only!")
return
else
if input - 1 >= 0 then
setPass(m, x, y, input - 1)
if getPass(m, x, y) == 0 then
id = 235
else
id = 228
end
player:sendFrontAnimation(id)
end
end
end
}
toggle_pass = {
cast = function(player)
local m, x, y = player.m, player.x, player.y
if player.side == 0 then
y = y - 1
end
if player.side == 1 then
x = x + 1
end
if player.side == 2 then
y = y + 1
end
if player.side == 3 then
x = x - 1
end
if getPass(m, x, y) == 0 then
setPass(m, x, y, 1)
player:talk(2, "Pass set: False")
printf = 0
elseif getPass(m, x, y) == 1 then
setPass(m, x, y, 0)
player:talk(2, "Pass set: True")
printf = 0
end
end
}
toggle_highlight_pass = {
cast = function(player)
if player:hasDuration("toggle_highlight_pass") then
player:setDuration("toggle_highlight_pass", 0)
else
player:setDuration("toggle_highlight_pass", 100000000)
end
end,
while_cast = function(player)
local m = player.m
local xmax = player.xmax
local ymax = player.ymax
for x = 0, player.xmax do
for y = 0, player.ymax do
if getPass(m, x, y) == 0 then
player:selfAnimationXY(player.ID, 540, x, y)
elseif getPass(m, x, y) == 1 then
player:selfAnimationXY(player.ID, 542, x, y)
end
end
end
end
}
editor_save = {
cast = function(player)
saveMap(player.m, "../rtkmaps/Accepted/" .. player.mapFile)
player:sendMinitext("Map saved!")
local gm = player:getUsers()
for i = 1, #gm do
if gm[i].gmLevel > 0 then
gm[i]:msg(
4,
player.name .. " has made changes to " .. player.mapTitle .. " map (Id: " .. player.m .. ") and saved the map file!",
gm[i].ID
)
gm[i]:msg(
4,
"[SAVED]: " .. player.mapTitle .. " to " .. player.mapfile .. "",
gm[i].ID
)
end
end
end
}
editor_exit = {
cast = function(player)
map_editor.quit(player)
end
}
|
-- this module defines the types with metatypes that are always common, so do not get errors redefining metatypes
local require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string =
require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string
local ffi = require "ffi"
local bit = require "syscall.bit"
local t, ctypes, pt, s = {}, {}, {}, {}
local types = {t = t, pt = pt, s = s, ctypes = ctypes}
local h = require "syscall.helpers"
local addtype, addtype_var, addtype_fn, addraw2 = h.addtype, h.addtype_var, h.addtype_fn, h.addraw2
local addtype1, addtype2, addptrtype = h.addtype1, h.addtype2, h.addptrtype
local ptt, reviter, mktype, istype, lenfn, lenmt, getfd, newfn
= h.ptt, h.reviter, h.mktype, h.istype, h.lenfn, h.lenmt, h.getfd, h.newfn
local ntohl, ntohl, ntohs, htons, htonl = h.ntohl, h.ntohl, h.ntohs, h.htons, h.htonl
local split, trim, strflag = h.split, h.trim, h.strflag
local align = h.align
local addtypes = {
char = "char",
uchar = "unsigned char",
int = "int",
uint = "unsigned int",
int8 = "int8_t",
uint8 = "uint8_t",
int16 = "int16_t",
uint16 = "uint16_t",
int32 = "int32_t",
uint32 = "uint32_t",
int64 = "int64_t",
uint64 = "uint64_t",
long = "long",
ulong = "unsigned long",
}
for k, v in pairs(addtypes) do addtype(types, k, v) end
local addtypes1 = {
char1 = "char",
uchar1 = "unsigned char",
int1 = "int",
uint1 = "unsigned int",
int16_1 = "int16_t",
uint16_1 = "uint16_t",
int32_1 = "int32_t",
uint32_1 = "uint32_t",
int64_1 = "int64_t",
uint64_1 = "uint64_t",
long1 = "long",
ulong1 = "unsigned long",
}
for k, v in pairs(addtypes1) do addtype1(types, k, v) end
local addtypes2 = {
char2 = "char",
int2 = "int",
uint2 = "unsigned int",
}
for k, v in pairs(addtypes2) do addtype2(types, k, v) end
local ptrtypes = {
uintptr = "uintptr_t",
intptr = "intptr_t",
}
for k, v in pairs(ptrtypes) do addptrtype(types, k, v) end
t.ints = ffi.typeof("int[?]")
t.buffer = ffi.typeof("char[?]") -- TODO rename as chars?
t.string_array = ffi.typeof("const char *[?]")
local mt = {}
mt.iovec = {}
addtype(types, "iovec", "struct iovec", mt.iovec)
mt.iovecs = {
__len = function(io) return io.count end,
__tostring = function(io)
local s = {}
for i = 0, io.count - 1 do
local iovec = io.iov[i]
s[i + 1] = ffi.string(iovec.iov_base, iovec.iov_len)
end
return table.concat(s)
end;
__new = function(tp, is)
if type(is) == 'number' then return ffi.new(tp, is, is) end
local count = #is
local iov = ffi.new(tp, count, count)
local j = 0
for n, i in ipairs(is) do
if type(i) == 'string' then
local buf = t.buffer(#i)
ffi.copy(buf, i, #i)
iov.iov[j].iov_base = buf
iov.iov[j].iov_len = #i
elseif type(i) == 'number' then
iov.iov[j].iov_base = t.buffer(i)
iov.iov[j].iov_len = i
elseif ffi.istype(t.iovec, i) then
ffi.copy(iov[n], i, s.iovec)
elseif type(i) == 'cdata' or type(i) == 'userdata' then -- eg buffer or other structure, userdata if luaffi
iov.iov[j].iov_base = i
iov.iov[j].iov_len = ffi.sizeof(i)
else -- eg table
iov.iov[j] = i
end
j = j + 1
end
return iov
end,
}
addtype_var(types, "iovecs", "struct {int count; struct iovec iov[?];}", mt.iovecs)
-- convert strings to inet addresses and the reverse
local function inet4_ntop(src)
local b = pt.uchar(src)
return b[0] .. "." .. b[1] .. "." .. b[2] .. "." .. b[3]
end
local function inet6_ntop(src)
local a = src.s6_addr
local parts = {256*a[0] + a[1], 256*a[2] + a[3], 256*a[4] + a[5], 256*a[6] + a[7],
256*a[8] + a[9], 256*a[10] + a[11], 256*a[12] + a[13], 256*a[14] + a[15]}
for i = 1, #parts do parts[i] = string.format("%x", parts[i]) end
local start, max = 0, 0
for i = 1, #parts do
if parts[i] == "0" then
local count = 0
for j = i, #parts do
if parts[j] == "0" then count = count + 1 else break end
end
if count > max then max, start = count, i end
end
end
if max > 2 then
parts[start] = ""
if start == 1 or start + max == 9 then parts[start] = ":" end
if start == 1 and start + max == 9 then parts[start] = "::" end
for i = 1, max - 1 do table.remove(parts, start + 1) end
end
return table.concat(parts, ":")
end
local function inet4_pton(src)
local ip4 = split("%.", src)
if #ip4 ~= 4 then error "malformed IP address" end
return htonl(tonumber(ip4[1]) * 0x1000000 + tonumber(ip4[2]) * 0x10000 + tonumber(ip4[3]) * 0x100 + tonumber(ip4[4]))
end
local function hex(str) return tonumber("0x" .. str) end
local function inet6_pton(src, addr)
-- TODO allow form with decimals at end for ipv4 addresses
local ip8 = split(":", src)
if #ip8 > 8 then return nil end
local before, after = src:find("::")
before, after = src:sub(1, before - 1), src:sub(after + 1)
if before then
if #ip8 == 8 then return nil end -- must be some missing
if before == "" then before = "0" end
if after == "" then after = "0" end
src = before .. ":" .. string.rep("0:", 8 - #ip8 + 1) .. after
ip8 = split(":", src)
end
for i = 1, 8 do
addr.s6_addr[i * 2 - 1] = bit.band(hex(ip8[i]), 0xff)
addr.s6_addr[i * 2 - 2] = bit.rshift(hex(ip8[i]), 8)
end
return addr
end
local inaddr = strflag {
ANY = "0.0.0.0",
LOOPBACK = "127.0.0.1",
BROADCAST = "255.255.255.255",
}
local in6addr = strflag {
ANY = "::",
LOOPBACK = "::1",
}
-- given this address and a mask, return a netmask and broadcast as in_addr
local function mask_bcast(address, netmask)
local bcast = t.in_addr()
local nmask = t.in_addr() -- TODO
if netmask > 32 then error("bad netmask " .. netmask) end
if netmask < 32 then nmask.s_addr = htonl(bit.rshift(-1, netmask)) end
bcast.s_addr = bit.bor(tonumber(address.s_addr), nmask.s_addr)
return {address = address, broadcast = bcast, netmask = nmask}
end
mt.in_addr = {
__index = {
get_mask_bcast = function(addr, mask) return mask_bcast(addr, mask) end,
},
newindex = {
addr = function(addr, s)
if ffi.istype(t.in_addr, s) then
addr.s_addr = s.s_addr
elseif type(s) == "string" then
if inaddr[s] then s = inaddr[s] end
addr.s_addr = inet4_pton(s)
else -- number
addr.s_addr = htonl(s)
end
end,
},
__tostring = inet4_ntop,
__new = function(tp, s)
local addr = ffi.new(tp)
if s then addr.addr = s end
return addr
end,
__len = lenfn,
}
addtype(types, "in_addr", "struct in_addr", mt.in_addr)
mt.in6_addr = {
__tostring = inet6_ntop,
__new = function(tp, s)
local addr = ffi.new(tp)
if s then
if in6addr[s] then s = in6addr[s] end
addr = inet6_pton(s, addr)
end
return addr
end,
__len = lenfn,
}
addtype(types, "in6_addr", "struct in6_addr", mt.in6_addr)
-- ip, udp types. Need endian conversions.
local ptchar = ffi.typeof("char *")
local uint16 = ffi.typeof("uint16_t[1]")
local function ip_checksum(buf, size, c, notfinal)
c = c or 0
local b8 = ffi.cast(ptchar, buf)
local i16 = uint16()
for i = 0, size - 1, 2 do
ffi.copy(i16, b8 + i, 2)
c = c + i16[0]
end
if size % 2 == 1 then
i16[0] = 0
ffi.copy(i16, b8[size - 1], 1)
c = c + i16[0]
end
local v = bit.band(c, 0xffff)
if v < 0 then v = v + 0x10000 end -- positive
c = bit.rshift(c, 16) + v
c = c + bit.rshift(c, 16)
if not notfinal then c = bit.bnot(c) end
if c < 0 then c = c + 0x10000 end -- positive
return c
end
mt.iphdr = {
index = {
checksum = function(i) return function(i)
i.check = 0
i.check = ip_checksum(i, s.iphdr)
return i.check
end end,
},
}
addtype(types, "iphdr", "struct iphdr", mt.iphdr)
local udphdr_size = ffi.sizeof("struct udphdr")
-- ugh, naming problems as cannot remove namespace as usual
-- checksum = function(u, ...) return 0 end, -- TODO checksum, needs IP packet info too. as method.
mt.udphdr = {
index = {
src = function(u) return ntohs(u.source) end,
dst = function(u) return ntohs(u.dest) end,
length = function(u) return ntohs(u.len) end,
checksum = function(i) return function(i, ip, body)
local bip = pt.char(ip)
local bup = pt.char(i)
local cs = 0
-- checksum pseudo header
cs = ip_checksum(bip + ffi.offsetof(ip, "saddr"), 4, cs, true)
cs = ip_checksum(bip + ffi.offsetof(ip, "daddr"), 4, cs, true)
local pr = t.char2(0, 17) -- c.IPPROTO.UDP
cs = ip_checksum(pr, 2, cs, true)
cs = ip_checksum(bup + ffi.offsetof(i, "len"), 2, cs, true)
-- checksum udp header
i.check = 0
cs = ip_checksum(i, udphdr_size, cs, true)
-- checksum body
cs = ip_checksum(body, i.length - udphdr_size, cs)
if cs == 0 then cs = 0xffff end
i.check = cs
return cs
end end,
},
newindex = {
src = function(u, v) u.source = htons(v) end,
dst = function(u, v) u.dest = htons(v) end,
length = function(u, v) u.len = htons(v) end,
},
}
addtype(types, "udphdr", "struct udphdr", mt.udphdr)
mt.ethhdr = {
-- TODO
}
addtype(types, "ethhdr", "struct ethhdr", mt.ethhdr)
mt.winsize = {
index = {
row = function(ws) return ws.ws_row end,
col = function(ws) return ws.ws_col end,
xpixel = function(ws) return ws.ws_xpixel end,
ypixel = function(ws) return ws.ws_ypixel end,
},
newindex = {
row = function(ws, v) ws.ws_row = v end,
col = function(ws, v) ws.ws_col = v end,
xpixel = function(ws, v) ws.ws_xpixel = v end,
ypixel = function(ws, v) ws.ws_ypixel = v end,
},
__new = newfn,
}
addtype(types, "winsize", "struct winsize", mt.winsize)
return types
|
-- Project: OiL - ORB in Lua
-- Release: 0.6
-- Title : Server-side LuDO Protocol
-- Authors: Renato Maia <maia@inf.puc-rio.br>
local _G = require "_G"
local select = _G.select
local tonumber = _G.tonumber
local tostring = _G.tostring
local array = require "table"
local unpack = array.unpack
local table = require "loop.table"
local memoize = table.memoize
local oo = require "oil.oo"
local class = oo.class
local Exception = require "oil.Exception" --[[VERBOSE]] local verbose = require "oil.verbose"
local Request = require "oil.protocol.Request"
local Listener = require "oil.protocol.Listener"
local LuDOChannel = require "oil.ludo.Channel"
local ServerRequest = class({}, Request)
function ServerRequest:setreply(...) --[[VERBOSE]] verbose:listen("set reply for request ",self.request_id," to ",self.objectkey,":",self.operation)
local channel = self.channel
channel:trylock("write")
local success, except = channel:sendvalues(self.request_id, ...)
channel:freelock("write")
if not success and except.error ~= "closed" then
return false, except
end
channel.pending = channel.pending-1
if channel.closing and channel.pending == 0 then
LuDOChannel.close(channel)
end
return true
end
local ServerChannel = class({ pending = 0 }, LuDOChannel)
local function makerequest(channel, success, requestid, objkey, operation, ...)
if not success then return nil, requestid end
channel.pending = channel.pending+1
return ServerRequest{
channel = channel,
request_id = requestid,
objectkey = objkey,
operation = operation,
n = select("#", ...),
...,
}
end
function ServerChannel:getrequest(timeout)
local result, except
if self:trylock("read", timeout) then
result, except = makerequest(self, self:receivevalues(timeout))
self:freelock("read")
else
result, except = nil, Exception{ "timeout", error = "timeout" }
end
return result, except
end
function ServerChannel:idle()
return self.pending == 0
end
function ServerChannel:close()
if self.pending > 0 then
self.closing = true
else
LuDOChannel.close(self)
end
return true
end
local ChannelFactory = class()
function ChannelFactory:create(socket)
return ServerChannel{
socket = socket,
context = self,
}
end
return ChannelFactory
|
Locales['fr'] = {
['left_instance'] = 'vous avez quitté l\'instance',
['invite_expired'] = 'invitation expirée',
['press_to_enter'] = 'appuyez sur ~INPUT_CONTEXT~ pour entrer dans l\'instance',
['entered_instance'] = 'vous êtes entré dans l\'instance',
['entered_into'] = '%s est entré dans l\'instance',
['left_out'] = '%s est sorti dans l\'instance',
}
|
local value = false
local t = 0
local dt = 0
local r_curr = 1
local r_prev = 1
function but_cb(dt)
value = not value
if value == false then
led(1023)
else
led(512)
end
end
tmr.alarm(tmr_but, 50, 1, function()
r_curr = gpio.read(io_but)
if r_curr == 0 and r_prev == 1 then
t = tmr.now()
r_prev = r_curr
elseif r_curr == 1 and r_prev == 0 then
dt = tmr.now() - t
r_prev = r_curr
if (dt > 89999) then but_cb(dt) end
else
-- do nothing
end
end)
print("button [ok]")
|
--
-- created with TexturePacker - https://www.codeandweb.com/texturepacker
--
-- $TexturePacker:SmartUpdate:cadcfe307a1eb19417de4d4c0dcda166:1e2a9027e60fc70d48b2e90cb500a164:1784b3470aad1b82bb9f03684bcf642d$
--
-- local sheetInfo = require("mysheet")
-- local myImageSheet = graphics.newImageSheet( "mysheet.png", sheetInfo:getSheet() )
-- local sprite = display.newSprite( myImageSheet , {frames={sheetInfo:getFrameIndex("sprite")}} )
--
local SheetInfo = {}
SheetInfo.sheet =
{
frames = {
{
-- bg-clouds
x=0,
y=1024,
width=1280,
height=480,
},
{
-- bg-separator
x=0,
y=360,
width=1280,
height=268,
},
{
-- cannon
x=240,
y=116,
width=68,
height=132,
},
{
-- continue
x=680,
y=0,
width=644,
height=88,
},
{
-- crown
x=1328,
y=0,
width=160,
height=104,
},
{
-- earth
x=1284,
y=660,
width=360,
height=360,
},
{
-- finger
x=1184,
y=116,
width=200,
height=200,
},
{
-- leaderboard
x=116,
y=116,
width=120,
height=120,
},
{
-- leaf
x=312,
y=116,
width=144,
height=152,
},
{
-- logo-text
x=0,
y=660,
width=1280,
height=344,
},
{
-- meteor
x=804,
y=116,
width=172,
height=184,
},
{
-- ozone
x=460,
y=116,
width=168,
height=168,
},
{
-- play
x=1388,
y=116,
width=240,
height=240,
},
{
-- rate
x=0,
y=116,
width=112,
height=112,
},
{
-- remove-ads
x=1492,
y=0,
width=112,
height=112,
},
{
-- rocket
x=1284,
y=1024,
width=252,
height=496,
},
{
-- satellite1
x=0,
y=0,
width=336,
height=80,
},
{
-- satellite2
x=340,
y=0,
width=336,
height=80,
},
{
-- ship
x=1284,
y=360,
width=188,
height=296,
},
{
-- star
x=632,
y=116,
width=168,
height=168,
},
{
-- ufo
x=980,
y=116,
width=200,
height=196,
},
},
sheetContentWidth = 1644,
sheetContentHeight = 1520
}
SheetInfo.frameIndex =
{
["bg-clouds"] = 1,
["bg-separator"] = 2,
["cannon"] = 3,
["continue"] = 4,
["crown"] = 5,
["earth"] = 6,
["finger"] = 7,
["leaderboard"] = 8,
["leaf"] = 9,
["logo-text"] = 10,
["meteor"] = 11,
["ozone"] = 12,
["play"] = 13,
["rate"] = 14,
["remove-ads"] = 15,
["rocket"] = 16,
["satellite1"] = 17,
["satellite2"] = 18,
["ship"] = 19,
["star"] = 20,
["ufo"] = 21,
}
function SheetInfo:getSheet()
return self.sheet;
end
function SheetInfo:getFrameIndex(name)
return self.frameIndex[name];
end
return SheetInfo
|
-- tl_ops_cookie
-- en : get balance cookie config list
-- zn : 获取路由cookie配置列表
-- @author iamtsm
-- @email 1905333456@qq.com
local cjson = require("cjson");
cjson.encode_empty_table_as_object(false)
local snowflake = require("lib.snowflake");
local cache = require("cache.tl_ops_cache"):new("tl-ops-cookie");
local tl_ops_constant_cookie = require("constant.tl_ops_constant_cookie");
local tl_ops_rt = require("constant.tl_ops_constant_comm").tl_ops_rt;
local tl_ops_utils_func = require("utils.tl_ops_utils_func");
local rule, _ = cache:get(tl_ops_constant_cookie.cache_key.rule);
if not rule or rule == nil then
tl_ops_utils_func:set_ngx_req_return_ok(tl_ops_rt.not_found, "not found rule", _);
return;
end
local list_str, _ = cache:get(tl_ops_constant_cookie.cache_key.list);
if not list_str or list_str == nil then
tl_ops_utils_func:set_ngx_req_return_ok(tl_ops_rt.not_found, "not found list", _);
return;
end
local res_data = {}
res_data[tl_ops_constant_cookie.cache_key.rule] = rule
res_data[tl_ops_constant_cookie.cache_key.list] = cjson.decode(list_str)
tl_ops_utils_func:set_ngx_req_return_ok(tl_ops_rt.ok, "success", res_data); |
test = require 'u-test'
common = require 'common'
function TestMPTransferCpp_Handler()
print("TestMPTransferCpp_Handler")
session1, hr = MultiplayerSessionCreateCpp("00000000-0000-0000-0000-000076029b4d", "MinGameSession", "", 0)
session2, hr = MultiplayerSessionCreateCpp("00000000-0000-0000-0000-000076029b4d", "MinGameSession", "", 1)
MultiplayerSessionJoinCpp(session1)
MultiplayerSessionJoinCpp(session2)
MultiplayerServiceWriteSession(session1)
MultiplayerServiceWriteSession(session2)
end
local sessionsWritten = 0
function OnMultiplayerServiceWriteSession()
sessionsWritten = sessionsWritten + 1;
if sessionsWritten == 2 then
MultiplayerServiceSetTransferHandle(session1, session2)
end
end
function OnMultiplayerServiceSetTransferHandle()
test.stopTest();
end
test.TestMPTransferCpp = function()
common.init(TestMPTransferCpp_Handler)
end |
-- www.pubnub.com - PubNub realtime push service in the cloud.
-- https://github.com/pubnub/pubnub-api/tree/master/lua-corona - lua-Corona Push API
-- PubNub Real Time Push APIs and Notifications Framework
-- Copyright (c) 2010 Stephen Blum
-- http://www.pubnub.com/
-- -----------------------------------
-- PubNub 3.1 Real-time Push Cloud API
-- -----------------------------------
require "Json"
require "crypto"
pcall(require,"BinDecHex")
pubnub = {}
function pubnub.new(init)
local self = init
local subscriptions = {}
-- SSL ENABLED?
if self.ssl then
self.origin = "https://" .. self.origin
else
self.origin = "http://" .. self.origin
end
function self:publish(args)
local callback = args.callback or function() end
if not (args.channel and args.message) then
return callback({ nil, "Missing Channel and/or Message" })
end
local channel = args.channel
local message = Json.Encode(args.message)
local signature = "0"
-- SIGN PUBLISHED MESSAGE?
if self.secret_key then
signature = crypto.hmac( crypto.sha256,self.secret_key, table.concat( {
self.publish_key,
self.subscribe_key,
self.secret_key,
channel,
message
}, "/" ) )
end
-- PUBLISH MESSAGE
self:_request({
callback = function(response)
if not response then
return callback({ nil, "Connection Lost" })
end
callback(response)
end,
request = {
"publish",
self.publish_key,
self.subscribe_key,
signature,
self:_encode(channel),
"0",
self:_encode(message)
}
})
end
function self:subscribe(args)
local channel = args.channel
local callback = callback or args.callback
local errorback = args['errorback'] or function() end
local connectcb = args['connect'] or function() end
local timetoken = 0
if not channel then return print("Missing Channel") end
if not callback then return print("Missing Callback") end
-- NEW CHANNEL?
if not subscriptions[channel] then
subscriptions[channel] = {}
end
-- ENSURE SINGLE CONNECTION
if (subscriptions[channel].connected) then
return print("Already Connected")
end
subscriptions[channel].connected = 1
subscriptions[channel].first = nil
-- SUBSCRIPTION RECURSION
local function substabizel()
-- STOP CONNECTION?
if not subscriptions[channel].connected then return end
-- CONNECT TO PUBNUB SUBSCRIBE SERVERS
self:_request({
callback = function(response)
-- STOP CONNECTION?
if not subscriptions[channel].connected then return end
-- CONNECTED CALLBACK
if not subscriptions[channel].first then
subscriptions[channel].first = true
connectcb()
end
-- PROBLEM?
if not response then
-- ENSURE CONNECTED
return self:time({
callback = function(time)
if not time then
timer.performWithDelay( 1000, substabizel )
return errorback("Lost Network Connection")
end
timer.performWithDelay( 10, substabizel )
end
})
end
timetoken = response[2]
timer.performWithDelay( 1, substabizel )
for i, message in ipairs(response[1]) do
callback(message)
end
end,
request = {
"subscribe",
self.subscribe_key,
self:_encode(channel),
"0",
timetoken
}
})
end
-- BEGIN SUBSCRIPTION (LISTEN FOR MESSAGES)
substabizel()
end
function self:unsubscribe(args)
local channel = args.channel
if not subscriptions[channel] then return nil end
-- DISCONNECT
subscriptions[channel].connected = nil
subscriptions[channel].first = nil
end
function self:history(args)
if not (args.callback and args.channel) then
return print("Missing History Callback and/or Channel")
end
local limit = args.limit
local channel = args.channel
local callback = args.callback
if not limit then limit = 10 end
self:_request({
callback = callback,
request = {
'history',
self.subscribe_key,
self:_encode(channel),
'0',
limit
}
})
end
function self:time(args)
if not args.callback then
return print("Missing Time Callback")
end
self:_request({
request = { "time", "0" },
callback = function(response)
if response then
return args.callback(response[1])
end
args.callback(nil)
end
})
end
function self:_request(args)
-- APPEND PUBNUB CLOUD ORIGIN
table.insert( args.request, 1, self.origin )
local url = table.concat( args.request, "/" )
local params = {}
params["V"] = "3.1"
params["User-Agent"] = "Corona"
network.request( url, "GET", function(event)
if (event.isError) then
return args.callback(nil)
end
status, message = pcall( Json.Decode, event.response )
if status then
return args.callback(message)
else
return args.callback(nil)
end
end, params)
end
function self:_encode(str)
str = string.gsub( str, "([^%w])", function(c)
return string.format( "%%%02X", string.byte(c) )
end )
return str
end
function self:_map( func, array )
local new_array = {}
for i,v in ipairs(array) do
new_array[i] = func(v)
end
return new_array
end
function self:UUID()
local chars = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"}
local uuid = {[9]="-",[14]="-",[15]="4",[19]="-",[24]="-"}
local r, index
for i = 1,36 do
if(uuid[i]==nil)then
-- r = 0 | Math.random()*16;
r = math.random (36)
if(i == 20 and BinDecHex)then
-- (r & 0x3) | 0x8
index = tonumber(Hex2Dec(BMOr(BMAnd(Dec2Hex(r), Dec2Hex(3)), Dec2Hex(8))))
if(index < 1 or index > 36)then
print("WARNING Index-19:",index)
return UUID() -- should never happen - just try again if it does ;-)
end
else
index = r
end
uuid[i] = chars[index]
end
end
return table.concat(uuid)
end
local Hex2Dec, BMOr, BMAnd, Dec2Hex
if(BinDecHex)then
Hex2Dec, BMOr, BMAnd, Dec2Hex = BinDecHex.Hex2Dec, BinDecHex.BMOr, BinDecHex.BMAnd, BinDecHex.Dec2Hex
end
-- RETURN NEW PUBNUB OBJECT
return self
end
|
---------------------------------
--! @file OutPortPushConnector.lua
--! @brief Push型通信OutPortConnector定義
---------------------------------
--[[
Copyright (c) 2017 Nobuhiko Miyamoto
]]
local OutPortPushConnector= {}
--_G["openrtm.OutPortPushConnector"] = OutPortPushConnector
--local oil = require "oil"
local OutPortConnector = require "openrtm.OutPortConnector"
local DataPortStatus = require "openrtm.DataPortStatus"
local BufferStatus = require "openrtm.BufferStatus"
local OutPortProvider = require "openrtm.OutPortProvider"
local OutPortProviderFactory = OutPortProvider.OutPortProviderFactory
local CdrBufferBase = require "openrtm.CdrBufferBase"
local CdrBufferFactory = CdrBufferBase.CdrBufferFactory
local InPortConsumer = require "openrtm.InPortConsumer"
local InPortConsumerFactory = InPortConsumer.InPortConsumerFactory
local PublisherBase = require "openrtm.PublisherBase"
local PublisherFactory = PublisherBase.PublisherFactory
local StringUtil = require "openrtm.StringUtil"
local ConnectorListener = require "openrtm.ConnectorListener"
local ConnectorListenerType = ConnectorListener.ConnectorListenerType
-- Push型通信OutPortConnectorの初期化
-- @param info プロファイル
-- 「buffer」という要素名にバッファの設定を格納
-- @param consumer コンシューマ
-- @param listeners コールバック
-- @param buffer バッファ
-- 指定しない場合はリングバッファを生成する
-- @return Push型通信OutPortConnector
OutPortPushConnector.new = function(info, consumer, listeners, buffer)
--print(consumer, listeners, buffer)
local obj = {}
setmetatable(obj, {__index=OutPortConnector.new(info)})
-- データ書き込み
-- @param data data._dataを書き込み
-- @return リターンコード(パブリッシャのデータ書き込み結果による)
function obj:write(data)
self._rtcout:RTC_TRACE("write()")
local Manager = require "openrtm.Manager"
local cdr_data = Manager:instance():cdrMarshal(data._data, data._type)
--print(#cdr_data)
return self._publisher:write(cdr_data, 0, 0)
end
-- コネクタ切断
-- @return リターンコード
function obj:disconnect()
self._rtcout:RTC_TRACE("disconnect()")
self:onDisconnect()
if self._publisher ~= nil then
self._rtcout:RTC_DEBUG("delete publisher")
local pfactory = PublisherFactory:instance()
pfactory:deleteObject(self._publisher)
end
self._publisher = nil
if self._consumer ~= nil then
self._rtcout:RTC_DEBUG("delete consumer")
local cfactory = InPortConsumerFactory:instance()
cfactory:deleteObject(self._consumer)
end
self._consumer = nil
if self._buffer ~= nil then
self._rtcout:RTC_DEBUG("delete buffer")
local bfactory = CdrBufferFactory:instance()
bfactory:deleteObject(self._buffer)
end
self._buffer = nil
self._rtcout:RTC_TRACE("disconnect() done")
return DataPortStatus.PORT_OK
end
-- アクティブ化
function obj:activate()
self._publisher:activate()
end
-- 非アクティブ化
function obj:deactivate()
self._publisher:activate()
end
-- バッファ取得
-- @return バッファ
function obj:getBuffer()
return self._buffer
end
-- パブリッシャー生成
-- @param profile コネクタプロファイル
-- @return パブリッシャー
function obj:createPublisher(info)
local pub_type = info.properties:getProperty("subscription_type","flush")
pub_type = StringUtil.normalize(pub_type)
return PublisherFactory:instance():createObject(pub_type)
end
-- バッファ作成
-- @param profile コネクタプロファイル
-- @return バッファ
function obj:createBuffer(info)
local buf_type = info.properties:getProperty("buffer_type",
"ring_buffer")
return CdrBufferFactory:instance():createObject(buf_type)
end
-- コネクタ接続時のコールバック呼び出し
function obj:onConnect()
if self._listeners ~= nil and self._profile ~= nil then
self._listeners.connector_[ConnectorListenerType.ON_CONNECT]:notify(self._profile)
end
end
-- コネクタ切断時のコールバック呼び出し
function obj:onDisconnect()
if self._listeners ~= nil and self._profile ~= nil then
self._listeners.connector_[ConnectorListenerType.ON_DISCONNECT]:notify(self._profile)
end
end
-- InPortサーバントオブジェクト設定
-- @param directInPort InPortサーバントオブジェクト
-- @return true:設定成功、false:設定失敗
function obj:setInPort(directInPort)
return false
end
obj._buffer = buffer
obj._consumer = consumer
obj._listeners = listeners
obj._directInPort = nil
obj._inPortListeners = nil
obj._publisher = obj:createPublisher(info)
if obj._buffer == nil then
obj._buffer = obj:createBuffer(info)
end
if obj._publisher == nil or obj._buffer == nil or obj._consumer == nil then
error("")
end
if obj._publisher:init(info.properties) ~= DataPortStatus.PORT_OK then
error("")
end
obj._buffer:init(info.properties:getNode("buffer"))
obj._consumer:init(info.properties)
obj._publisher:setConsumer(obj._consumer)
obj._publisher:setBuffer(obj._buffer)
obj._publisher:setListener(obj._profile, obj._listeners)
obj:onConnect()
return obj
end
return OutPortPushConnector
|
local function registerCommands (_)
SILE.registerCommand("debug", function (options, _)
for k, v in pairs(options) do
SILE.debugFlags[k] = SU.boolean(v, true)
end
end)
SILE.registerCommand("disable-pushback", function (_, _)
SILE.typesetter.pushBack = function() end
end)
end
return {
registerCommands = registerCommands,
documentation = [[
\begin{document}
This package provides two commands: \autodoc:command{\debug}, which turns
on and off SILE’s internal debugging flags (similar to using \code{--debug=...}
on the command line); and \autodoc:command{\disable-pushback} which is used
by SILE’s developers to turn off the typesetter’s pushback routine, because we
don’t really trust it very much.
\end{document}
]]
}
|
--
-- premake5 file to build RecastDemo
-- http://premake.github.io/
--
require "lib"
local action = _ACTION or ""
local outdir = action
WorkSpaceInit "dbproxy"
Project "dbproxy_svr"
IncludeFile {
"../external/",
"../external/protobuf/include/",
"../external/mysql_connector/include/",
"../proto/",
"./cpp_cfg/com/",
}
SrcPath {
"../dbproxy_svr/**", --**递归所有子目录,指定目录可用 "cc/*.cpp" 或者 "cc/**.cpp"
"../proto/**",
"./cpp_cfg/**",
}
files {
"../*.txt",
"../*.lua",
}
Project "proto"
files {
"../proto/*.proto",
}
Project "db_driver"
IncludeFile {
"../external/",
"../external/protobuf/include/",
"../proto/",
}
files {
"../db_driver/src/**",
"../db_driver/include/**",
"../db_driver/*.txt",
}
Project "test_mysql"
IncludeFile {
"../external/",
"../external/protobuf/include/",
"../proto/",
}
files {
"../test/test_mysql/**",
"../test/com/**",
"../test/test_mysql/*.txt",
}
Project "test_leak"
IncludeFile {
"../external/",
"../external/protobuf/include/",
"../proto/",
}
files {
"../test/test_leak/**",
"../test/com/**",
"../test/test_leak/*.txt",
}
|
-- module Data.Semiring
local exports = {}
exports.intAdd = function (x)
return function (y)
return math.floor(x + y)
end
end
exports.intMul = function (x)
return function (y)
return math.floor(x * y)
end
end
exports.numAdd = function (n1)
return function (n2)
return n1 + n2
end
end
exports.numMul = function (n1)
return function (n2)
return n1 * n2
end
end
return exports
|
AddCSLuaFile()
local DbgPrint = GetLogging("MapScript")
local MAPSCRIPT = {}
MAPSCRIPT.PlayersLocked = false
MAPSCRIPT.DefaultLoadout =
{
Weapons = {},
Ammo = {},
Armor = 30,
HEV = false,
}
MAPSCRIPT.EntityFilterByClass =
{
}
MAPSCRIPT.EntityFilterByName =
{
}
MAPSCRIPT.InputFilters =
{
["train_door_2_counter"] = {"Add"},
["razortrain_gate_cop_2"] = {"SetPoliceGoal"},
["cage_playerclip"] = {"Enable"},
["cage_door_counter"] = {"Add"},
["logic_kill_citizens"] = {"Trigger"},
["storage_room_door"] = {"Close", "Lock"},
}
MAPSCRIPT.GlobalStates =
{
["gordon_precriminal"] = GLOBAL_ON,
["gordon_invulnerable"] = GLOBAL_ON,
["super_phys_gun"] = GLOBAL_OFF,
["antlion_allied"] = GLOBAL_OFF,
}
function MAPSCRIPT:Init()
end
function MAPSCRIPT:PostInit()
if SERVER then
local function fixCitizen(ent)
ent:SetKeyValue("spawnflags", "16794640")
end
ents.WaitForEntityByName("citizen_queue_start_1", fixCitizen)
ents.WaitForEntityByName("citizen_queue_start_2", fixCitizen)
ents.WaitForEntityByName("citizen_queue_start_3", fixCitizen)
ents.RemoveByClass("trigger_once", Vector(-4614.97, -678.03, 16))
ents.RemoveByClass("trigger_once", Vector(-4614.97, -806.03, 16))
ents.RemoveByClass("trigger_once", Vector(-5022.15, -787.48, 0))
ents.RemoveByClass("trigger_once", Vector(-4370.18, -922.25, 20.5))
ents.WaitForEntityByName("customs_schedule_walk_to_exit", function(ent)
ent:SetKeyValue("m_flRadius", "110")
ent:SetKeyValue("m_iszEntity", "citizen_queue_start*")
end)
ents.WaitForEntityByName("customs_schedule_walk_to_train", function(ent)
ent:SetKeyValue("m_flRadius", "110")
ent:SetKeyValue("m_iszEntity", "citizen_queue_start*")
end)
local queueTrigger = ents.Create("trigger_once")
queueTrigger:SetupTrigger(Vector(-4322.127441, -922.505859, -27.981224), Angle(0,0,0), Vector(-20, -20, 0), Vector(20, 20, 90))
queueTrigger:SetKeyValue("teamwait", 0)
queueTrigger:Fire("AddOutput", "OnTrigger customs_relay_send_to_train,Trigger,,0.0,-1")
queueTrigger:Fire("AddOutput", "OnTrigger lambda_queue_pclip,Kill,,0.0,-1")
local pclipBrush = ents.Create("func_brush")
pclipBrush:SetPos(Vector(-4330.575195, -922.814453, 35))
pclipBrush:SetName("lambda_queue_pclip")
pclipBrush:SetModel("*58")
pclipBrush:SetKeyValue("disabled", "1")
pclipBrush:SetKeyValue("rendermode", "10")
pclipBrush:SetKeyValue("excludednpc", "npc_citizen")
pclipBrush:Spawn()
ents.WaitForEntityByName("trigger_watchclock", function(ent)
ent:Fire("AddOutput", "OnTrigger customs_queue_timer,Enable,,0.1,-1")
end)
ents.WaitForEntityByName("customs_queue_timer", function(ent)
ent:Fire("AddOutput", "OnTimer lambda_queue_pclip,Enable,,0.0,-1")
ent:Fire("AddOutput", "OnTimer lambda_queue_pclip,Disable,,2.5,-1")
end)
-- Remove all default spawnpoints.
ents.RemoveByClass("info_player_start")
-- Annoying stuff.
ents.RemoveByName("cage_playerclip")
--ents.RemoveByName("barney_room_blocker")
ents.RemoveByName("barney_room_blocker_2")
ents.RemoveByName("barney_hallway_clip")
ents.RemoveByName("logic_kill_citizens")
-- Fix spawn position
ents.WaitForEntityByName("teleport_to_start", function(ent)
ent:SetPos(Vector(-14576, -13924, -1290))
end)
ents.WaitForEntityByName("breakfall_crates", function(ent)
-- Don't break so easily.
ent:SetKeyValue("physdamagescale", "1")
ent:SetHealth(1000)
end)
-- Fix point_viewcontrol, affect all players.
for k,v in pairs(ents.FindByClass("point_viewcontrol")) do
v:SetKeyValue("spawnflags", "128") -- SF_CAMERA_PLAYER_MULTIPLAYER_ALL
end
-- Make the cop go outside the hallway so other players can still pass by.
local mark_cop_security_room_leave = ents.FindFirstByName("mark_cop_security_room_leave");
mark_cop_security_room_leave:SetPos(Vector(-4304, -464, -16))
GAMEMODE:WaitForInput("logic_start_train", "Trigger", function()
DbgPrint("Assigning new spawnpoint")
local intro_train_2 = ents.FindFirstByName("intro_train_2")
local pos = intro_train_2:LocalToWorld(Vector(-233.685928, 1.246165, 47.031250))
local cp = GAMEMODE:SetPlayerCheckpoint({ Pos = pos, Ang = Angle(0, 0, 0)})
cp:SetParent(intro_train_2)
-- Disable them earlier, the black fadeout is gone.
for k,v in pairs(ents.FindByClass("point_viewcontrol")) do
v:Fire("Disable")
end
end)
-- Block players from escaping control gate.
local cage_playerclip = ents.Create("func_brush")
cage_playerclip:SetPos(Vector(-4226.9350585938, -417.03271484375,-31.96875))
cage_playerclip:SetModel("*68")
cage_playerclip:SetKeyValue("spawnflags", "2")
cage_playerclip:Spawn()
-- Setup the door to not close anymore once we entered the trigger.
GAMEMODE:WaitForInput("razor_train_gate_2", "Close", function()
DbgPrint("Preventing barney_door_1 to close")
GAMEMODE:FilterEntityInput("barney_door_1", "Close")
end)
-- Move barney to a better position when he wants players to go inside.
ents.WaitForEntityByName("mark_barney_03", function(ent)
ent:SetPos(Vector(-3466.066650, -486.869598, -31.968750))
end)
-- Create a trigger once all players are inside we setup a new spawnpoint and close the door.
ents.RemoveByClass("trigger_once", Vector(-3442, -316, 8)) -- We will take over.
local barney_room_trigger = ents.Create("trigger_once")
barney_room_trigger:SetupTrigger(Vector(-3450, -255, 20), Angle(0,0,0), Vector(-150, -130, -50), Vector(150, 150, 50))
barney_room_trigger:SetKeyValue("teamwait", 1)
barney_room_trigger.OnTrigger = function(_, activator)
GAMEMODE:SetPlayerCheckpoint({ Pos = Vector(-3549, -347, -31), Ang = Angle(0, 0, 0)}, activator)
ents.WaitForEntityByName("security_intro_02", function(ent) ent:Fire("Start") end)
ents.WaitForEntityByName("barney_room_blocker", function(ent) ent:Fire("Enable") end)
end
ents.WaitForEntityByName("barney_door_2", function(ent)
ent:SetKeyValue("opendir", "2")
end)
-- Use a better spot for barney
local mark_barneyroom_comblock_4 = ents.FindFirstByName("mark_barneyroom_comblock_4")
mark_barneyroom_comblock_4:SetPos(Vector(-3588, 3, -31))
end
end
return MAPSCRIPT
|
local copas = require "copas"
local now = require("socket").gettime
local Semaphore = require "copas.semaphore"
local Queue = require "copas.queue"
--local log = require("logging").defaultLogger()
local _M = {}
--- waits for a task to complete. Does exponential backoff while waiting.
-- @tparam function check should return true on completion
-- @tparam[opt=30] number timeout time out in seconds
-- @tparam[opt=0.010] number first wait in seconds
-- @tparam[opt=1] number max wait in seconds (each try doubles the wait until it hits this value)
-- @return true if finished, or nil+timeout
function _M.wait_for(check, timeout, init, max)
assert(type(check) == "function", "expected 'check' to be a function")
timeout = timeout or 30
assert(timeout > 0, "expected 'timeout' to be greater than 0")
init = init or 0.010
assert(init > 0, "expected 'init' to be greater than 0")
max = max or 1
assert(max > 0, "expected 'max' to be greater than 0")
local end_time = now() + max
while now() > end_time do
if check() then
return true
end
copas.sleep(init)
init = math.min(max, init * 2)
end
return nil, "timeout"
end
--- schedules an async task using `copas.addthread` and waits for completion.
-- On a timeout the task will be removed from the Copas scheduler, and the cancel
-- function will be called. The latter one is required when doing socket
-- operations, you must close the socket in case it is in the receiving/sending
-- queues
-- @tparam function task function with the task to execute
-- @tparam[opt=30] number timeout timeout in seconds for the task
-- @tparam[opt] function cancel function to cancel the task
function _M.wait_for_task(task, timeout, cancel)
local sema = Semaphore.new(1)
local coro = copas.addthread(function()
task()
sema:give()
end)
local ok, err = sema:wait(1, timeout or 30)
if not ok then
-- timeout
copas.removethread(coro)
if cancel then cancel() end
return ok, err
end
return true
end
--- (un)subscribes to/from a list of topics. Will not return until done/failed.
-- @param mqtt the mqtt device
-- @param list table with topics (topics can be in the key or value, as long as only one of them is a string)
-- @param unsub boolean: subcribe or unsubscribe
-- @return true or nil+err
function _M.subscribe_topics(mqtt, list, unsub, timeout)
assert(timeout, "timeout is a required parameter")
if not next(list) then
return true -- empty list, so nothing to do
end
local s = Semaphore.new(10^9)
local q = Queue.new()
local h = unsub and mqtt.unsubscribe or mqtt.subscribe
for key, value in pairs(list) do
local topic = type(key) == "string" and key or
type(value) == "string" and value or
error("either key or value must be a topic string)")
q:push(function()
return h(mqtt ,{
topic = topic,
qos = 1,
callback = function(...)
s:give(1)
--log:info("%ssubscribing %s topic '%s' succeeded", (unsub and "un" or ""),(unsub and "from" or "to"),topic)
end
})
end)
end
local items_to_finish = q:get_size()
q:add_worker(function(item)
if not item() then
s:destroy()
q:destroy()
end
end)
local ok, err = s:take(items_to_finish, timeout)
s:destroy()
q:destroy()
return ok, err
end
--- Publishes a list of topics. Will not return until done/failed.
-- Note: the defaults are; `retain = true`,
-- `qos = 1`, and `callback` can't be set (will always be overridden).
-- @param mqtt the mqtt device
-- @param list table payloads indexed by topics (payload can also be a table with
-- options see mqtt_client:publish)
-- @return true or nil+err
function _M.publish_topics(mqtt, list, timeout)
assert(timeout, "timeout is a required parameter")
if not next(list) then
return true -- empty list, so nothing to do
end
local s = Semaphore.new(10^9)
local q = Queue.new()
local cb = function(...)
s:give(1)
end
for topic, payload in pairs(list) do
if type(payload) == "string" then
payload = { payload = payload }
end
payload.topic = topic
payload.callback = cb
-- set alternative defaults
if payload.retain == nil then payload.retain = true end
if payload.qos == nil then payload.qos = 1 end
q:push(function()
return mqtt:publish(payload)
end)
end
local items_to_finish = q:get_size()
q:add_worker(function(item)
if not item() then
s:destroy()
q:destroy()
end
end)
local ok, err = s:take(items_to_finish, timeout)
s:destroy()
q:destroy()
return ok, err
end
return _M
|
--- Quickstart script.
-- Creates a quickstart world for testing mods.
-- <p>This module requires the use of stdlib's @{Event} module for player creation interactions.
-- <p>config settings should be a created in a table retured from `config-quickstart.lua`
-- @script quickstart
-- @usage
-- if DEBUG then
-- require('stdlib/utils/scripts/quickstart')
-- end
local Core = require("stdlib/core")
require("stdlib/event/event")
local Area = require("stdlib/area/area")
if not remote.interfaces["quickstart-script"] then
local qs_interface = {}
qs_interface.registered_to = function()
if game then
game.print(script.mod_name)
end
return script.mod_name
end
qs_interface.creative_mode_quickstart_registerd_to = qs_interface.registered_to
remote.add_interface("quickstart-script", qs_interface)
else
-- quickstart-script has already been registered, lets not clobber things
return
end
local QS = require("stdlib/config/config").new(Core.prequire("config-quickstart") or {})
local quickstart = {}
function quickstart.on_player_created(event)
if #game.players == 1 and event.player_index == 1 then
local player = game.players[event.player_index]
local surface = player.surface
local force = player.force
local area = Area(QS.get("area_box", {{-100, -100}, {100, 100}})):shrink_to_surface_size(surface)
player.force.chart(surface, area)
if QS.get("cheat_mode", false) then
player.cheat_mode = true
player.force.research_all_technologies()
if player.character then
player.character_running_speed_modifier = 2
player.character_reach_distance_bonus = 100
player.character_build_distance_bonus = 100
end
end
if QS.get("clear_items", false) then
player.clear_items_inside()
end
local simple_stacks = QS.get("stacks", {})
local qb_stacks = QS.get("quickbar", {})
local inv = player.get_inventory(player.character and defines.inventory.player_main or defines.inventory.god_main)
local qb = player.get_inventory(player.character and defines.inventory.player_quickbar or defines.inventory.god_quickbar)
if inv then
for _, item in pairs(simple_stacks) do
if game.item_prototypes[item] then
inv.insert(item)
end
end
for _, item in pairs(qb_stacks) do
if game.item_prototypes[item] then
qb.insert(item)
end
end
end
local power_armor = QS.get("power_armor", "fake")
if player.character and game.item_prototypes[power_armor] then
--Put on power armor, install equipment
player.get_inventory(defines.inventory.player_armor).insert(power_armor)
local grid = player.character.grid
if grid then
for _, eq in pairs(QS.get("equipment", {"fusion-reactor-equipment"})) do
if game.equipment_prototypes[eq] then
grid.put {name = eq}
end
end
end
end
if remote.interfaces["RSO"] then
if QS.get("disable_rso_starting", false) and remote.interfaces["RSO"]["disableStartingArea"] then
remote.call("RSO", "disableStartingArea")
end
if QS.get("disable_rso_chunk", false) and remote.interfaces["RSO"]["disableChunkHandler"] then
remote.call("RSO", "disableChunkHandler")
end
end
if QS.get("destroy_everything", false) then
for _, entity in pairs(surface.find_entities(area)) do
-- destroying cliffs can invalidate other cliffs so .valid is needed here
if entity.valid and entity.name ~= "player" then
entity.destroy()
end
end
end
if QS.get("floor_tile", false) then
local tiles = {}
local floor_tile = QS.get("floor_tile")
local floor_tile_alt = QS.get("floor_tile_alt", floor_tile)
for x, y in Area.spiral_iterate(area) do
if y % 2 == 0 then
if x % 2 == 0 then
tiles[#tiles + 1] = {name = floor_tile, position = {x = x, y = y}}
else
tiles[#tiles + 1] = {name = floor_tile_alt, position = {x = x, y = y}}
end
else
if x % 2 ~= 0 then
tiles[#tiles + 1] = {name = floor_tile, position = {x = x, y = y}}
else
tiles[#tiles + 1] = {name = floor_tile_alt, position = {x = x, y = y}}
end
end
end
surface.set_tiles(tiles, true)
surface.destroy_decoratives(area)
end
if QS.get("ore_patches", true) then
--Top left
for x, y in Area.iterate({{-37.5, -27.5}, {-33.5, -3.5}}) do
surface.create_entity {name = "coal", position = {x, y}, amount = 2500}
end
--Top Right
for x, y in Area.iterate({{33.5, -27.5}, {37.5, -3.5}}) do
surface.create_entity {name = "iron-ore", position = {x, y}, amount = 2500}
end
--Bottom Right
for x, y in Area.iterate({{33.5, 3.5}, {37.5, 27.5}}) do
surface.create_entity {name = "copper-ore", position = {x, y}, amount = 2500}
end
--Bottom Left
for x, y in Area.iterate({{-37.5, 3.5}, {-33.5, 27.5}}) do
surface.create_entity {name = "stone", position = {x, y}, amount = 2500}
end
surface.create_entity {name = "crude-oil", position = {-35.5, 1.5}, amount = 32000}
surface.create_entity {name = "crude-oil", position = {-35.5, -1.5}, amount = 32000}
surface.create_entity {name = "crude-oil", position = {35.5, 1.5}, amount = 32000}
surface.create_entity {name = "crude-oil", position = {35.5, -1.5}, amount = 32000}
local water_tiles = {}
for x = 27.5, -27.5, -1 do
for y = 45.5, 50.5, 1 do
if x < -4 or x > 4 then
water_tiles[#water_tiles + 1] = {
name = "water",
position = {x = x, y = y}
}
end
end
end
surface.set_tiles(water_tiles, false)
surface.create_entity {name = "offshore-pump", position = {4.5, 44.5}, force = force, direction = defines.direction.south}
surface.create_entity {name = "offshore-pump", position = {-4.5, 44.5}, force = force, direction = defines.direction.south}
surface.create_entity {name = "offshore-pump", position = {27.5, 44.5}, force = force, direction = defines.direction.south}
surface.create_entity {name = "offshore-pump", position = {-27.5, 44.5}, force = force, direction = defines.direction.south}
end
if QS.get("chunk_bounds", false) then
if game.entity_prototypes["debug-chunk-marker"] then
local a = surface.create_entity {name = "debug-chunk-marker", position = {0, 0}}
a.graphics_variation = 1
for i = 1, 31, 2 do
a = surface.create_entity {name = "debug-chunk-marker", position = {i, 0}}
a.graphics_variation = 2
a = surface.create_entity {name = "debug-chunk-marker", position = {-i, 0}}
a.graphics_variation = 2
a = surface.create_entity {name = "debug-chunk-marker", position = {0, i}}
a.graphics_variation = 3
a = surface.create_entity {name = "debug-chunk-marker", position = {0, -i}}
a.graphics_variation = 3
end
end
local tiles = {}
for i = .5, 32.5, 1 do
tiles[#tiles + 1] = {name = "hazard-concrete-left", position = {i, 32.5}}
tiles[#tiles + 1] = {name = "hazard-concrete-right", position = {-i, 32.5}}
tiles[#tiles + 1] = {name = "hazard-concrete-left", position = {i, -32.5}}
tiles[#tiles + 1] = {name = "hazard-concrete-right", position = {-i, -32.5}}
tiles[#tiles + 1] = {name = "hazard-concrete-left", position = {32.5, i}}
tiles[#tiles + 1] = {name = "hazard-concrete-left", position = {32.5, -i}}
tiles[#tiles + 1] = {name = "hazard-concrete-right", position = {-32.5, i}}
tiles[#tiles + 1] = {name = "hazard-concrete-right", position = {-32.5, -i}}
end
surface.set_tiles(tiles)
end
if QS.get("starter_tracks", false) then
-- Create proxy blueprint from string, read in the entities and remove it.
local bp = surface.create_entity {name = "item-on-ground", position = {0, 0}, force = force, stack = "blueprint"}
bp.stack.import_stack(quickstart.trackstring)
local tracks = bp.stack.get_blueprint_entities()
bp.destroy()
for _, track in pairs(tracks) do
local pos = {track.position.x + 1, track.position.y + 1}
local ent = surface.create_entity {name = track.name, position = pos, direction = track.direction, force = force}
if ent.name == "train-stop" then
if ent.position.x > 0 and ent.position.y > 0 then
ent.backer_name = "#SOUTH"
elseif ent.position.x < 0 and ent.position.y > 0 then
ent.backer_name = "#WEST"
elseif ent.position.x > 0 and ent.position.y < 0 then
ent.backer_name = "#EAST"
else
ent.backer_name = "#NORTH"
end
end
end
if QS.get("make_train", false) then
local loco = surface.create_entity {name = "locomotive", position = {20, 39}, orientation = 0.25, direction = 2, force = force}
loco.orientation = .25
loco.get_fuel_inventory().insert({name = "rocket-fuel", count = 30})
local cwag = surface.create_entity {name = "cargo-wagon", position = {13, 39}, orientation = 0.25, direction = 2, force = force}
cwag.orientation = .25
local fwag = surface.create_entity {name = "fluid-wagon", position = {7, 39}, orientation = 0.25, direction = 2, force = force}
fwag.orientation = .25
local awag = surface.create_entity {name = "artillery-wagon", position = {0, 39}, orientation = 0.25, direction = 2, force = force}
awag.orientation = .25
local train = loco and loco.train
if train then
local records = {}
for _, name in pairs({"#SOUTH", "#EAST", "#NORTH", "#WEST"}) do
records[#records + 1] = {station = name, wait_conditions = {{type = "time", ticks = 0, compare_type = "and"}}}
end
records[1].wait_conditions = {{type = "full", compare_type = "and"}}
train.schedule = {current = 1, records = records}
train.manual_mode = false
end
end
end
if QS.get("center_map_tag", false) then
local function create_center_map_tag()
local tag = {
position = {0, 0},
text = "Center",
icon = {type = "virtual", name = "signal-0"},
last_user = player
}
if force.add_chart_tag(surface, tag) then
Event.remove(defines.events.on_chunk_generated, create_center_map_tag)
end
end
--Not completely MP Safe
Event.register(defines.events.on_chunk_generated, create_center_map_tag)
end
if QS.get("setup_power", false) then
if game.entity_prototypes["debug-energy-interface"] then
local es = surface.create_entity {name = "debug-energy-interface", position = {0, 0}, force = force}
es.destructible = false
script.raise_event(defines.events.on_built_entity, {created_entity = es, player_index = player.index})
end
if game.entity_prototypes["debug-substation"] then
local sb = surface.create_entity {name = "debug-substation", position = {0, 0}, force = force}
sb.destructible = false
script.raise_event(defines.events.on_built_entity, {created_entity = sb, player_index = player.index})
end
end
if QS.get("setup_creative_mode", false) and game.active_mods["creative-mode"] then
local radar = surface.create_entity {name = "creative-mode_super-radar", position = {3.5, -34.5}, force = force}
script.raise_event(defines.events.on_built_entity, {created_entity = radar, player_index = player.index})
local rb = surface.create_entity {name = "creative-mode_super-roboport", position = {-4, -35}, force = force}
script.raise_event(defines.events.on_built_entity, {created_entity = rb, player_index = player.index})
end
end
end
Event.register(defines.events.on_player_created, quickstart.on_player_created)
quickstart.trackstring =
[[
0eNqdmt1u2kAUhF+l2muIvLveP677BL2tqgoSK7VEDAITNYry7rUDRYWMy0zuAOHPZ33m7O7Z8atZrQ/Ndtd2vVm8mvZ+0+3N4vur2beP3XI9/ta/bBuzMG3fP
JmZ6ZZP47fdsl2bt5lpu4fmt1nYtx8z03R927fN8fr3Ly8/u8PTqtkNf7i4cn6iz8x2sx+u2XTjjQbO3KW7MDMvw6fa3oXhBg/trrk//sO9zT5w3ZnbD+Buvu8
3W4SNJ6i7REaA9Gfk/WH33DzM38f6ken9kenLbWZ9Zu7HOB9/9VNUl0+RVrcHH3hq5KmRp9Y8NfFUx1MzT614aqGpVsiWrXiskC5reayQL+t4rJAw63mskDHLF
5iSMb7AlITxBabkSygwgUoXmJIsur6ESB1dXcJDdXRtCfl3dGUJUnV0XSll5eiyUuYAR5eVMmE5uqyU2dXRZaUsBY4uK2XZcnxdCdnydGEp2wFPV5aydfGO27u
Nd0dbN4+Y/IrlT6H6eIlNCEuXlq8x1SJqYDev5QT1BDSSTzWdmYjCL1D1SfQuQxBdPD7/l1O4nsSXvy3J2JxcPq4a7fUrfaARBVhbeaCYwzVJN4Lx+qhqCKrlU
WFO0ANyEBTlgDDnEwKvIEgXOOYUOSALKyVUakATHKsHBMUYnBwQ5uiitlCMQRb1BEcXtYViDLKoJzi6qC0UY5BFPcHRRQ21GGVNY4wuaajEKCsaY3RBQx1GWc8
Y84k5GnL0KRpiZDFDCUZVypgiCxmOKak6xhRZxjDfSVUxpsgihrWQVA1jiixhOE8kVcGYIgsYT6JJVfAERpYwXmSyquEJjCxivAhnVcUTGFnGeJOSVR1PYGQh4
01cVpU8gZGljDe5WZXyBEafjaEGizwdY4zlfK36eJAzdEg329Li5BFCWRevjhBjatIRHH3AIycM3TciycLGHW5RhT2BSdoRjLdE7rJ0AnONDAhZ1GMtX9+m2qr
S3FOfbh+V2cpKx3rXTGzGOfH87Xr4HlK9avT6zARbq04vhw2q1ctho+r1ctikmr0cNqtuL4ctqttLYRUTWUiZYiILKVNMZCFlgoksZEzwkJWEBdHt5ahRdHs5a
tLcXg6aNbeXgxbN7aWgvIUs5J+3kAWp8hayUlaChyykSvCQlVwF0e3lqFF0ezlqEt1ejppFt5ejFtHtpaiChyxky3NN0ilQ7u0kx3UlYy9yDLRcW4JxfBXy/WX
JxT/vVs7Merlq1sNvX5vV4fHLt4G+H359bnb742U52VKnmOqhIfwDr9+U4w==
]]
return quickstart
|
function getRun(i, param)
local i = i
local param = param
return function ()
--print("test");
--[[if i == 1 then
i = 0
print "aqui"
print(io.read())
end]]
--luajava.bindClass("java.lang.String")
print("teste2 "..i);
--luajava.bindClass("java.lang.Thread"):sleep(100)
luajava.newInstance("java.lang.String", "lalala");
--print("fim thread");
print(gcinfo());
print(param:toString());
end
end
for i=0,100 do
f = luajava.createProxy("java.lang.Runnable",{run=getRun(i, luajava.newInstance("java.lang.String", "str param"))});
--print(f:toString())
t = luajava.newInstance("java.lang.Thread", f);
print(t:toString())
t:start()
--t:run()
--t:join()
end
for i=0,5000 do
--luajava.bindClass("java.lang.String")
end
print("fim main");
--luajava.bindClass("java.lang.Thread"):sleep(100)
|
fx_version 'adamant'
game 'gta5'
ui_page 'html/index.html'
files {
'html/index.html',
'html/sounds/*.ogg'
}
client_scripts {
'cl_sound.lua',
}
server_scripts {
'@utils/server/players.lua',
'sv_sound.lua',
} |
-- Inofficial Tezos Extension for MoneyMoney
-- Fetches Tezos quantity for address via https://tzkt.io/ API
-- Fetches Tezos price in EUR via cryptocompare API
-- Returns cryptoassets as securities
--
-- Username: Tezos Adresses comma seperated
-- Password: anything
-- MIT License
-- Copyright (c) 2021 Mate Steinforth
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
WebBanking{
version = 0.1,
description = "Include your Tezos as cryptoportfolio in MoneyMoney by providing a Tezos Address.",
services= { "Tezos" }
}
local xtzAddresses
local connection = Connection()
local currency = "EUR" -- fixme: make dynamik if MM enables input field
function SupportsBank (protocol, bankCode)
return protocol == ProtocolWebBanking and bankCode == "Tezos"
end
function InitializeSession (protocol, bankCode, username, username2, password, username3)
xtzAddresses = username:gsub("%s+", "")
end
function ListAccounts (knownAccounts)
local account = {
name = "Tezos",
accountNumber = "Crypto Asset Tezos",
currency = currency,
portfolio = true,
type = "AccountTypePortfolio"
}
return {account}
end
function RefreshAccount (account, since)
local s = {}
prices = requestXTZPrice()
for address in string.gmatch(xtzAddresses, '([^,]+)') do
XtzQuantity = requestXtzBalance(address)
FXtzQuantity = convertBalanceToXtz(XtzQuantity)
s[#s+1] = {
name = address,
currency = nil,
market = "cryptocompare",
quantity = FXtzQuantity,
price = prices["EUR"],
}
end
return {securities = s}
end
function EndSession ()
end
-- Querry Functions
function requestXTZPrice()
content = connection:request("GET", cryptocompareRequestUrl(), {})
json = JSON(content)
return json:dictionary()
end
function requestXtzBalance(ethAddress)
content = connection:request("GET", etherscanRequestUrl(ethAddress), {})
return content
end
-- Helper Functions
function convertBalanceToXtz(xtz)
return xtz / 1000000
end
function cryptocompareRequestUrl()
return "https://min-api.cryptocompare.com/data/price?fsym=XTZ&tsyms=EUR,USD"
end
function etherscanRequestUrl(ethAddress)
apiRoot = "https://api.tzkt.io/v1/accounts/"
balance = ethAddress .. "/balance"
return apiRoot .. balance
end
|
local function oscillate(self)
local phDiff = self.freq / self.data:getSampleRate() * math.pi
for i = 0, self.data:getSampleCount() - 1 do
local v = math.sin(self.ph)
self.data:setSample(i, v)
self.ph = self.ph + phDiff
end
end
local function play(self)
love.audio.play(self.source)
self.playing = true
end
local function stop(self)
self.source:stop()
self.playing = false
end
local function proc(self)
if self.playing and not self.source:isPlaying() then
self:oscillate()
self:play()
end
end
local function new()
local s = {}
s.data = love.sound.newSoundData(1024, 44100, 16, 1)
s.source = love.audio.newSource(s.data)
s.ph = 0
s.freq = 440
s.playing = false
s.oscillate = oscillate
s.proc = proc
s.play = play
s:oscillate()
return s
end
return {
new = new,
}
|
local CATEGORY_NAME = "Discord"
function ulx.mute(calling_ply, target_plys, duration, should_unmute)
if (should_unmute) then
for i=1, #target_plys do
hook.Run("UnmutePlayer", target_plys[ i ])
end
ulx.fancyLogAdmin( calling_ply, "#A unmuted #T", target_plys )
else
for i=1, #target_plys do
hook.Run("MutePlayer", target_plys[ i ], duration)
end
ulx.fancyLogAdmin( calling_ply, "#A muted #T for #i seconds", target_plys, duration )
end
end
local mute = ulx.command(CATEGORY_NAME, "ulx mute", ulx.mute, "!mute")
mute:addParam{ type=ULib.cmds.PlayersArg }
mute:addParam{ type=ULib.cmds.NumArg, min=0, max=60, default=5, hint="duration, 0 is round end", ULib.cmds.optional, ULib.cmds.round }
mute:addParam{ type=ULib.cmds.BoolArg, invisible=true }
mute:setOpposite( "ulx unmute", {_, _, _, true}, "!unmute" )
mute:defaultAccess(ULib.ACCESS_ADMIN)
mute:help("Mute and Unmute the player in Discord")
|
DebuffMe = DebuffMe or {}
local DebuffMe = DebuffMe
DebuffMe.DebuffList = {
[1] = "None",
[2] = zo_strformat(SI_ABILITY_NAME, GetAbilityName(38541)), --Taunt
[3] = zo_strformat(SI_ABILITY_NAME, GetAbilityName(17906)), --Crusher
[4] = zo_strformat(SI_ABILITY_NAME, GetAbilityName(75753)), --Alkosh
[5] = zo_strformat(SI_ABILITY_NAME, GetAbilityName(31104)), --EngFlames
[6] = zo_strformat(SI_ABILITY_NAME, GetAbilityName(62988)), --OffBalance
[7] = zo_strformat(SI_ABILITY_NAME, GetAbilityName(81519)), --Minor Vulnerability
[8] = zo_strformat(SI_ABILITY_NAME, GetAbilityName(62504)), --Minor Maim
[9] = zo_strformat(SI_ABILITY_NAME, GetAbilityName(39100)), --Minor MagSteal
[10] = zo_strformat(SI_ABILITY_NAME, GetAbilityName(88575)), --Minor LifeSteal
[11] = zo_strformat(SI_ABILITY_NAME, GetAbilityName(17945)), --Weakening
[12] = zo_strformat(SI_ABILITY_NAME, GetAbilityName(64144)), --Minor Fracture
[13] = zo_strformat(SI_ABILITY_NAME, GetAbilityName(68588)), --Minor Breach
[14] = zo_strformat(SI_ABILITY_NAME, GetAbilityName(62484)), --Major Fracture
[15] = zo_strformat(SI_ABILITY_NAME, GetAbilityName(62485)), --Major Breach
[16] = zo_strformat(SI_ABILITY_NAME, GetAbilityName(122397)), --Major Vulnerability
[17] = zo_strformat(SI_ABILITY_NAME, GetAbilityName(34384)), --Morag Tong
[18] = zo_strformat(SI_ABILITY_NAME, GetAbilityName(34734)), --Surprise Attack
}
--52788 Taunt immunity
--134599 OffBalance immunity
--68359 Minor Vulne (not IA)
--68368 Mino Maim (not W+S)
--80020 Minor Lifesteal
--41958 Green Altar
--41967 Red Altar
DebuffMe.TransitionTable = {
[1] = 0,
[2] = 38541, --Taunt
[3] = 17906, --Crusher
[4] = 75753, --Alkosh
[5] = 31104, --EngFlames
[6] = 62988, --OffBalance
[7] = 81519, --Minor Vulnerability
[8] = 62504, --Minor Maim
[9] = 39100, --Minor MagSteal
[10] = 88575, --Minor LifeSteal
[11] = 17945, --Weakening
[12] = 64144, --Minor Fracture
[13] = 68588, --Minor Breach
[14] = 62484, --Major Fracture
[15] = 62485, --Major Breach
[16] = 122397, --Major Vulnerability
[17] = 34384, --Morag Tong
[18] = 34734, --Surprise Attack
}
DebuffMe.CustomAbilityNameWithID = {
[38541] = GetAbilityName(38541), --Taunt
[52788] = GetAbilityName(52788), --Taunt Immunity
[17906] = GetAbilityName(17906), --Crusher
[75753] = GetAbilityName(75753), --Alkosh
[31104] = GetAbilityName(31104), --EngFlames
[62988] = GetAbilityName(62988), --OffBalance
[134599] = GetAbilityName(134599), --OffBalance Immunity
[81519] = GetAbilityName(81519), --Minor Vulnerability
[68359] = GetAbilityName(68359), --Minor Vulne (not IA)
[68368] = GetAbilityName(62504), --Minor Maim
[39100] = GetAbilityName(39100), --Minor MagSteal
[88575] = GetAbilityName(88575), --Minor LifeSteal
[17945] = GetAbilityName(17945), --Weakening
[64144] = GetAbilityName(64144), --Minor Fracture
[68588] = GetAbilityName(68588), --Minor Breach
[62484] = GetAbilityName(62484), --Major Fracture
[62485] = GetAbilityName(62485), --Major Breach
[122397] = GetAbilityName(122397), --Major Vulnerability
[34384] = GetAbilityName(34384), --Morag Tong
[34734] = GetAbilityName(34734), --Surprise Attack
}
DebuffMe.Abbreviation = {
[1] = "",
[2] = "TN", --Taunt
[3] = "CR", --Crusher
[4] = "AL", --Alkosh
[5] = "EF", --EngFlames
[6] = "OB", --OffBalance
[7] = "IA", --Minor Vulnerability
[8] = "mM", --Minor Maim
[9] = "mS", --Minor MagSteal
[10] = "mL", --Minor LifeSteal
[11] = "WK", --Weakening
[12] = "mF", --Minor Fracture
[13] = "mB", --Minor Breach
[14] = "MF", --Major Fracture
[15] = "MB", --Major Breach
[16] = "MV", --Major Vulnerability
[17] = "MT", --Morag Tong
[18] = "SA", --Surprise Attack
} |
--[[Author: Pizzalol
Date: 26.09.2015.
Creates a dummy at the target location that acts as the Chronosphere]]
function Chronosphere( keys )
-- Variables
local caster = keys.caster
local ability = keys.ability
local target_point = keys.target_points[1]
-- Special Variables
local duration = ability:GetLevelSpecialValueFor("duration", (ability:GetLevel() - 1))
local vision_radius = ability:GetLevelSpecialValueFor("vision_radius", (ability:GetLevel() - 1))
-- Dummy
local dummy_modifier = keys.dummy_aura
local dummy = CreateUnitByName("npc_dummy_unit", target_point, false, caster, caster, caster:GetTeam())
dummy:AddNewModifier(caster, nil, "modifier_phased", {})
ability:ApplyDataDrivenModifier(caster, dummy, dummy_modifier, {duration = duration})
-- Vision
AddFOWViewer(caster:GetTeamNumber(), target_point, vision_radius, duration, false)
-- Timer to remove the dummy
-- Timers:CreateTimer(duration, function() dummy:RemoveSelf() end)
dummy:AddNewModifier(caster, nil, "modifier_kill", { duration = duration } )
end
--[[Author: Pizzalol
Date: 26.09.2015.
Checks if the target is a unit owned by the player that cast the Chronosphere
If it is then it applies the no collision and extra movementspeed modifier
otherwise it applies the stun modifier]]
function ChronosphereAura( keys )
local caster = keys.caster
local target = keys.target
local ability = keys.ability
local ability_level = ability:GetLevel() - 1
-- Ability variables
local aura_modifier = keys.aura_modifier
local ignore_void = ability:GetLevelSpecialValueFor("ignore_void", ability_level)
local duration = ability:GetLevelSpecialValueFor("aura_interval", ability_level)
-- Variable for deciding if Chronosphere should affect Faceless Void
if ignore_void == 0 then ignore_void = false
else ignore_void = true end
-- Check if it is a caster controlled unit or not
-- Caster controlled units get the phasing and movement speed modifier
--if (caster:GetPlayerOwner() == target:GetPlayerOwner()) or (target:GetName() == "npc_dota_hero_faceless_void" and ignore_void) then
-- target:AddNewModifier(caster, ability, "modifier_chronosphere_speed_lua", {duration = duration})
--else
-- Everyone else gets immobilized and stunned
target:InterruptMotionControllers(false)
ability:ApplyDataDrivenModifier(caster, target, aura_modifier, {duration = duration})
end |
-- Calculate probabilities from meps with area and time averaging
--
local MISS = missingf
local mask = matrixf(33, 33, 1, MISS)
mask:Fill(1)
function produceProbabilities(sourceparam, targetparam, op, limit)
local datas = {}
local producer = configuration:GetSourceProducer(0)
local ensemble_size = tonumber(radon:GetProducerMetaData(producer, "ensemble size"))
logger:Info("Producing area probabilities for " .. sourceparam:GetName())
local ens = lagged_ensemble(sourceparam, "MEPS_LAGGED_ENSEMBLE")
ens:SetMaximumMissingForecasts(ensemble_size)
local curtime = forecast_time(current_time:GetOriginDateTime(), current_time:GetValidDateTime())
for j=0,3 do -- Look for the past 3 hours
ens:Fetch(configuration, curtime, current_level)
local actual_size = ens:Size()
for i=0,actual_size-1 do
local data = ens:GetForecast(i)
if data then
local reduced = nil
if op == ">" then
reduced = ProbLimitGt2D(data:GetData(), mask, limit):GetValues()
elseif op == "==" then
reduced = ProbLimitEq2D(data:GetData(), mask, limit):GetValues()
end
mvals = 0
for k,v in pairs(reduced) do
if v == v then
reduced[k] = math.ceil(v)
end
end
datas[#datas+1] = reduced
end
end
curtime:GetValidDateTime():Adjust(HPTimeResolution.kHourResolution, -1)
end
logger:Info(string.format("Read %d grids", #datas))
if #datas == 0 then
return
end
local prob = {}
for i=1,#datas[1] do
prob[i] = MISS
local tmp = 0
local cnt = 0
for j=1,#datas do
local v = datas[j][i]
if v == v then
tmp = tmp + datas[j][i]
cnt = cnt + 1
end
end
prob[i] = tmp / cnt
end
proctype = nil
if op == ">" then
proctype = processing_type(HPProcessingType.kProbabilityGreaterThan, limit, kHPMissingValue)
elseif op == "==" then
proctype = processing_type(HPProcessingType.kProbabilityEq, limit, kHPMissingValue)
end
targetparam:SetProcessingType(proctype)
if sourceparam:GetName() == "FFG-MS" then
targetparam:SetAggregation(aggregation(HPAggregationType.kMaximum, configuration:GetForecastStep()))
elseif sourceparam:GetName() == "RRR-KGM2" then
targetparam:SetAggregation(aggregation(HPAggregationType.kAccumulation, configuration:GetForecastStep()))
end
result:SetForecastType(forecast_type(HPForecastType.kStatisticalProcessing))
result:SetParam(targetparam)
result:SetValues(prob)
luatool:WriteToFile(result)
end
local sourceparam = configuration:GetValue("source_param")
local targetparam = configuration:GetValue("target_param")
local op = configuration:GetValue("comparison_op")
local limit = tonumber(configuration:GetValue("limit"))
if sourceparam == "" or targetparam == "" or op == "" or limit == nil then
logger:Error("Source or target param or limit not specified")
return
end
logger:Info(string.format("Source: %s Target: %s Operator: %s Limit: %d", sourceparam, targetparam, op, limit))
produceProbabilities(param(sourceparam), param(targetparam), op, limit)
|
CodexDB["meta-tbc"]={
["chests"]={
[-300405]="_",
[-300404]="_",
[-300403]="_",
[-300402]="_",
[-300401]="_",
[-300400]="_",
[-187072]=0,
[-186750]=0,
[-186748]=0,
[-186744]=0,
[-186741]=0,
[-186740]=0,
[-186739]=0,
[-186736]=0,
[-186734]=0,
[-186302]=0,
[-186263]=0,
[-185169]=0,
[-185168]=0,
[-185032]=0,
[-184941]=0,
[-184939]=0,
[-184937]=0,
[-184935]=0,
[-184933]=0,
[-184930]=0,
[-184622]=0,
[-184621]=0,
[-184620]=0,
[-184619]=0,
[-184504]=0,
[-182258]=0,
[-182069]=0,
[-181804]=0,
[-181802]=0,
[-181800]=0,
[-181798]=0,
[-181671]=0,
[-181366]=0,
[-181074]="_",
[-161513]=0,
[-153473]=0,
[-153472]=0,
[-153471]=0,
[-153470]=0,
[-19021]=0,
[-13873]=0,
[-3743]=0,
[-3719]=0,
[-3707]=0,
[-3706]=0,
[-3705]=0,
[-3695]=0,
[-3694]=0,
[-3693]=0,
[-3691]=0,
[-3690]=0,
[-3662]=0,
[-3659]=0,
[-3658]=0,
[-2847]=0,
[-2846]=0,
[-2845]=0,
},
["flight"]={
[353]="A",
[1233]="AH",
[1574]="A",
[1575]="A",
[16189]="H",
[16192]="H",
[16587]="H",
[16822]="A",
[17554]="A",
[17555]="A",
[18785]="A",
[18788]="A",
[18789]="A",
[18791]="H",
[18807]="H",
[18808]="H",
[18809]="A",
[18930]="AH",
[18931]="AH",
[18937]="A",
[18938]="AH",
[18939]="A",
[18940]="AH",
[18942]="H",
[18953]="H",
[19317]="H",
[19558]="H",
[19581]="AH",
[19583]="AH",
[20234]="A",
[20515]="AH",
[20762]="H",
[21107]="A",
[21766]="AH",
[22216]="AH",
[22455]="H",
[22485]="A",
[22931]="AH",
[22935]="A",
[23612]="AH",
[24366]="A",
[24851]="AH",
[26560]="AH",
},
["herbs"]={
[-185881]=350,
[-183046]=235,
[-183045]=315,
[-183044]=300,
[-183043]=325,
[-181281]=375,
[-181280]=365,
[-181279]=350,
[-181278]=340,
[-181277]=325,
[-181276]=335,
[-181275]=325,
[-181271]=315,
[-181270]=300,
[-181166]=0,
},
["mines"]={
[-185877]=350,
[-185557]=375,
[-181570]=350,
[-181569]=350,
[-181557]=375,
[-181556]=325,
[-181555]=300,
[-181249]=65,
[-181248]=0,
[-73939]=125,
},
["rares"]={
[601]=19,
[639]="_",
[723]="_",
[1037]=24,
[1140]=31,
[1361]=28,
[1720]=25,
[1849]=58,
[1885]=58,
[2753]=38,
[3651]=16,
[3652]=17,
[3672]=17,
[3718]=20,
[3792]=31,
[3831]=23,
[3872]=21,
[4030]=29,
[4339]=41,
[4380]=38,
[4425]=27,
[4438]=25,
[4842]=27,
[5346]=48,
[5348]=62,
[5367]=52,
[5789]=10,
[5790]=9,
[5793]=10,
[5794]=10,
[5795]=9,
[5796]=8,
[5797]=22,
[5800]=22,
[5912]=19,
[6228]=28,
[6489]=32,
[6490]=32,
[6646]=53,
[6647]=51,
[6650]=50,
[6652]=51,
[7895]=35,
[8206]=51,
[8208]=43,
[8923]=56,
[9025]="_",
[9041]=54,
[9042]=53,
[9417]=60,
[9736]="_",
[10203]=62,
[10236]=33,
[10237]=35,
[10238]=35,
[10239]=38,
[10584]="_",
[10808]="_",
[10810]=59,
[10818]=43,
[10820]=45,
[10899]=61,
[11383]=57,
[11467]=59,
[11580]=41,
[11676]=1,
[12037]=31,
[12237]=46,
[13977]=60,
[14016]=1,
[14018]=1,
[14019]=1,
[14229]=35,
[14230]=37,
[14233]=37,
[14235]=40,
[14236]=37,
[14237]=38,
[14266]=19,
[14268]=15,
[14341]=53,
[14346]=52,
[14425]=24,
[14506]=62,
[14697]=71,
[15796]=59,
[16179]=73,
[16180]=73,
[16181]=73,
[16184]=60,
[16854]=11,
[16855]=10,
[17075]=63,
[17144]=65,
[18241]=30,
[18677]=61,
[18678]=62,
[18679]=62,
[18680]=63,
[18681]=63,
[18682]=63,
[18683]=68,
[18684]=66,
[18685]=64,
[18686]=64,
[18689]=65,
[18690]=68,
[18692]=68,
[18693]=68,
[18694]=68,
[18695]=69,
[18696]=68,
[18697]=69,
[18698]=68,
[18699]=68,
[20932]=70,
[22060]=18,
[22062]=18,
[22625]=70,
[22631]=1,
[22636]=1,
[22637]=1,
[22642]=1,
},
}
|
local unpack = unpack
local Logo_GUI = {
{type = "texture", texture = "Interface\\AddOns\\Nerdpack-Kleei-2.0\\media\\assassin.blp", width = 160, height = 160, offset = 125, y = -60, align = "center"},
}
local GUI = {
unpack(Logo_GUI),
{type = "header", size = 16, text = "Keybinds", align = "center"},
{type = "text", text = "|c0000FA9A Just hold the Key|r", align = "center"},
{type = "text", text = "|c0087CEFA Choose Keybind:", align = "center"},
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "dropdown", text = "Cheap Shot, Kidney Shot:|c0000FA9A", key = "list1", width = 100, list = {
{key = "1", text = "Shift Keybind"},
{key = "2", text = "Control Keybind"},
{key = "3", text = "Alt Keybind"},
{key = "none", text = "Disable"},
}, default = "1" },
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "dropdown", text = "Blind:|c0000FA9A target behind you or out of melee", key = "list2", width = 100, list = {
{key = "4", text = "Shift Keybind"},
{key = "5", text = "Control Keybind"},
{key = "6", text = "Alt Keybind"},
{key = "none", text = "Disable"},
}, default = "6" },
{type = "text", text = "", align = "center"}, --------------------------------------
--{type = "combo", default = "9", key = "list3", list = keybind_list_3, width = 100},
--{type = "text", text = "Use Shadowstep:|c0000FA9A on target"},
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "ruler"}, {type = "ruler"},
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "text", text = "", align = "center"}, --------------------------------------
{type = 'header', size = 16, text = 'PVP', align = 'center'},
{type = "checkbox", text = "Stun:|c0000FA9A auto stun PVP Target [Kidney Shot].|r", align = "left", key = "stun", default = true},
{type = "checkbox", text = "Sap:|c0000FA9A auto [Sap] PVP Target.", align = "left", key = "sap_key", default = true},
--{type = 'checkbox', text = "Vanish:|c0000FA9A target PVP not stuned and [Kidney Shot] is on CD", align = 'left', key = 'van_no_stun', default = false},
--{type = 'checkbox', text = "Blind:|c0000FA9A target PVP not stuned and [Vanish] is on CD", align = 'left', key = 'blind_no_van', default = false},
{type = 'checkbox', text = "Gladiator's Medallion , Every Man for Himself:", align = 'left', key = 'medal', default = true},
{type = 'text', text = "|c0000FA9A Remove stun/fear/disorient/charm.|r"},
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "ruler"}, {type = "ruler"},
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "header", size = 16, text = "Survival", align = "center"},
{type = "checkspin", text = "Use Vanish:|c0000FA9A PVP", key = "van_pvp", check = true, spin = 15, width = 150, step = 5, max = 95, min = 1},
{type = "checkspin", text = "Use Vanish:|c0000FA9A PVE", key = "van_pve", check = false, spin = 15, width = 150, step = 5, max = 95, min = 1},
{type = "checkspin", text = "Use Crimson Vial:", key = "cv", check = true, spin = 70, width = 150, step = 5, max = 95, min = 1},
{type = "checkspin", text = "Use Evasion:", key = "eva", check = true, spin = 65, width = 150, step = 5, max = 95, min = 1},
{type = "checkspin", text = "Use Health Stone:", key = "hs", check = true, spin = 60, width = 150, step = 5, max = 95, min = 1},
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "ruler"}, {type = "ruler"},
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "header", size = 16, text = "Cooldowns Toggle:", align = 'center'},
{type = "checkbox", text = "Vendetta:", key = "vendeta_key", default = true},
{type = "checkbox", text = "Marked for Death:", key = "mfd_key", default = true},
{type = "checkbox", text = "Thistle Tea:|c0000FA9A when energy < 40 and target boss or PVP enemy", key = "tea_key", default = true},
{type = 'checkbox', text = "Arcane Torrent:|c0000FA9A Blood Elf Racial, when less 30 energy", key = "blood_elf_racial_key", default = true},
{type = "checkbox", text = "Blood Fury:|c0000FA9A ORC Racial", key = "bloodfury_key", default = true},
{type = "checkbox", text = "Berserking:|c0000FA9A Troll Racial", key = "berserking_key", default = true},
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "ruler"}, {type = "ruler"},
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "header", size = 16, text = "Other", align = "center"},
--{type = "checkbox", text = "Auto Targeting:|c0000FA9A when you have no target or target is dead", key = "auto_target_key", default = true},
{type = "checkbox", text = "Auto Stealth:|c0000FA9A when you have enemy target", key = "stealth_key", default = true},
{type = "checkbox", text = "Use Tricks of the Trade:|c0000FA9A in dungeon on tank", key = "tott", default = true},
{type = "checkbox", text = "Pick Pocket:|c0000FA9A when in Range", key = "pocket_key", default = false},
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "dropdown", text = "Lethal Poisons:|c0000FA9A <= 10 min.", key = "poisons_list", width = 100, list = {
{key = "22", text = "Deadly Poison"},
{key = "23", text = "Wound Poison"},
{key = "none", text = "Disable"},
}, default = "22" },
{type = "checkbox", text = "Crippling Poison:|c0000FA9A", key = "crippling_key", default = true},
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "ruler"}, {type = "ruler"},
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "text", text = "", align = "center"}, --------------------------------------
{type = 'header', size = 16, text = "Trinkets", align = 'center'},
{type = 'text', text = '|c0000FA9A Use Trinkets if Cooldown Toggle is enable|r', align = 'center'},
{type = 'checkbox', text = 'Trinket #1', key = 'trk1', default = false},
{type = 'checkbox', text = 'Trinket #2', key = 'trk2', default = false},
{type = 'text', text = '|c0000FA9A Enable only trinkets that are usable, otherwise it will loop the rotation !|r'},
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "ruler"}, {type = "ruler"},
{type = "text", text = "", align = "center"}, --------------------------------------
{type = "text", text = "", align = "center"}, --------------------------------------
}
local exeOnLoad = function()
print("|c0000FA9A ----------------------------------------------------------------------|r")
print("|c0000FA9A --- |r|cffffff00ROGUE - Assassination|r|c00FF0000 for Advanced Unlocker|r")
--[[print('|c0000FA9A ------------------------PVP-------------------------------------------|r')
print('|c0000FA9A --- |rRecommended Talents: 1/1 - 2/3 - 3/3 - 4/3 - 5/2 - 6/3 - 7/1')
print('|c0000FA9A')]]
print('|c0000FA9A ------------------------PVE-------------------------------------------|r')
print('|c0000FA9A --- |rRecommended Talents: 1/1 - 2/2 - 3/1 - 4/1 - 5/3 - 6/2 - 7/1')
print('|c0000FA9A ----------------------------------------------------------------------|r')
print('|c0000FA9A ----------------------Still descovering BFA-------------------------|r')
print("|c0000FA9A")
print("|c0000FA9A Please Setup Rotation Settings first before using it|r")
print("|c0000FA9A If you like my work you can always support me|r|c00FF0000 https://www.paypal.me/thekleei|r")
NeP.Interface:AddToggle({key = "rupture_key", icon = "Interface\\Icons\\ability_rogue_rupture", name = "Rupture", text = "Include Rupture in rotation."})
end
local GarroteAoE = {
{"%pause", "player.energy <= 45", "player"},
{"Garrote", "inRange.spell", "enemies"},
}
local Garrote = {
{"%pause", "player.energy <= 45", "player"},
{"Garrote", "inRange.spell", "target"},
}
local pvp = {
{"!Every Man for Himself", "UI(medal) & state(stun) & !buff(Stealth) & !buff(Vanish)", "player"},
{"!Gladiator's Medallion", "UI(medal) & !buff(Stealth) & !buff(Vanish) & target.player & target.canAttack & {player.state(stun) || player.state(fear) || player.state(disorient) || player.state(charm)}", "player"},
{"Fan of Knives", "canAttack & distance <= 10 & buff(Stealth).any", "enemies"},
{"Fan of Knives", "canAttack & distance <= 10 & buff(Prowl).any", "enemies"},
}
--[[local pvp_1v1 = {
{"!Every Man for Himself", "UI(medal) & state(stun) & !buff(Stealth) & !buff(Vanish)", "player"},
{"!Gladiator's Medallion", "UI(medal) & !buff(Stealth) & !buff(Vanish) & target.player & {player.state(stun) & player.spell(Every Man for Himself)cooldown > 0 & player.race = Human || player.state(stun) & !player.race = Human || player.state(fear) || player.state(disorient) || player.state(charm)}", "player"},
{"Kidney Shot", "inRange.spell & !player.buff(Stealth) & !player.buff(Vanish) & player.combopoints >= 3 & UI(stun) & target.debuff(Cheap Shot).duration <= 0.5", "target"},
{"Vanish", "!player.buff(Stealth) & !player.buff(Cloak of Shadows) & !target.debuff(Sap) & UI(van_no_stun) & !target.state(stun) & !target.state(disorient) & !player.lastcast(Kidney Shot) & player.spell(Kidney Shot).cooldown >= gcd & !player.buff(Evasion) & {target.class(Rogue) & player.spell(Blind).cooldown >= gcd || !target.class(Rogue)}"}, --test & targettarget.is(player)
{"Blind", "inRange.spell & !player.buff(Stealth) & !player.buff(Vanish) & !player.buff(Cloak of Shadows) & !target.debuff(Sap) & !target.debuff(Blind) & UI(blind_no_van) & !target.state(stun) & !target.state(disorient) & !player.lastcast(Kidney Shot) & !player.lastcast(Vanish) & player.spell(Kidney Shot).cooldown >= gcd & !target.immune(disorient) & !player.buff(Evasion)", "target"},-- & targettarget.is(player)
}]]
local Keybinds = {
{"Cheap Shot", "inRange.spell & canAttack & infront & !immune_stun & {player.buff(Stealth) || player.buff(Subterfuge)} & {keybind(alt) & UI(list1)==3 || keybind(shift) & UI(list1)==1 || keybind(control) & UI(list1)==2 || UI(stun) & target.player & !player.buff(Vanish) & !target.state(stun)}", "target"},
{"Kidney Shot", "inRange.spell & canAttack & infront & !IsStealthed & !immune_stun & !state(disarm) & !player.lastcast(Cheap Shot) & player.combopoints >= 3 & {keybind(alt) & UI(list1)==3 || keybind(shift) & UI(list1)==1 || keybind(control) & UI(list1)==2 || UI(stun) & target.player & !player.buff(Vanish) & !target.state(stun)}", "target"},
{"Sap", "inRange.spell & canAttack & infront & UI(sap_key) & !player.buff(Vanish) & !immune_stun & !state(stun) & !state(disorient) & !state(incapacitate) & !combat & player", "target"},
{"Blind", "inRange.spell & canAttack & !immune_stun & !player.buff(Vanish) & {IsStealthed || !IsStealthed & {target.behind || target.distance >= 7}} & {target.buff(Touch of Karma) || keybind(alt) & UI(list2)==6 || keybind(shift) & UI(list2)==4 || keybind(control) & UI(list2)==5}", "target"},
}
local PreCombat = {
--Leveling
{"Sinister Strike", "inRange.spell & {player.level < 8 || !keybind(alt) & !keybind(shift) & !keybind(control) & player.level >= 8 & player.level <= 11}", "target"},
--End Leveling
{"Pick Pocket", "inRange.spell & UI(pocket_key) & !isdummy & !target.player & !player.moving & player.buff(Stealth) & !player.lastcast(Pick Pocket) & creatureType(Humanoid)", "target"},
{"Garrote", "inRange.spell", "target"},
}
local Poisons = {
{"!/stopcasting", "UI(poisons_list)==22 & casting(Deadly Poison) & buff(Deadly Poison).duration > 600", "player"},
{"Deadly Poison", "UI(poisons_list)==22 & !casting(Deadly Poison) & buff(Deadly Poison).duration <= 600", "player"},
{"!/stopcasting", "UI(poisons_list)==23 & casting(Wound Poison) & buff(Wound Poison).duration > 600", "player"},
{"Wound Poison", "UI(poisons_list)==23 & !casting(Wound Poison) & buff(Wound Poison).duration <= 600", "player"},
{"!/stopcasting", "UI(crippling_key) & casting(Crippling Poison) & buff(Crippling Poison).duration > 600", "player"},
{"Crippling Poison", "UI(crippling_key) & !casting(Crippling Poison) & buff(Crippling Poison).duration <= 600", "player"},
}
local Survival ={
--{"Blind", "inRange.spell & !IsStealthed & player.area(10).enemies < 2 & targettarget(player) & target.buff(Touch of Karma).any", "target"}, -- || many more target CD's
{"Vanish", "!player.buff(Stealth) & target.canAttack & target.alive & target.player & health < target.health & health <= UI(van_pvp_spin) & UI(van_pvp_check)", "player"},
{"Vanish", "!player.buff(Stealth) & target.canAttack & target.alive & !target.player & !pvp.area & health < target.health & health <= UI(van_pve_spin) & UI(van_pve_check)", "player"},
{"Crimson Vial", "!target.isdummy & health <= UI(cv_spin) & UI(cv_check)", "player"},
{"Evasion", "health <= UI(eva_spin) & UI(eva_check) & !IsStealthed & incdmg.phys(5) >= health.max*0.02 & target.canAttack & target.alive", "player"},
{"#5512", "item(5512).count >= 1 & player.health <= UI(hs_spin) & UI(hs_check)", "player"}, --Health Stone
}
local Interrupts = {
{"!Kick", "interruptAt(60) & inRange.spell & alive & canAttack & infront", "target"},
}
local Cooldowns = {
{"&Vendetta", "inRange(Mutilate).spell & UI(vendeta_key) & canAttack & infront & debuff(Garrote) & debuff(Rupture)", "target"},
{"#7676", "UI(tea_key) & target.inRange(Garrote).spell & target.canAttack & item(7676).count > 0 & energy < 40 & {target.boss || target.player}", "player"},
{"&Marked for Death", "inRange(Mutilate).spell & UI(mfd_key) & talent(3,3) & player.combopoints < 2", "target"},
{"Arcane Torrent", "UI(blood_elf_racial_key) & target.inRange(Mutilate).spell & energy <= 30", "player"},
{"Blood Fury", "UI(bloodfury_key) & target.inRange(Mutilate).spell & target.canAttack", "player"},
{"Berserking", "UI(berserking_key) & target.inRange(Mutilate).spell & target.canAttack", "player"},
{"Exsanguinate", "talent(6,3) & inRange.spell & canAttack & deathin > 5 & debuff(Rupture).duration >= 18 & debuff(Garrote).duration >= 10", "target"},
{"#trinket1", "UI(trk1) & target.inRange(Mutilate).spell & target.canAttack"},
{"#trinket2", "UI(trk2) & target.inRange(Mutilate).spell & target.canAttack"},
}
local Combat = {
{"/startattack", "!isattacking & inRange(Mutilate).spell & canAttack & infront & !IsStealthed", "target"},
{"Tricks of the Trade", "target.inRange(Mutilate).spell & player.aggro & distance <= 20 & indungeon & UI(tott) & !IsStealthed", "tank"},
--Garrote
{Garrote, "inRange(Garrote).spell & spell(Garrote).cooldown <= 1 & canAttack & infront & player.combopoints < 4 & debuff(Garrote).duration < 5", "target"},
{"Garrote", "toggle(AoE) & canAttack & infront & !pvp & target.debuff(Garrote) & debuff(Garrote).duration < 3 & deathin > 9 & count.enemies.debuffs(Garrote) < 3 & player.area(7).enemies >= 2", "enemies"},
--AoEs
{"Fan of Knives", "toggle(AoE) & player.area(10).enemies >= 3 & !IsStealthed & {player.combopoints < 4 || !target.exists}", "player"},
{"Rupture", "toggle(AoE) & toggle(rupture_key) & inRange.spell & canAttack & infront & !pvp & target.debuff(Rupture) & debuff(Rupture).duration < 3 & deathin > 9 & player.combopoints > 2 & count.enemies.debuffs(Rupture) < 3 & player.area(7).enemies >= 2", "enemies"},
--Finishers
{"Rupture", "toggle(rupture_key) & inRange.spell & canAttack & infront & deathin > 12 & player.combopoints > 2 & debuff(Rupture).duration <= 8", "target"},
{"Envenom", "inRange.spell & canAttack & infront & player.combopoints > 3", "target"},
--Builders
{"Toxic Blade", "inRange.spell & talent(6,2) & canAttack & infront & player.combopoints < 4 & {!toggle(cooldowns) || toggle(cooldowns) & spell(Vendetta).cooldown > 0}", "target"},
{"Mutilate", "inRange.spell & canAttack & infront & player.combopoints < 4", "target"},
{"Sinister Strike", "inRange.spell & canAttack & infront & {player.level < 3 || player.combopoints <= 4 & player.level < 40}", "target"},
{"Eviscerate", "inRange.spell & canAttack & infront & player.level < 36 & player.combopoints > 4", "target"},
}
local inCombat = {
--Sometimes shit happens XD , so we prevent it.
{"!/stopcasting", "combat.time < 3 & {player.casting(Deadly Poison) || player.casting(Wound Poison) || player.casting(Crippling Poison)}", "player"},
--[[Targeting Function
{(function() Targeting() end), "UI(auto_target_key) & area(10).enemies.infront > 0 & {!target.exists || !target.alive || !target.enemy}", "player"},]]
{pvp},
{Survival, "player.health < 100"},
{"!/stopattack", "player.buff(Vanish) || target.immune_all", "player"},
--{pvp_1v1, "player.pvp & target.player & target.enemy & target.alive"},
{Keybinds, "target.alive"},
{Interrupts, "toggle(interrupts) & !IsStealthed"},
{Cooldowns, "toggle(cooldowns) & target.canAttack & target.alive & target.infront & !IsStealthed"},
{Combat, "target.canAttack & target.alive"},
}
local outCombat = {
{pvp},
{"Stealth", "UI(stealth_key) & !state(dot) & !IsStealthed & target.canAttack & target.alive", "player"},
{"Crimson Vial", "health <= UI(cv_spin) & UI(cv_check)", "player"},
{"!/stopattack", "player.buff(Vanish) || target.immune_all", "player"},
{Keybinds, "target.canAttack & target.alive & target.infront"},
{PreCombat, "target.canAttack & target.alive & target.infront"},
{Poisons, "!player.moving & !player.buff(Vanish)"},
}
NeP.CR:Add(259, {
name = "[|cffffff00Kleei|r]|cffffff00 ROGUE - Assassination",
ic = inCombat,
ooc = outCombat,
gui = GUI,
gui_st = {title="Kleei Combat Routine Settings", width="315", height="770", color="87CEFA"},
wow_ver = "8.0.1",
nep_ver = "1.11",
load = exeOnLoad
})
|
--[[
Input:bind('keyboard', 'released', function(key, scan_code)
print('keyreleased', key, scan_code)
end)
Input:bind('keyboard', 'textinput', function(char)
print('textinput', char)
end)
Input:bind('mouse', 'released', function(x, y, button)
print('mousereleased', x, y, button)
end)
]]
local Emitter = require 'src.emitter'
local Input = {
emitters = {
['textinput'] = Emitter(),
['keyboard'] = Emitter(),
['mouse'] = Emitter()
},
bind = function(self, emitter_id, event, callback)
self.emitters[emitter_id]:bind(event, callback)
end,
unbind = function(self, emitter_id, event, callback)
self.emitters[emitter_id]:unbind(event, callback)
end,
onKeyReleased = function(self, key, scan_code)
self.emitters.keyboard:emit('released', key, scan_code)
end,
onKeyPressed = function(self, key, scan_code, isrepeat)
if isrepeat then
self.emitters.keyboard:emit('repeated', key, scan_code)
else
self.emitters.keyboard:emit('pressed', key, scan_code)
end
end,
onTextInput = function(self, char)
self.emitters.keyboard:emit('textinput', char)
end,
onMouseReleased = function(self, x, y, button)
self.emitters['mouse']:emit('released', x, y, button)
end,
onMousePressed = function(self, x, y, button)
self.emitters['mouse']:emit('pressed', x, y, button)
end
}
return Input
|
GHI_ContainerData = {
}
GHI_ItemData = {
}
GHI_CooldownData = {
}
GHI_MiscData = {
["allow_camera_move"] = false,
["BackpackPos"] = {
269.000001592562, -- [1]
1058.00002397224, -- [2]
},
["block_area_buff"] = false,
["hide_mod_att_tooltip"] = false,
["UI_Themes"] = {
["Current"] = {
["detailsTextColor"] = {
1, -- [1]
1, -- [2]
1, -- [3]
1, -- [4]
},
["titleBarTextColor"] = {
1, -- [1]
1, -- [2]
1, -- [3]
1, -- [4]
},
["titleBar"] = {
0.502, -- [1]
0.102, -- [2]
0.102, -- [3]
1, -- [4]
},
["mainTextColor"] = {
1, -- [1]
0.82, -- [2]
0, -- [3]
1, -- [4]
},
["name"] = "<New Theme>",
["background"] = "Interface\\GLUES\\MODELS\\UI_BLOODELF\\bloodelf_mountains.blp",
["backgroundColor"] = {
1, -- [1]
1, -- [2]
1, -- [3]
0.502, -- [4]
},
["buttonColor"] = {
0.502, -- [1]
0.102, -- [2]
0.102, -- [3]
1, -- [4]
},
},
},
["UseMenuAnimation"] = true,
["target_icon_display_method"] = 1,
["chatMsgPermission"] = 1,
["hide_empty_slots"] = false,
["no_channel_comm"] = false,
["SyntaxColor"] = {
["number"] = {
0.8, -- [1]
0.2, -- [2]
0.8, -- [3]
},
["string"] = {
0.6, -- [1]
1, -- [2]
0.6, -- [3]
},
["comment"] = {
1, -- [1]
0.6, -- [2]
0.6, -- [3]
},
["keyword"] = {
0.6, -- [1]
0.6, -- [2]
1, -- [3]
},
["boolean"] = {
0.5, -- [1]
0.9, -- [2]
1, -- [3]
},
},
["BuffPos"] = {
["target"] = {
425.000015715137, -- [1]
1038.0000068061, -- [2]
},
},
["block_std_emote"] = true,
["stick_target_buffs"] = false,
["useWideEditor"] = false,
["tooltip_version"] = true,
["stick_player_buffs"] = true,
["soundPermission"] = 1,
["block_area_sound"] = false,
["WhiteList"] = {
"", -- [1]
"", -- [2]
"", -- [3]
"", -- [4]
"", -- [5]
"", -- [6]
"", -- [7]
"", -- [8]
"", -- [9]
"", -- [10]
"", -- [11]
"", -- [12]
"", -- [13]
"", -- [14]
"", -- [15]
"", -- [16]
"", -- [17]
},
["syntaxDisabled"] = false,
["show_area_sound_sender"] = false,
}
GHI_CS = {
[27008] = {
},
[27492] = {
},
[19716] = {
},
[25869] = {
},
[40449] = {
},
}
GHI_ActionBarData = {
}
GHI_ChatData = nil
GHI_EquipmentDisplayData = {
}
|
function AttachOrbs(keys)
local hero = keys.caster
local origin = hero:GetAbsOrigin()
local particleName = "particles/blood_mage/exort_orb.vpcf"
hero.orbs = {}
for i = 1, 3 do
hero.orbs[i] = ParticleManager:CreateParticle(particleName, PATTACH_OVERHEAD_FOLLOW, hero)
ParticleManager:SetParticleControlEnt(hero.orbs[i], 1, hero, PATTACH_POINT_FOLLOW, "attach_orb"..i, origin, false)
end
end
function RemoveOrbs(keys)
local hero = keys.caster
local origin = hero:GetAbsOrigin()
for i = 1, 3 do
if hero.orbs and hero.orbs[i] then
ParticleManager:DestroyParticle(hero.orbs[i], false)
ParticleManager:ReleaseParticleIndex(hero.orbs[i])
end
end
hero.orbs = {}
end
|
-- Smartab
-- MIT © 2019 Arthur Corenzan
-- More on https://github.com/haggen/wow
|
local class = require 'middleclass'
-- 基底クラス
local Repository = require 'repository.Repository'
-- リポジトリ:クラス
local CharacterClassRepository = class('CharacterClassRepository', Repository)
-- モジュール
local CharacterClass = require 'entities.CharacterClass'
-- 初期化
function CharacterClassRepository:initialize(t)
Repository.initialize(self, t)
end
-- データ読み込み
function CharacterClassRepository:loadData(t)
return CharacterClass(t)
end
return CharacterClassRepository
|
-- XEP-0257: Client Certificates Management implementation for Prosody
-- Copyright (C) 2012 Thijs Alkemade
--
-- This file is MIT/X11 licensed.
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
local jid_split = require "util.jid".split;
local xmlns_saslcert = "urn:xmpp:saslcert:1";
local dm_load = require "util.datamanager".load;
local dm_store = require "util.datamanager".store;
local dm_table = "client_certs";
local x509 = require "ssl.x509";
local id_on_xmppAddr = "1.3.6.1.5.5.7.8.5";
local id_ce_subjectAltName = "2.5.29.17";
local digest_algo = "sha1";
local base64 = require "util.encodings".base64;
local function get_id_on_xmpp_addrs(cert)
local id_on_xmppAddrs = {};
for k,ext in pairs(cert:extensions()) do
if k == id_ce_subjectAltName then
for e,extv in pairs(ext) do
if e == id_on_xmppAddr then
for i,v in ipairs(extv) do
id_on_xmppAddrs[#id_on_xmppAddrs+1] = v;
end
end
end
end
end
module:log("debug", "Found JIDs: (%d) %s", #id_on_xmppAddrs, table.concat(id_on_xmppAddrs, ", "));
return id_on_xmppAddrs;
end
local function enable_cert(username, cert, info)
-- Check the certificate. Is it not expired? Does it include id-on-xmppAddr?
--[[ the method expired doesn't exist in luasec .. yet?
if cert:expired() then
module:log("debug", "This certificate is already expired.");
return nil, "This certificate is expired.";
end
--]]
if not cert:validat(os.time()) then
module:log("debug", "This certificate is not valid at this moment.");
end
local valid_id_on_xmppAddrs;
local require_id_on_xmppAddr = true;
if require_id_on_xmppAddr then
valid_id_on_xmppAddrs = get_id_on_xmpp_addrs(cert);
local found = false;
for i,k in pairs(valid_id_on_xmppAddrs) do
if jid_bare(k) == (username .. "@" .. module.host) then
found = true;
break;
end
end
if not found then
return nil, "This certificate has no valid id-on-xmppAddr field.";
end
end
local certs = dm_load(username, module.host, dm_table) or {};
info.pem = cert:pem();
local digest = cert:digest(digest_algo);
info.digest = digest;
certs[info.name] = info;
dm_store(username, module.host, dm_table, certs);
return true
end
local function disable_cert(username, name, disconnect)
local certs = dm_load(username, module.host, dm_table) or {};
local info = certs[name];
if not info then
return nil, "item-not-found"
end
certs[name] = nil;
if disconnect then
module:log("debug", "%s revoked a certificate! Disconnecting all clients that used it", username);
local sessions = hosts[module.host].sessions[username].sessions;
local disabled_cert_pem = info.pem;
for _, session in pairs(sessions) do
if session and session.conn then
local cert = session.conn:socket():getpeercertificate();
if cert and cert:pem() == disabled_cert_pem then
module:log("debug", "Found a session that should be closed: %s", tostring(session));
session:close{ condition = "not-authorized", text = "This client side certificate has been revoked."};
end
end
end
end
dm_store(username, module.host, dm_table, certs);
return info;
end
module:hook("iq/self/"..xmlns_saslcert..":items", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "get" then
module:log("debug", "%s requested items", origin.full_jid);
local reply = st.reply(stanza):tag("items", { xmlns = xmlns_saslcert });
local certs = dm_load(origin.username, module.host, dm_table) or {};
for digest,info in pairs(certs) do
reply:tag("item")
:tag("name"):text(info.name):up()
:tag("x509cert"):text(info.x509cert)
:up();
end
origin.send(reply);
return true
end
end);
module:hook("iq/self/"..xmlns_saslcert..":append", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local append = stanza:get_child("append", xmlns_saslcert);
local name = append:get_child_text("name", xmlns_saslcert);
local x509cert = append:get_child_text("x509cert", xmlns_saslcert);
if not x509cert or not name then
origin.send(st.error_reply(stanza, "cancel", "bad-request", "Missing fields.")); -- cancel? not modify?
return true
end
local can_manage = append:get_child("no-cert-management", xmlns_saslcert) ~= nil;
x509cert = x509cert:gsub("^%s*(.-)%s*$", "%1");
local cert = x509.load(
"-----BEGIN CERTIFICATE-----\n"
.. x509cert ..
"\n-----END CERTIFICATE-----\n");
if not cert then
origin.send(st.error_reply(stanza, "modify", "not-acceptable", "Could not parse X.509 certificate"));
return true;
end
local ok, err = enable_cert(origin.username, cert, {
name = name,
x509cert = x509cert,
no_cert_management = can_manage,
});
if not ok then
origin.send(st.error_reply(stanza, "cancel", "bad-request", err));
return true -- REJECT?!
end
module:log("debug", "%s added certificate named %s", origin.full_jid, name);
origin.send(st.reply(stanza));
return true
end
end);
local function handle_disable(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local disable = stanza.tags[1];
module:log("debug", "%s disabled a certificate", origin.full_jid);
local name = disable:get_child_text("name");
if not name then
origin.send(st.error_reply(stanza, "cancel", "bad-request", "No key specified."));
return true
end
disable_cert(origin.username, name, disable.name == "revoke");
origin.send(st.reply(stanza));
return true
end
end
module:hook("iq/self/"..xmlns_saslcert..":disable", handle_disable);
module:hook("iq/self/"..xmlns_saslcert..":revoke", handle_disable);
-- Ad-hoc command
local adhoc_new = module:require "adhoc".new;
local dataforms_new = require "util.dataforms".new;
local function generate_error_message(errors)
local errmsg = {};
for name, err in pairs(errors) do
errmsg[#errmsg + 1] = name .. ": " .. err;
end
return table.concat(errmsg, "\n");
end
local choose_subcmd_layout = dataforms_new {
title = "Certificate management";
instructions = "What action do you want to perform?";
{ name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/certs#subcmd" };
{ name = "subcmd", type = "list-single", label = "Actions", required = true,
value = { {label = "Add certificate", value = "add"},
{label = "List certificates", value = "list"},
{label = "Disable certificate", value = "disable"},
{label = "Revoke certificate", value = "revoke"},
};
};
};
local add_layout = dataforms_new {
title = "Adding a certificate";
instructions = "Enter the certificate in PEM format";
{ name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/certs#add" };
{ name = "name", type = "text-single", label = "Name", required = true };
{ name = "cert", type = "text-multi", label = "PEM certificate", required = true };
{ name = "manage", type = "boolean", label = "Can manage certificates", value = true };
};
local disable_layout_stub = dataforms_new { { name = "cert", type = "list-single", label = "Certificate", required = true } };
local function adhoc_handler(self, data, state)
if data.action == "cancel" then return { status = "canceled" }; end
if not state or data.action == "prev" then
return { status = "executing", form = choose_subcmd_layout, actions = { "next" } }, {};
end
if not state.subcmd then
local fields, errors = choose_subcmd_layout:data(data.form);
if errors then
return { status = "completed", error = { message = generate_error_message(errors) } };
end
local subcmd = fields.subcmd
if subcmd == "add" then
return { status = "executing", form = add_layout, actions = { "prev", "next", "complete" } }, { subcmd = "add" };
elseif subcmd == "list" then
local list_layout = dataforms_new {
title = "List of certificates";
};
local certs = dm_load(jid_split(data.from), module.host, dm_table) or {};
for digest, info in pairs(certs) do
list_layout[#list_layout + 1] = { name = info.name, type = "text-multi", label = info.name, value = info.x509cert };
end
return { status = "completed", result = list_layout };
else
local layout = dataforms_new {
{ name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/certs#" .. subcmd };
{ name = "cert", type = "list-single", label = "Certificate", required = true };
};
if subcmd == "disable" then
layout.title = "Disabling a certificate";
layout.instructions = "Select the certificate to disable";
elseif subcmd == "revoke" then
layout.title = "Revoking a certificate";
layout.instructions = "Select the certificate to revoke";
end
local certs = dm_load(jid_split(data.from), module.host, dm_table) or {};
local values = {};
for digest, info in pairs(certs) do
values[#values + 1] = { label = info.name, value = info.name };
end
return { status = "executing", form = { layout = layout, values = { cert = values } }, actions = { "prev", "next", "complete" } },
{ subcmd = subcmd };
end
end
if state.subcmd == "add" then
local fields, errors = add_layout:data(data.form);
if errors then
return { status = "completed", error = { message = generate_error_message(errors) } };
end
local name = fields.name;
local x509cert = fields.cert:gsub("^%s*(.-)%s*$", "%1");
local cert = x509.load(
"-----BEGIN CERTIFICATE-----\n"
.. x509cert ..
"\n-----END CERTIFICATE-----\n");
if not cert then
return { status = "completed", error = { message = "Could not parse X.509 certificate" } };
end
local ok, err = enable_cert(jid_split(data.from), cert, {
name = name,
x509cert = x509cert,
no_cert_management = not fields.manage
});
if not ok then
return { status = "completed", error = { message = err } };
end
module:log("debug", "%s added certificate named %s", data.from, name);
return { status = "completed", info = "Successfully added certificate " .. name .. "." };
else
local fields, errors = disable_layout_stub:data(data.form);
if errors then
return { status = "completed", error = { message = generate_error_message(errors) } };
end
local info = disable_cert(jid_split(data.from), fields.cert, state.subcmd == "revoke" );
if state.subcmd == "revoke" then
return { status = "completed", info = "Revoked certificate " .. info.name .. "." };
else
return { status = "completed", info = "Disabled certificate " .. info.name .. "." };
end
end
end
local cmd_desc = adhoc_new("Manage certificates", "http://prosody.im/protocol/certs", adhoc_handler, "user");
module:provides("adhoc", cmd_desc);
-- Here comes the SASL EXTERNAL stuff
local now = os.time;
module:hook("stream-features", function(event)
local session, features = event.origin, event.features;
if session.secure and session.type == "c2s_unauthed" then
local cert = session.conn:socket():getpeercertificate();
if not cert then
module:log("error", "No Client Certificate");
return
end
module:log("info", "Client Certificate: %s", cert:digest(digest_algo));
if not cert:validat(now()) then
module:log("debug", "Client has an expired certificate", cert:digest(digest_algo));
return
end
module:log("debug", "Stream features:\n%s", tostring(features));
local mechs = features:get_child("mechanisms", "urn:ietf:params:xml:ns:xmpp-sasl");
if mechs then
mechs:tag("mechanism"):text("EXTERNAL");
end
end
end, -1);
local sm_make_authenticated = require "core.sessionmanager".make_authenticated;
module:hook("stanza/urn:ietf:params:xml:ns:xmpp-sasl:auth", function(event)
local session, stanza = event.origin, event.stanza;
if session.type == "c2s_unauthed" and stanza.attr.mechanism == "EXTERNAL" then
if session.secure then
local cert = session.conn:socket():getpeercertificate();
local username_data = stanza:get_text();
local username = nil;
if username_data == "=" then
-- Check for either an id_on_xmppAddr
local jids = get_id_on_xmpp_addrs(cert);
if not (#jids == 1) then
module:log("debug", "Client tried to authenticate as =, but certificate has multiple JIDs.");
module:fire_event("authentication-failure", { session = session, condition = "not-authorized" });
session.send(st.stanza("failure", { xmlns="urn:ietf:params:xml:ns:xmpp-sasl"}):tag"not-authorized");
return true;
end
username = jids[1];
else
-- Check the base64 encoded username
username = base64.decode(username_data);
end
local user, host, resource = jid_split(username);
module:log("debug", "Inferred username: %s", user or "nil");
if (not username) or (not host == module.host) then
module:log("debug", "No valid username found for %s", tostring(session));
module:fire_event("authentication-failure", { session = session, condition = "not-authorized" });
session.send(st.stanza("failure", { xmlns="urn:ietf:params:xml:ns:xmpp-sasl"}):tag"not-authorized");
return true;
end
local certs = dm_load(user, module.host, dm_table) or {};
local digest = cert:digest(digest_algo);
local pem = cert:pem();
for name,info in pairs(certs) do
if info.digest == digest and info.pem == pem then
sm_make_authenticated(session, user);
module:fire_event("authentication-success", { session = session });
session.send(st.stanza("success", { xmlns="urn:ietf:params:xml:ns:xmpp-sasl"}));
session:reset_stream();
return true;
end
end
module:fire_event("authentication-failure", { session = session, condition = "not-authorized" });
session.send(st.stanza("failure", { xmlns="urn:ietf:params:xml:ns:xmpp-sasl"}):tag"not-authorized");
else
session.send(st.stanza("failure", { xmlns="urn:ietf:params:xml:ns:xmpp-sasl"}):tag"encryption-required");
end
return true;
end
end, 1);
|
--------------------------------------------------------------------------------
-- Sobol quasi random number generator module.
--
-- Copyright (C) 2011-2014 Stefano Peluchetti. All rights reserved.
--
-- Features, documentation and more: http://www.scilua.org .
--
-- Credit: this implementation is based on the code published at:
-- http://web.maths.unsw.edu.au/~fkuo/sobol/ .
-- Please notice that the code written in this file is NOT endorsed in any way
-- by the authors of the original C++ code (on which this implementation is
-- based), S. Joe and F. Y. Kuo, nor they participated in the development of
-- this Lua implementation.
-- Any bug / problem introduced in this port is my sole responsibility.
--
-- This file is part of the SciLua library, which is released under the MIT
-- license: full text in file LICENSE.TXT in the library's root folder.
--------------------------------------------------------------------------------
local ffi = require "ffi"
local dirndata = require "sci.qrng._new-joe-kuo-6-21201"
local xsys = require "xsys"
local cfg = require "sci.alg.cfg"
local UNROLL = cfg.unroll
local bit = xsys.bit
local tobit, lshift, rshift = bit.tobit, bit.lshift, bit.rshift
local band, bor, bxor, lsb = bit.band, bit.bor, bit.bxor, bit.lsb
local sobol_t = ffi.typeof([[
struct {
int32_t _n; // Counter.
int32_t _o; // Offset.
int32_t _s; // Status.
int32_t _d; // Dimension.
int32_t _x[21202]; // State.
} ]])
-- For background see:
-- http://web.maths.unsw.edu.au/~fkuo/sobol/joe-kuo-notes.pdf .
local m = dirndata.m -- Sequence of positive integers.
local a = dirndata.a -- Primitive polynomial coefficients.
-- Direction numbers: 32 bits * 21201 dimensions.
-- Maximum number of samples is 2^32-1 (the origin, i=0, is discarded).
local v = ffi.new("int32_t[33][21202]")
-- Fill direction numbers for first dimension, all m = 1.
for i=1,32 do v[i][1] = lshift(1, 32-i) end
local maxdim = 1 -- Current maximum dimension.
local function compute_dn(dim) -- Fill direction numbers up to dimension dim.
if dim > 21201 then
error("maximum dimensionality of 21201 exceeded, requested "..dim)
end
if dim > maxdim then -- Maxdim is max dimension computed up to now.
for j=maxdim+1, dim do -- Compute missing dimensions.
local s = #m[j]
for i=1,s do
v[i][j] = lshift(m[j][i], 32-i)
end
for i=s+1,32 do
v[i][j] = bxor(v[i-s][j], rshift(v[i-s][j], s))
for k=1,s-1 do
v[i][j] = bxor(v[i][j], band(rshift(a[j], s-1-k), 1) * v[i-k][j])
end
end
end
maxdim = dim
end
end
local function fill_state(self, c)
for i=1,21201 do self._x[i] = c end
end
local next_state_template = xsys.template([[
return function(self)
local n = self._d
local c = lsb(self._n) + 1
|for n=1,UNROLL do
${n==1 and 'if' or 'elseif'} n == ${n} then
|for i=1,n do
self._x[${i}] = bxor(self._x[${i}], v[c][${i}])
|end
|end
${UNROLL>=1 and 'else'}
for i=1,n do
self._x[i] = bxor(self._x[i], v[c][i])
end
${UNROLL>=1 and 'end'}
self._o = 0
end
]])
local next_state = xsys.exec(next_state_template({ UNROLL = UNROLL }),
"next_state", { lsb = lsb, bxor = bxor, v = v })
local sobol_mt = {
__new = function(ct)
-- -2^31 is state at first iteration, which is precomputed.
local o = ffi.new(ct, -1, 0, 0, 21201)
fill_state(o, -2^31)
return o
end,
-- Move rng to next state (exactly all dimensions must have been used).
nextstate = function(self)
self._n = tobit(self._n + 1)
if self._n <= 0 then
if self._s == 0 then -- Zero iterations up to now.
if self._o ~= 0 then
error(":sample() called before :nextstate()")
end
self._n = -1 -- Get back to self._n = 0 condition next iteration.
self._s = 1
return
elseif self._s == 1 then -- One iteration up to now, initializing.
self._s = 2
self._d = self._o
fill_state(self, 0)
compute_dn(self._d)
-- Recover missed computations.
self._n = 1
next_state(self)
self._o = self._d
self._n = 2
else
error("limit of 2^32-1 states exceeded")
end
end
-- Usual operation.
if self._o ~= self._d then
error("not enough samples generated for current state, dimensionality is "
..self._d)
end
next_state(self)
end,
-- Result between (0, 1) extremes excluded.
sample = function(self)
self._o = self._o + 1
if self._o > self._d then
error("too many samples generated for current state, dimensionality is "
..self._d)
end
return (bxor(self._x[self._o], 0x80000000) + 0x80000000)*(1/2^32)
end,
}
sobol_mt.__index = sobol_mt
local qrng = ffi.metatype(sobol_t, sobol_mt)
return {
qrng = qrng,
} |
local modname = minetest.get_current_modname()
local test_box = modname .. ":test_box"
local textures = {}
for index = 1, 6 do
textures[index] = modname .. "_test_box.png"
end
minetest.register_entity(test_box, {
initial_properties = {
physical = false,
pointable = true,
visual = "cube",
visual_size = { x = 1, y = 1, z = 1 },
textures = textures,
colors = {},
use_texture_alpha = true,
backface_culling = true,
glow = 14,
infotext = "Collisionbox",
static_save = false,
shaded = false
}
})
local function visualize_box(pos, box)
local obj = minetest.add_entity(vector.add(pos, {x = (box[1] + box[4]) / 2, y = (box[2] + box[5]) / 2, z = (box[3] + box[6]) / 2}), test_box)
obj:set_properties{
infotext = "Collisionbox: " .. minetest.write_json(box),
visual_size = {x = box[4] - box[1], y = box[5] - box[2], z = box[6] - box[3]}
}
end
return visualize_box |
MqttConventionPrototype = {
type = "'type' needs to be overriden",
mqtt = "MQTT connection must be established first"
}
function MqttConventionPrototype:getLastWillMessage()
error("function is mandatory for implementation")
end
function MqttConventionPrototype:onConnected()
error("function is mandatory for implementation")
end
function MqttConventionPrototype:onDeviceCreated(device)
error("function is mandatory for implementation")
end
function MqttConventionPrototype:onDeviceRemoved(device)
error("function is mandatory for implementation")
end
function MqttConventionPrototype:onPropertyUpdated(device, event)
error("function is mandatory for implementation")
end
function MqttConventionPrototype:onCommand(event)
error("function is mandatory for implementation")
end
function MqttConventionPrototype:onDisconnected()
error("function is mandatory for implementation")
end
-----------------------------------
-- HOME ASSISTANT
-----------------------------------
MqttConventionHomeAssistant = inheritFrom(MqttConventionPrototype)
MqttConventionHomeAssistant.type = "Home Assistant"
MqttConventionHomeAssistant.rootTopic = "homeassistant/"
-- TOPICS
function MqttConventionHomeAssistant:getDeviceTopic(device)
return self.rootTopic .. device.bridgeType .. "/" .. device.id .. "/"
end
function MqttConventionHomeAssistant:getGenericEventTopic(device, eventType, propertyName)
if (propertyName) then
return self:getDeviceTopic(device) .. "events/" .. eventType .. "/" .. propertyName
else
return self:getDeviceTopic(device) .. "events/" .. eventType
end
end
function MqttConventionHomeAssistant:getterTopic(device, propertyName)
return self:getGenericEventTopic(device, "DevicePropertyUpdatedEvent", propertyName)end
function MqttConventionHomeAssistant:getGenericCommandTopic(device, command, propertyName)
if (propertyName) then
return self:getDeviceTopic(device) .. command .. "/" .. propertyName
else
return self:getDeviceTopic(device) .. command
end
end
function MqttConventionHomeAssistant:setterTopic(device, propertyName)
return self:getGenericCommandTopic(device, "set", propertyName)
end
function MqttConventionHomeAssistant:getLastWillAvailabilityTopic()
return self.rootTopic .. "hc3-dead"
end
function MqttConventionHomeAssistant:getLastWillMessage()
return {
topic = self:getLastWillAvailabilityTopic(),
payload = "true"
}
end
function MqttConventionHomeAssistant:onConnected()
self.mqtt:publish(self.rootTopic .. "hc3-dead", "false", {retain = true})
self.mqtt:subscribe(self.rootTopic .. "+/+/set/+")
end
function MqttConventionHomeAssistant:onDisconnected()
self.mqtt:publish(self.rootTopic .. "hc3-dead", "true", {retain = true})
end
function MqttConventionHomeAssistant:onDeviceCreated(device)
------------------------------------------
--- AVAILABILITY
------------------------------------------
local msg = {
unique_id = tostring(device.id),
name = device.name .. " (" .. device.roomName .. ")",
availability_mode = "all",
availability = {
{
topic = self:getLastWillAvailabilityTopic(),
payload_available = "false",
payload_not_available = "true"
}
,
{
topic = self:getterTopic(device, "dead"),
payload_available = "false",
payload_not_available = "true"
}
},
json_attributes_topic = self:getDeviceTopic(device) .. "config_json_attributes"
}
------------------------------------------
--- PARENT DEVICE INFO
------------------------------------------
local parentDevice = device.bridgeParent
if parentDevice then
msg.device = {
identifiers = "hc3-" .. parentDevice.id,
name = parentDevice.name,
manufacturer = parentDevice.properties.zwaveCompany,
model = parentDevice.properties.model,
-- zwave version is used instead of device software version
sw_version = parentDevice.properties.zwaveVersion
}
end
------------------------------------------
--- USE "TRUE"/"FALSE" VALUE PAYLOAD, instead of "ON"/"OFF"
------------------------------------------
if (device.bridgeRead) then
if (device.bridgeBinary and device.bridgeType ~= "cover") then
msg.payload_on = "true"
msg.payload_off = "false"
end
msg.value_template = "{{ value_json.value }}"
end
------------------------------------------
---- READ
------------------------------------------
-- Does device have binary state to share?
if (device.bridgeRead and device.bridgeBinary) then
msg.state_topic = self:getterTopic(device, "state")
end
-- Does device have multilevel state to share?
if (device.bridgeRead and device.bridgeMultilevel) then
if (device.bridgeType == "light") then
msg.brightness_state_topic = self:getterTopic(device, "value")
msg.brightness_value_template = "{{ value_json.value }}"
elseif (device.bridgeType == "cover") then
msg.position_topic = self:getterTopic(device, "value")
elseif (device.bridgeType == "sensor") then
msg.state_topic = self:getterTopic(device, "value")
end
end
------------------------------------------
---- WRITE
------------------------------------------
-- Does device support binary write operations?
if (device.bridgeWrite and device.bridgeBinary) then
msg.command_topic = self:setterTopic(device, "state")
end
-- Does device support multilevel write operations?
if (device.bridgeWrite) and (device.bridgeMultilevel) then
if (device.bridgeType == "light") then
msg.brightness_command_topic = self:setterTopic(device, "value")
msg.brightness_scale = 99
msg.on_command_type = "brightness"
elseif (device.bridgeType == "cover") then
msg.set_position_topic = self:setterTopic(device, "value")
msg.position_template = "{{ value_json.value }}"
-- value_template is deprecated since Home Assistant Core 2021.6.
msg.value_template = nil
msg.position_open = 99
msg.position_closed = 0
msg.payload_open = "open"
msg.payload_close = "close"
msg.payload_stop = "stop"
msg.state_open = "open"
msg.state_closed = "closed"
msg.state_opening = "opening"
msg.state_closing = "closing"
msg.state_topic = self:setterTopic(device, "state")
end
end
------------------------------------------
---- SENSOR SPECIFIC
------------------------------------------
if (device.bridgeType == "binary_sensor" or device.bridgeType == "sensor") then
if (PrototypeDevice.bridgeSubtype ~= device.bridgeSubtype) then
msg.device_class = device.bridgeSubtype
end
if (PrototypeDevice.bridgeUnitOfMeasurement ~= device.bridgeUnitOfMeasurement) then
msg.unit_of_measurement = device.bridgeUnitOfMeasurement
end
end
------------------------------------------
---- THERMOSTAT SPECIFIC
------------------------------------------
if (device.bridgeType == "climate") then
msg.modes = device.properties.supportedThermostatModes
msg.temperature_unit = device.properties.unit
msg.temp_step = device.properties.heatingThermostatSetpointStep[msg.temperature_unit]
-- MODE
msg.mode_state_topic = self:getterTopic(device, "thermostatMode")
msg.mode_command_topic = self:setterTopic(device, "thermostatMode")
-- MIX/MAX TEMPERATURE
msg.min_temp = device.properties.heatingThermostatSetpointCapabilitiesMin
msg.max_temp = device.properties.heatingThermostatSetpointCapabilitiesMax
-- TARGET TEMPERATURE
msg.temperature_state_topic = self:getterTopic(device, "heatingThermostatSetpoint")
msg.temperature_command_topic = self:setterTopic(device, "heatingThermostatSetpoint")
-- CURRENT TEMPERATURE
local temperatureSensorDevice = device:getTemperatureSensor(self.devices)
if temperatureSensorDevice then
msg.current_temperature_topic = self:getterTopic(temperatureSensorDevice, "value")
end
end
self.mqtt:publish(self:getDeviceTopic(device) .. "config", json.encode(msg), {retain = true})
self.mqtt:publish(self:getDeviceTopic(device) .. "config_json_attributes", json.encode(device.fibaroDevice), {retain = true})
end
function MqttConventionHomeAssistant:onDeviceRemoved(device)
self.mqtt:publish(
self:getDeviceTopic(device) .. "config",
""
)
end
function MqttConventionHomeAssistant:onPropertyUpdated(device, event)
local propertyName = event.data.property
local value = (type(event.data.newValue) == "number" and event.data.newValue or tostring(event.data.newValue))
if device.bridgeType == "cover" then
if propertyName == "value" then
-- Fibaro doesn't use "state" attribute for covers, so we'll trigger it on behalf of Fibaro based on "value" attribute
local state
if value < 20 then
state = "closed"
elseif value > 80 then
state = "open"
else
state = "unknown"
end
if state then
local payload = {
id = device.id,
deviceName = device.name,
created = event.created,
timestamp = os.date(),
roomName = device.roomName,
value = state
}
formattedState = json.encode(payload)
--formattedState = state
self.mqtt:publish(self:getterTopic(device, "state"), formattedState, {retain = true})
end
elseif propertyName == "state" then
if (value == "unknown") then
-- drop event as Fibaro has "Uknnown" value constantly assigned to the "state" attribute
return
end
end
end
value = string.lower(value)
if(device.bridgeType == "scene") then
value = json.encode(event)
end
local formattedPayload
if (propertyName == "dead") then
formattedPayload = tostring(value)
else
local payload = {
id = device.id,
deviceName = device.name,
created = event.created,
timestamp = os.date(),
roomName = device.roomName,
value = value
}
formattedPayload = json.encode(payload)
end
if (device.bridgeType == "scene") then
self.mqtt:publish(self:getGenericEventTopic(device, "scene", propertyName), formattedPayload, {retain = false})
else
self.mqtt:publish(self:getterTopic(device, propertyName), formattedPayload, {retain = true}) -- original: Retain true
end
end
function MqttConventionHomeAssistant:onCommand(event)
if (string.find(event.topic, self.rootTopic) == 1) then
-- Home Assistant command detected
local topicElements = splitString(event.topic, "/")
local deviceId = tonumber(topicElements[3])
local propertyName = topicElements[5]
local device = self.devices[deviceId]
local value = event.payload
if (device.bridgeType == "climate") then
-- Fibaro HC3 uses first letter in upper case, and HA relies on lower case
local firstPart = string.upper(string.sub(value, 1, 1))
local secondPart = string.sub(value, 2, string.len(value))
value = firstPart .. secondPart
end
device:setProperty(propertyName, value)
end
end
-----------------------------------
-- HOMIE
-----------------------------------
MqttConventionHomie = inheritFrom(MqttConventionPrototype)
MqttConventionHomie.type = "Homie"
MqttConventionHomie.rootTopic = "homie/"
-- TOPICS
function MqttConventionHomie:getDeviceTopic(device)
return self.rootTopic .. device.id .. "/"
end
function MqttConventionHomie:getGenericEventTopic(device, eventType, propertyName)
if (propertyName) then
return self:getDeviceTopic(device) .. "events/" .. eventType .. "/" .. propertyName
else
return self:getDeviceTopic(device) .. "events/" .. eventType
end
end
function MqttConventionHomie:getterTopic(device, propertyName)
return self:getGenericEventTopic(device, "DevicePropertyUpdatedEvent", propertyName)
end
function MqttConventionHomie:getGenericCommandTopic(device, command, propertyName)
if (propertyName) then
return self:getDeviceTopic(device) .. command .. "/" .. propertyName
else
return self:getDeviceTopic(device) .. command
end
end
function MqttConventionHomie:getSetterTopic(device, propertyName)
return self:getGenericCommandTopic(device, "set", propertyName)
end
function MqttConventionHomie:getLastWillMessage()
return {
topic = self.rootTopic .. "hc3-dead",
payload = "true",
lastWill = true
}
end
function MqttConventionHomie:onConnected()
self.mqtt:subscribe(self.rootTopic .. "+/+/+/set")
end
function MqttConventionHomie:onDisconnected()
end
function MqttConventionHomie:onDeviceCreated(device)
self.mqtt:publish(self:getDeviceTopic(device) .. "$homie", "2.1.0", {retain = true})
self.mqtt:publish(self:getDeviceTopic(device) .. "$name", device.name .. " (" .. device.roomName .. ")", {retain = true})
self.mqtt:publish(self:getDeviceTopic(device) .. "$implementation", "Fibaro HC3 to MQTT bridge", {retain = true})
self.mqtt:publish(self:getDeviceTopic(device) .. "$nodes", "node", {retain = true})
self.mqtt:publish(self:getDeviceTopic(device) .. "node/$name", device.name, {retain = true})
self.mqtt:publish(self:getDeviceTopic(device) .. "node/$type", "", {retain = true})
self.mqtt:publish(self:getDeviceTopic(device) .. "$extensions", "", {retain = true})
local properties = { }
if (device.bridgeRead) then
local propertyName = device.bridgeType
if (PrototypeDevice.bridgeSubtype ~= device.bridgeSubtype) then
propertyName = propertyName .. " - " .. device.bridgeSubtype
end
if (device.bridgeBinary) then
properties["state"] = {
name = device.bridgeType,
datatype = "boolean",
settable = device.bridgeWrite,
retained = true,
}
end
if (device.bridgeMultilevel) then
properties["value"] = {
name = device.bridgeType,
datatype = "integer",
settable = device.bridgeWrite,
retained = true,
unit = device.bridgeUnitOfMeasurement
}
end
end
local propertiesStr = ""
local firstParameter = true
for i, j in pairs(properties) do
if (not firstParameter) then
propertiesStr = propertiesStr .. ","
end
propertiesStr = propertiesStr .. i
firstParameter = false
end
self.mqtt:publish(self:getDeviceTopic(device) .. "node/$properties", propertiesStr, {retain = true})
for i, j in pairs(properties) do
local propertyTopic = self:getDeviceTopic(device) .. "node/" .. i .. "/$"
for m, n in pairs(j) do
self.mqtt:publish(propertyTopic .. m, tostring(n), {retain = true})
end
end
local homieState
if (device.dead) then
homieState = "lost"
else
homieState = "ready"
end
self.mqtt:publish(self:getDeviceTopic(device) .. "$state", homieState, {retain = true})
end
function MqttConventionHomie:onDeviceRemoved(device)
end
function MqttConventionHomie:onPropertyUpdated(device, event)
local propertyName = event.data.property
local value = (type(event.data.newValue) == "number" and event.data.newValue or tostring(event.data.newValue))
value = string.lower(value)
self.mqtt:publish(self:getDeviceTopic(device) .. "node/" .. propertyName, value, {retain = true})
end
function MqttConventionHomie:onCommand(event)
if (string.find(event.topic, self.rootTopic) == 1) then
local topicElements = splitString(event.topic, "/")
local deviceId = tonumber(topicElements[2])
local device = self.devices[deviceId]
local propertyName = topicElements[4]
local value = event.payload
device:setProperty(propertyName, value)
end
end
-----------------------------------
-- FOR EXTENDED DEBUG PURPOSES
-----------------------------------
MqttConventionDebug = inheritFrom(MqttConventionPrototype)
MqttConventionDebug.type = "Debug"
function MqttConventionDebug:getLastWillMessage()
end
function MqttConventionDebug:onDeviceCreated(device)
end
function MqttConventionDebug:onDeviceRemoved(device)
end
function MqttConventionDebug:onPropertyUpdated(device, event)
end
function MqttConventionDebug:onConnected()
end
function MqttConventionDebug:onCommand(event)
end
function MqttConventionDebug:onDisconnected()
end
-----------------------------------
-- MQTT CONVENTION MAPPINGS
-----------------------------------
mqttConventionMappings = {
["home-assistant"] = MqttConventionHomeAssistant,
["homie"] = MqttConventionHomie,
["debug"] = MqttConventionDebug
}
|
local GAMEMODE = PIS:GetGamemode()
GAMEMODE:SetName("Backup")
GAMEMODE:SetID("backup")
GAMEMODE:SetDetectionCondition(function()
return false
end)
GAMEMODE:SetPlayers(function(author)
local tbl = {}
for i, v in pairs(player.GetAll()) do
if (v == author) then continue end
table.insert(tbl, v)
end
return tbl
end)
GAMEMODE:SetSubtitleDisplay(function(player)
return player:GetUserGroup():sub(1, 1):upper() .. player:GetUserGroup():sub(2)
end)
GAMEMODE:SetViewCondition(function(author, target)
return true
end)
GAMEMODE:SetPingCondition(function(author)
return author:Alive()
end)
GAMEMODE:SetCommandCondition(function(author)
return true
end)
GAMEMODE:SetInteractionCondition(function(author)
return author:Alive()
end)
GAMEMODE:SetOnDeath(function(author)
end)
GAMEMODE:Register()
|
do
local _ENV = _ENV
package.preload[ "alfons.env" ] = function( ... ) local arg = _G.arg;
local style
style = require("ansikit.style").style
local setfenv = setfenv or require("alfons.setfenv")
local fs = require("filekit")
local unpack = unpack or table.unpack
local ENVIRONMENT
ENVIRONMENT = {
_VERSION = _VERSION,
assert = assert,
error = error,
pcall = pcall,
xpcall = xpcall,
tonumber = tonumber,
tostring = tostring,
select = select,
type = type,
pairs = pairs,
ipairs = ipairs,
next = next,
unpack = unpack,
require = require,
print = print,
style = style,
io = io,
math = math,
string = string,
table = table,
os = os,
fs = fs
}
local loadEnv
loadEnv = function(content, env)
local fn
local _exp_0 = _VERSION
if "Lua 5.1" == _exp_0 then
local err
fn, err = loadstring(content)
if not (fn) then
return nil, "Could not load Alfonsfile content (5.1): " .. tostring(err)
end
setfenv(fn, env)
elseif "Lua 5.2" == _exp_0 or "Lua 5.3" == _exp_0 or "Lua 5.4" == _exp_0 then
local err
fn, err = load(content, "Alfons", "t", env)
if not (fn) then
return nil, "Could not load Alfonsfile content (5.2+): " .. tostring(err)
end
end
return fn
end
return {
ENVIRONMENT = ENVIRONMENT,
loadEnv = loadEnv
}
end
end
do
local _ENV = _ENV
package.preload[ "alfons.file" ] = function( ... ) local arg = _G.arg;
local fs = require("filekit")
local readMoon
readMoon = function(file)
local content
do
local _with_0 = fs.safeOpen(file, "r")
if _with_0.error then
return nil, "Could not open " .. tostring(file) .. ": " .. tostring(_with_0.error)
end
local to_lua
to_lua = require("moonscript.base").to_lua
local err
content, err = to_lua(_with_0:read("*a"))
if not (content) then
return nil, "Could not read or parse " .. tostring(file) .. ": " .. tostring(err)
end
_with_0:close()
end
return content
end
local readLua
readLua = function(file)
local content
do
local _with_0 = fs.safeOpen(file, "r")
if _with_0.error then
return nil, "Could not open " .. tostring(file) .. ": " .. tostring(_with_0.error)
end
content = _with_0:read("*a")
if not (content) then
return nil, "Could not read " .. tostring(file) .. ": " .. tostring(content)
end
_with_0:close()
end
return content
end
local readTeal
readTeal = function(file)
local content
do
local _with_0 = fs.safeOpen(file, "r")
if _with_0.error then
return nil, "Could not open " .. tostring(file) .. ": " .. tostring(_with_0.error)
end
local init_env, gen
do
local _obj_0 = require("tl")
init_env, gen = _obj_0.init_env, _obj_0.gen
end
local gwe = init_env(true, false)
content = gen((_with_0:read("*a")), gwe)
if not (content) then
return nil, "Could not read " .. tostring(file) .. ": " .. tostring(content)
end
_with_0:close()
end
return content
end
return {
readMoon = readMoon,
readLua = readLua,
readTeal = readTeal
}
end
end
do
local _ENV = _ENV
package.preload[ "alfons.getopt" ] = function( ... ) local arg = _G.arg;
local getopt
getopt = function(argl)
local args = {
commands = { }
}
local flags = {
stop = false,
command = false,
wait = false
}
local push
push = function(o, v)
if flags.command then
args[flags.command][o] = v
else
args[o] = v
end
end
for _index_0 = 1, #argl do
local _continue_0 = false
repeat
local arg = argl[_index_0]
if arg == "--" then
flags.stop = true
end
if flags.stop then
table.insert(args, arg)
_continue_0 = true
break
end
if flags.wait then
push(flags.wait, arg)
flags.wait = false
_continue_0 = true
break
end
if not (arg:match("^%-%-?")) then
args[arg] = { }
flags.command = arg
table.insert(args.commands, arg)
_continue_0 = true
break
end
do
local flag = arg:match("^%-(%w)$")
if flag then
flags.wait = flag
_continue_0 = true
break
end
end
do
local flagl = arg:match("^%-(%w+)$")
if flagl then
for chr in flagl:gmatch(".") do
push(chr, true)
end
_continue_0 = true
break
end
end
if arg:match("^%-%-?(%w+)=(.+)$") then
local opt, value = arg:match("^%-%-?(%w+)=(.+)")
push(opt, value)
_continue_0 = true
break
end
do
local opt = arg:match("^%-%-(%w+)$")
if opt then
flags.wait = opt
end
end
_continue_0 = true
until true
if not _continue_0 then
break
end
end
if flags.wait then
push(flags.wait, true)
end
return args
end
return {
getopt = getopt
}
end
end
do
local _ENV = _ENV
package.preload[ "alfons.init" ] = function( ... ) local arg = _G.arg;
local ENVIRONMENT, loadEnv
do
local _obj_0 = require("alfons.env")
ENVIRONMENT, loadEnv = _obj_0.ENVIRONMENT, _obj_0.loadEnv
end
local getopt
getopt = require("alfons.getopt").getopt
local look
look = require("alfons.look").look
local provide = require("alfons.provide")
local unpack = unpack or table.unpack
local sanitize, PREFIX, initEnv, runString
sanitize = function(pattern)
if pattern then
return pattern:gsub("[%(%)%.%%%+%-%*%?%[%]%^%$]", "%%%0")
end
end
PREFIX = "alfons.tasks."
initEnv = function(run, base, genv, modname, pretty)
if base == nil then
base = ENVIRONMENT
end
if modname == nil then
modname = "main"
end
if pretty == nil then
pretty = false
end
local env, envmt = { }, { }
local tasksmt
env.tasks, tasksmt = { }, { }
setmetatable(env, envmt)
setmetatable(env.tasks, tasksmt)
envmt.__index = function(self, k)
if genv and k == "__ran" then
return (getmetatable(genv[modname])).__ran
elseif genv and k == "store" then
return (getmetatable(genv)).store
else
return base[k] or provide[k]
end
end
envmt.__newindex = function(self, k, v)
if "function" ~= type(v) then
error("Task '" .. tostring(k) .. "' is not a function.")
end
self.tasks[k] = function(t)
if t == nil then
t = { }
end
return run(k, v, t)
end
end
tasksmt.__index = function(self, k)
return (rawget(self, k)) or (function()
for scope, t in pairs(genv) do
for name, task in pairs(t.tasks) do
if k == name then
return task
end
end
end
if pretty then
provide.printError("Task '" .. tostring(k) .. "' does not exist.")
return os.exit(1)
else
return error("Task '" .. tostring(k) .. "' does not exist.")
end
end)()
end
envmt.__ran = 0
return env
end
runString = function(content, environment, runAlways, child, genv, rqueue, pretty)
if environment == nil then
environment = ENVIRONMENT
end
if runAlways == nil then
runAlways = true
end
if child == nil then
child = 0
end
if genv == nil then
genv = { }
end
if rqueue == nil then
rqueue = { }
end
if pretty == nil then
pretty = false
end
if not ("string" == type(content)) then
return nil, "Taskfile content must be a string"
end
local modname
if (not content:match("\n")) and (content:match("^" .. tostring(sanitize(PREFIX)))) then
modname = content
local contentErr
content, contentErr = look(content)
if contentErr then
return nil, contentErr
end
else
modname = "main"
end
if genv[modname] then
return genv[modname]
end
local run
run = function(name, task, argl)
(getmetatable(genv[modname])).__ran = (getmetatable(genv[modname])).__ran + 1
local self = setmetatable({ }, {
__index = argl
})
self.name = name
self.task = function()
return run(name, task, argl)
end
local callstack = (getmetatable(genv)).store.callstack
table.insert(callstack, name)
local ret = task(self)
table.remove(callstack, #callstack)
return ret
end
if not (getmetatable(genv)) then
setmetatable(genv, {
store = {
callstack = { }
}
})
end
local env = initEnv(run, environment, genv, modname, pretty)
genv[modname] = env
local alf, alfErr = loadEnv(content, env)
if alfErr then
return nil, "Could not load Taskfile " .. tostring(child) .. ": " .. tostring(alfErr)
end
return function(...)
local argl = {
...
}
local args = getopt(argl)
rawset(env, "args", args)
rawset(env, "uses", function(cmdmd)
return provide.contains((args.commands or { }), cmdmd)
end)
rawset(env, "exists", function(wants)
for scope, t in pairs(genv) do
for name, task in pairs(t.tasks) do
if wants == name then
return true
end
end
end
return false
end)
rawset(env, "calls", function(cmdmd)
local callstack = (getmetatable(genv)).store.callstack
local current = callstack[#callstack]
local on = false
local subcommands = { }
local i = 0
local _list_0 = args.commands
for _index_0 = 1, #_list_0 do
local cmd = _list_0[_index_0]
i = i + 1
if on then
if rawget(env.tasks, cmd) then
break
end
subcommands[#subcommands + 1] = cmd
args.commands[i] = nil
else
if cmd == current then
on = true
end
end
end
do
local _accum_0 = { }
local _len_0 = 1
for i, e in provide.npairs(args.commands) do
_accum_0[_len_0] = e
_len_0 = _len_0 + 1
end
args.commands = _accum_0
end
return subcommands
end)
local list = alf(args)
local tasks = list and (list.tasks and list.tasks or { }) or { }
for k, v in pairs(tasks) do
env.tasks[k] = function(t)
if t == nil then
t = { }
end
return run(k, v, t)
end
end
do
local fintask = (rawget(env.tasks, "finalize"))
if fintask then
rqueue[#rqueue + 1] = fintask
end
end
rawset(env, "load", function(mod)
mod = PREFIX .. mod
if genv[mod] then
return genv[mod]
end
local subalf, subalfErr = runString(mod, env, runAlways, child + 1, genv, rqueue)
if subalfErr then
error(subalfErr)
end
local subenv = subalf(unpack(argl))
local tasksmt = getmetatable(env.tasks)
tasksmt.__index = function(self, k)
return (rawget(self, k)) or (function()
for scope, t in pairs(genv) do
for name, task in pairs(t.tasks) do
if k == name then
return task
end
end
end
if pretty then
provide.printError("Task '" .. tostring(k) .. "' does not exist.")
return os.exit(1)
else
return error("Task '" .. tostring(k) .. "' does not exist.")
end
end)()
end
local subtasksmt = getmetatable(subenv.tasks)
subtasksmt.__index = function(self, k)
return (rawget(self, k)) or (function()
for scope, t in pairs(genv) do
for name, task in pairs(t.tasks) do
if k == name then
return task
end
end
end
if pretty then
provide.printError("Task '" .. tostring(k) .. "' does not exist.")
return os.exit(1)
else
return error("Task '" .. tostring(k) .. "' does not exist.")
end
end)()
end
end)
if runAlways and (rawget(env.tasks, "always")) then
(rawget(env.tasks, "always"))();
(getmetatable(genv[modname])).__ran = (getmetatable(genv[modname])).__ran - 1
end
rawset(env, "finalize", function()
for scope, t in pairs(genv) do
if (rawget(t.tasks, "default")) and t.__ran < 1 then
(rawget(t.tasks, "default"))()
end
end
for i = #rqueue, 1, -1 do
rqueue[i]()
end
end)
return env
end
end
return {
runString = runString,
initEnv = initEnv
}
end
end
do
local _ENV = _ENV
package.preload[ "alfons.look" ] = function( ... ) local arg = _G.arg;
local readMoon, readLua
do
local _obj_0 = require("alfons.file")
readMoon, readLua = _obj_0.readMoon, _obj_0.readLua
end
local fs = require("filekit")
local sanitize
sanitize = function(pattern)
if pattern == nil then
pattern = ""
end
return pattern:gsub("[%(%)%.%%%+%-%*%?%[%]%^%$]", "%%%0")
end
local dirsep, pathsep, wildcard = package.config:match("^(.)\n(.)\n(.)")
local modsep = "%."
local swildcard = sanitize(wildcard)
local makeLook
makeLook = function(gpath)
if gpath == nil then
gpath = package.path
end
local paths
do
local _accum_0 = { }
local _len_0 = 1
for path in gpath:gmatch("[^" .. tostring(pathsep) .. "]+") do
_accum_0[_len_0] = path
_len_0 = _len_0 + 1
end
paths = _accum_0
end
local moonpaths
do
local _accum_0 = { }
local _len_0 = 1
for path in gpath:gmatch("[^" .. tostring(pathsep) .. "]+") do
_accum_0[_len_0] = path:gsub("%.lua$", ".moon")
_len_0 = _len_0 + 1
end
moonpaths = _accum_0
end
return function(name)
local mod = name:gsub(modsep, dirsep)
local file = false
for _index_0 = 1, #paths do
local path = paths[_index_0]
local pt = path:gsub(swildcard, mod)
if fs.exists(pt) then
file = pt
end
end
for _index_0 = 1, #moonpaths do
local path = moonpaths[_index_0]
local pt = path:gsub(swildcard, mod)
if fs.exists(pt) then
file = pt
end
end
if file then
local read = (file:match("%.lua$")) and readLua or readMoon
local content, contentErr = read(file)
if content then
return content
else
return nil, contentErr
end
else
return nil, tostring(name) .. " not found."
end
end
end
return {
makeLook = makeLook,
look = makeLook()
}
end
end
do
local _ENV = _ENV
package.preload[ "alfons.provide" ] = function( ... ) local arg = _G.arg;
local style
style = require("ansikit.style").style
local fs = require("filekit")
local unpack = unpack or table.unpack
local printerr
printerr = function(t)
return io.stderr:write(t .. "\n")
end
local inotify
do
local ok
ok, inotify = pcall(function()
return require("inotify")
end)
inotify = ok and inotify or nil
end
local contains
contains = function(t, v)
return #(function()
local _accum_0 = { }
local _len_0 = 1
for _index_0 = 1, #t do
local vv = t[_index_0]
if vv == v then
_accum_0[_len_0] = vv
_len_0 = _len_0 + 1
end
end
return _accum_0
end)() ~= 0
end
local prints
prints = function(...)
return printerr(unpack((function(...)
local _accum_0 = { }
local _len_0 = 1
local _list_0 = {
...
}
for _index_0 = 1, #_list_0 do
local arg = _list_0[_index_0]
_accum_0[_len_0] = style(arg)
_len_0 = _len_0 + 1
end
return _accum_0
end)(...)))
end
local printError
printError = function(text)
return printerr(style("%{red}" .. tostring(text)))
end
local readfile
readfile = function(file)
do
local _with_0 = fs.safeOpen(file, "r")
if _with_0.error then
error(_with_0.error)
else
local contents = _with_0:read("*a")
_with_0:close()
return contents
end
return _with_0
end
end
local writefile
writefile = function(file, content)
do
local _with_0 = fs.safeOpen(file, "w")
if _with_0.error then
error(_with_0.error)
else
_with_0:write(content)
_with_0:close()
end
return _with_0
end
end
local serialize
serialize = function(t)
local full = "return {\n"
for k, v in pairs(t) do
full = full .. " ['" .. tostring(k) .. "'] = '" .. tostring(v) .. "',"
end
full = full .. "}"
return full
end
local ask
ask = function(str)
io.write(style(str))
return io.read()
end
local show
show = function(str)
return prints("%{cyan}:%{white} " .. tostring(str))
end
local env = setmetatable({ }, {
__index = function(self, i)
return os.getenv(i)
end
})
local cmd = os.execute
local sh = cmd
local cmdfail
cmdfail = function(str)
local code = cmd(str)
if not (code == 0) then
return os.exit(code)
end
end
local shfail = cmdfail
local basename
basename = function(file)
return file:match("(.+)%..+")
end
local filename
filename = function(file)
return file:match(".+/(.+)%..+")
end
local extension
extension = function(file)
return file:match(".+%.(.+)")
end
local pathname
pathname = function(file)
return file:match("(.+/).+")
end
local isAbsolute
isAbsolute = function(path)
return path:match("^/")
end
local wildcard = fs.iglob
local iwildcard
iwildcard = function(paths)
local all = { }
for _index_0 = 1, #paths do
local path = paths[_index_0]
for globbed in fs.iglob(path) do
table.insert(all, globbed)
end
end
local i, n = 0, #all
return function()
i = i + 1
if i <= n then
return all[i]
end
end
end
local glob
glob = function(glob)
return function(path)
return fs.matchGlob((fs.fromGlob(glob)), path)
end
end
local build
build = function(iter, fn)
local times = { }
if fs.exists(".alfons") then
prints("%{cyan}:%{white} using .alfons")
times = dofile(".alfons")
do
local _tbl_0 = { }
for k, v in pairs(times) do
_tbl_0[k] = tonumber(v)
end
times = _tbl_0
end
end
for file in iter do
local mtime = fs.getLastModification(file)
if times[file] then
if mtime > times[file] then
fn(file)
end
times[file] = mtime
else
fn(file)
times[file] = mtime
end
end
return writefile(".alfons", serialize(times))
end
local EVENTS = {
access = "IN_ACCESS",
change = "IN_ATTRIB",
write = "IN_CLOSE_WRITE",
shut = "IN_CLOSE_NOWRITE",
close = "IN_CLOSE",
create = "IN_CREATE",
delete = "IN_DELETE",
destruct = "IN_DELETE_SELF",
modify = "IN_MODIFY",
migrate = "IN_MOVE_SELF",
move = "IN_MOVE",
movein = "IN_MOVED_TO",
moveout = "IN_MOVED_FROM",
open = "IN_OPEN",
all = "IN_ALL_EVENTS"
}
local bit_band
bit_band = function(a, b)
local result, bitval = 0, 1
while a > 0 and b > 0 do
if a % 2 == 1 and b % 2 == 1 then
result = result + bitval
end
bitval = bitval * 2
a = math.floor(a / 2)
b = math.floor(b / 2)
end
return result
end
local watch
watch = function(dirs, exclude, evf, pred, fn)
if not (inotify) then
error("Could not load inotify")
end
local handle = inotify.init()
if evf == "live" then
evf = {
"write",
"movein"
}
end
local cdir = fs.currentDir()
for i, dir in ipairs(dirs) do
if not (isAbsolute(dir)) then
dirs[i] = fs.reduce(fs.combine(cdir, dir))
end
end
for i, dir in ipairs(exclude) do
if not (isAbsolute(dir)) then
exclude[i] = fs.reduce(fs.combine(cdir, dir))
end
end
for i, dir in ipairs(dirs) do
for ii, subdir in ipairs(fs.listAll(dir)) do
local _continue_0 = false
repeat
local br8k = false
for _index_0 = 1, #exclude do
local exclusion = exclude[_index_0]
if subdir:match("^" .. tostring(exclusion)) then
br8k = true
end
end
if br8k then
_continue_0 = true
break
end
if fs.isDir(subdir) then
table.insert(dirs, subdir)
end
_continue_0 = true
until true
if not _continue_0 then
break
end
end
end
prints("%{cyan}:%{white} Watching for:")
for _index_0 = 1, #dirs do
local dir = dirs[_index_0]
prints(" - %{green}" .. tostring(dir))
end
local events
do
local _accum_0 = { }
local _len_0 = 1
for _index_0 = 1, #evf do
local ev = evf[_index_0]
_accum_0[_len_0] = inotify[EVENTS[ev]]
_len_0 = _len_0 + 1
end
events = _accum_0
end
local uevf
do
local _tbl_0 = { }
for k, v in pairs(evf) do
_tbl_0[k] = v
end
uevf = _tbl_0
end
if not (contains(evf, "create")) then
table.insert(evf, "create")
table.insert(events, inotify.IN_CREATE)
end
local watchers = { }
for _index_0 = 1, #dirs do
local dir = dirs[_index_0]
watchers[dir] = handle:addwatch(dir, unpack(events))
end
local reversed
do
local _tbl_0 = { }
for k, v in pairs(watchers) do
_tbl_0[v] = k
end
reversed = _tbl_0
end
while true do
local evts = handle:read()
if not (evts) then
break
end
for _index_0 = 1, #evts do
local _continue_0 = false
repeat
local ev = evts[_index_0]
local full = fs.combine(reversed[ev.wd], (ev.name or ""))
if (fs.isDir(full)) and (bit_band(ev.mask, inotify.IN_CREATE)) and not watchers[full] then
prints("%{cyan}:%{white} Added to watchlist: %{green}" .. tostring(full))
watchers[full] = handle:addwatch(full, unpack(events))
reversed[watchers[full]] = full
end
local actions = { }
for action, evt in pairs(EVENTS) do
local _continue_0 = false
repeat
if action == "all" then
_continue_0 = true
break
end
if 0 ~= bit_band(ev.mask, inotify[evt]) then
if contains(uevf, action) then
table.insert(actions, action)
end
end
_continue_0 = true
until true
if not _continue_0 then
break
end
end
if #actions == 0 then
_continue_0 = true
break
end
if not (pred(full, actions)) then
_continue_0 = true
break
end
prints("%{cyan}:%{white} Triggered %{magenta}" .. tostring(table.concat(actions, ', ')) .. "%{white}: %{yellow}" .. tostring(full))
fn(full, actions)
_continue_0 = true
until true
if not _continue_0 then
break
end
end
end
return handle:close()
end
local npairs
npairs = function(t)
local keys
do
local _accum_0 = { }
local _len_0 = 1
for k, v in pairs(t) do
if "number" == type(k) then
_accum_0[_len_0] = k
_len_0 = _len_0 + 1
end
end
keys = _accum_0
end
table.sort(keys)
local i = 0
local n = #keys
return function()
i = i + 1
if i <= n then
return keys[i], t[keys[i]]
end
end
end
return {
contains = contains,
prints = prints,
printError = printError,
readfile = readfile,
writefile = writefile,
serialize = serialize,
cmd = cmd,
cmdfail = cmdfail,
sh = sh,
shfail = shfail,
wildcard = wildcard,
iwildcard = iwildcard,
glob = glob,
basename = basename,
filename = filename,
extension = extension,
pathname = pathname,
build = build,
watch = watch,
env = env,
ask = ask,
show = show,
npairs = npairs
}
end
end
do
local _ENV = _ENV
package.preload[ "alfons.setfenv" ] = function( ... ) local arg = _G.arg;
return setfenv or function(fn, env)
local i = 1
while true do
local name = debug.getupvalue(fn, i)
if name == "_ENV" then
debug.upvaluejoin(fn, i, (function()
return env
end), 1)
elseif not name then
break
end
i = i + 1
end
return fn
end
end
end
do
local _ENV = _ENV
package.preload[ "alfons.tasks.fetch" ] = function( ... ) local arg = _G.arg;
return {
tasks = {
fetch = function(self)
local http = require("http.request")
local headers, stream = assert((http.new_from_uri(self.url)):go())
local body = assert(stream:get_body_as_string())
if "200" ~= headers:get(":status") then
return error(body)
else
return body
end
end
}
}
end
end
do
local _ENV = _ENV
package.preload[ "alfons.tasks.teal" ] = function( ... ) local arg = _G.arg;
return {
tasks = {
always = function(self)
load("fetch")
if not (store.teal_auto == true) then
tasks.install()
return tasks.typings({
modules = store.typings
})
end
end,
install = function(self)
if exists("teal_preinstall") then
prints("%{cyan}Teal:%{white} Running pre-install hook.")
tasks.teal_preinstall()
end
prints("%{cyan}Teal:%{white} Installing dependencies.")
local _list_0 = store.dependencies
for _index_0 = 1, #_list_0 do
local dep = _list_0[_index_0]
prints("%{green}+ " .. tostring(dep))
sh("luarocks install " .. tostring(dep))
end
if exists("teal_postinstall") then
prints("%{cyan}Teal:%{white} Running post-install hook.")
return tasks.teal_postinstall()
end
end,
build = function(self)
if exists("teal_prebuild") then
prints("%{cyan}Teal:%{white} Running pre-build hook.")
tasks.teal_prebuild()
end
prints("%{cyan}Teal:%{white} Building project.")
sh("tl build")
if exists("teal_postbuild") then
prints("%{cyan}Teal:%{white} Running post-build hook.")
return tasks.teal_postbuild()
end
end,
typings = function(self)
local json = require("dkjson")
local fetchdefs
fetchdefs = function(mod)
prints("%{cyan}Teal:%{white} Fetching type definitions for " .. tostring(mod) .. ".")
local unjson = tasks.fetch({
url = "https://api.github.com/repos/teal-language/teal-types/contents/types/" .. tostring(mod)
})
local files = json.decode(unjson)
for _index_0 = 1, #files do
local _continue_0 = false
repeat
local file = files[_index_0]
if not (file.type == "file") then
_continue_0 = true
break
end
local name = file.name
local def = tasks.fetch({
url = "https://raw.githubusercontent.com/teal-language/teal-types/master/types/" .. tostring(mod) .. "/" .. tostring(name)
})
writefile(name, def)
_continue_0 = true
until true
if not _continue_0 then
break
end
end
end
local mod = self.m or self.module
local mods = self.modules
if mod then
return fetchdefs(mod)
elseif mods then
local _list_0 = mods
for _index_0 = 1, #_list_0 do
local md = _list_0[_index_0]
fetchdefs(md)
end
end
end
}
}
end
end
do
local _ENV = _ENV
package.preload[ "alfons.version" ] = function( ... ) local arg = _G.arg;
return {
VERSION = "4.4.1"
}
end
end
local VERSION
VERSION = require("alfons.version").VERSION
local style
style = require("ansikit.style").style
local fs = require("filekit")
local unpack = unpack or table.unpack
local printerr
printerr = function(t)
return io.stderr:write(t .. "\n")
end
local prints
prints = function(...)
return printerr(unpack((function(...)
local _accum_0 = { }
local _len_0 = 1
local _list_0 = {
...
}
for _index_0 = 1, #_list_0 do
local arg = _list_0[_index_0]
_accum_0[_len_0] = style(arg)
_len_0 = _len_0 + 1
end
return _accum_0
end)(...)))
end
local printError
printError = function(text)
return printerr(style("%{red}" .. tostring(text)))
end
local errors
errors = function(code, msg)
printerr(style("%{red}" .. tostring(msg)))
return os.exit(code)
end
prints("%{bold blue}Alfons " .. tostring(VERSION))
local getopt
getopt = require("alfons.getopt").getopt
local args = getopt({
...
})
local FILE
do
if args.f then
FILE = args.f
elseif args.file then
FILE = args.file
elseif fs.exists("Alfons.lua") then
FILE = "Alfons.lua"
elseif fs.exists("Alfons.moon") then
FILE = "Alfons.moon"
elseif fs.exists("Alfons.tl") then
FILE = "Alfons.tl"
else
FILE = errors(1, "No Taskfile found.")
end
end
local LANGUAGE
do
if FILE:match("moon$") then
LANGUAGE = "moon"
elseif FILE:match("lua$") then
LANGUAGE = "lua"
elseif FILE:match("tl$") then
LANGUAGE = "teal"
elseif args.type then
LANGUAGE = args.type
else
LANGUAGE = errors(1, "Cannot resolve format for Taskfile.")
end
end
printerr("Using " .. tostring(FILE) .. " (" .. tostring(LANGUAGE) .. ")")
local readMoon, readLua, readTeal
do
local _obj_0 = require("alfons.file")
readMoon, readLua, readTeal = _obj_0.readMoon, _obj_0.readLua, _obj_0.readTeal
end
local content, contentErr
local _exp_0 = LANGUAGE
if "moon" == _exp_0 then
content, contentErr = readMoon(FILE)
elseif "lua" == _exp_0 then
content, contentErr = readLua(FILE)
elseif "teal" == _exp_0 then
content, contentErr = readTeal(FILE)
else
content, contentErr = errors(1, "Cannot resolve format '" .. tostring(LANGUAGE) .. "' for Taskfile.")
end
if not (content) then
errors(1, contentErr)
end
local runString
runString = require("alfons.init").runString
local alfons, alfonsErr = runString(content, nil, true, 0, { }, { }, true)
if not (alfons) then
errors(1, alfonsErr)
end
local env = alfons(...)
local _list_0 = args.commands
for _index_0 = 1, #_list_0 do
local command = _list_0[_index_0]
env.tasks[command](args[command])
if rawget(env.tasks, "teardown") then
local _ = (rawget(env.tasks, "teardown"))
end
end
return env.finalize()
|
-- example of printing Moose:RANGE scores to discord.
-- Requires:
-- Mist
-- Moose
-- HypeMan
assert(loadfile("C:/HypeMan/mist.lua"))()
assert(loadfile("C:/HypeMan/Moose.lua"))()
assert(loadfile("C:/HypeMan/HypeMan.lua"))()
assert(loadfile("C:/HypeMan/target_range/target_range.lua"))()
|
--[[
NetStream - 2.1.0
Alexander Grist-Hucker
http://www.revotech.org
Credits to:
thelastpenguin for pON.
https://github.com/thelastpenguin/gLUA-Library/tree/master/pON
--]]
local net = net
local ErrorNoHalt = ErrorNoHalt
local pairs = pairs
local pcall = pcall
local type = type
local util = util
local _player = player
netstream = netstream or {}
local stored = netstream.stored or {}
netstream.stored = stored
local cache = netstream.cache or {}
netstream.cache = cache
if (DBugR) then
DBugR.Profilers.Netstream = table.Copy(DBugR.SP)
DBugR.Profilers.Netstream.CChan = ""
DBugR.Profilers.Netstream.Name = "Netstream"
DBugR.Profilers.Netstream.Type = SERVICE_PROVIDER_TYPE_NET
DBugR.Profilers.NetstreamPerf = table.Copy(DBugR.SP)
DBugR.Profilers.NetstreamPerf.Name = "Netstream"
DBugR.Profilers.NetstreamPerf.Type = SERVICE_PROVIDER_TYPE_CPU
end
-- A function to split data for a data stream.
function netstream.Split(data)
local index = 1
local result = {}
local buffer = {}
for i = 0, string.len(data) do
buffer[#buffer + 1] = string.sub(data, i, i)
if (#buffer == 32768) then
result[#result + 1] = table.concat(buffer)
index = index + 1
buffer = {}
end
end
result[#result + 1] = table.concat(buffer)
return result
end
--[[
@codebase Shared
@details A function to hook a data stream.
@param String A unique identifier.
@param Function The datastream callback.
--]]
function netstream.Hook(name, Callback)
stored[name] = Callback
end
if (DBugR) then
local oldDS = netstream.Hook
for name, func in pairs(stored) do
stored[name] = nil
oldDS(name, DBugR.Util.Func.AttachProfiler(func, function(time)
DBugR.Profilers.NetstreamPerf:AddPerformanceData(tostring(name), time, func)
end))
end
netstream.Hook = DBugR.Util.Func.AddDetourM(netstream.Hook, function(name, func, ...)
func = DBugR.Util.Func.AttachProfiler(func, function(time)
DBugR.Profilers.NetstreamPerf:AddPerformanceData(tostring(name), time, func)
end)
return name, func, ...
end)
end
if (SERVER) then
util.AddNetworkString("NetStreamDS")
util.AddNetworkString("NetStreamHeavy")
-- A function to start a net stream.
function netstream.Start(player, name, ...)
local recipients = {}
local bShouldSend = false
if (type(player) != "table") then
if (!player) then
player = _player.GetAll()
else
player = {player}
end
end
for k, v in ipairs(player) do
if (type(v) == "Player") then
recipients[#recipients + 1] = v
bShouldSend = true
end
end
local encodedData = pon.encode({...})
if (encodedData and #encodedData > 0 and bShouldSend) then
net.Start("NetStreamDS")
net.WriteString(name)
net.WriteUInt(#encodedData, 32)
net.WriteData(encodedData, #encodedData)
net.Send(recipients)
end
end
if (DBugR) then
netstream.Start = DBugR.Util.Func.AddDetour(netstream.Start, function(player, name, ...)
local encodedData = pon.encode({...})
DBugR.Profilers.Netstream:AddNetData(name, #encodedData)
end)
end
-- A function to start a > 64KB net stream.
local queue, nextSend = {}, 0
timer.Create('NetStreamHeavy', 0.05, 0, function()
if nextSend > CurTime() or #queue < 1 then return end
local msg = table.remove(queue, 1)
net.Start("NetStreamHeavy")
net.WriteString(msg[1])
net.WriteUInt(#msg[4], 32)
net.WriteData(msg[4], #msg[4])
net.WriteUInt(msg[3], 8)
net.WriteUInt(msg[2], 8)
net.Send(msg[5])
nextSend = CurTime() + 0.2
end)
function netstream.Heavy(player, name, ...)
local recipients = {}
local bShouldSend = false
if (type(player) != "table") then
if (!player) then
player = _player.GetAll()
else
player = {player}
end
end
for k, v in ipairs(player) do
if (type(v) == "Player") then
recipients[#recipients + 1] = v
bShouldSend = true
end
end
local encodedData = pon.encode({...})
local split = netstream.Split(encodedData)
if (encodedData and #encodedData > 0 and bShouldSend) then
for k, v in ipairs(split) do
queue[#queue + 1] = {name, #split, k, v, recipients}
end
end
end
-- A function to listen for a request.
function netstream.Listen(name, Callback)
netstream.Hook(name, function(player, data)
local bShouldReply, reply = Callback(player, data)
if (bShouldReply) then
netstream.Start(player, name, reply)
end
end)
end
net.Receive("NetStreamDS", function(length, player)
local NS_DS_NAME = net.ReadString()
local NS_DS_LENGTH = net.ReadUInt(32)
local NS_DS_DATA = net.ReadData(NS_DS_LENGTH)
if (NS_DS_NAME and NS_DS_DATA and NS_DS_LENGTH) then
player.nsDataStreamName = NS_DS_NAME
player.nsDataStreamData = ""
if (player.nsDataStreamName and player.nsDataStreamData) then
player.nsDataStreamData = NS_DS_DATA
if (stored[player.nsDataStreamName]) then
local bStatus, value = pcall(pon.decode, player.nsDataStreamData)
if (bStatus) then
stored[player.nsDataStreamName](player, unpack(value))
else
ErrorNoHalt("NetStream: '"..NS_DS_NAME.."'\n"..value.."\n")
end
end
player.nsDataStreamName = nil
player.nsDataStreamData = nil
end
end
NS_DS_NAME, NS_DS_DATA, NS_DS_LENGTH = nil, nil, nil
end)
net.Receive("NetStreamHeavy", function(length, player)
local NS_DS_NAME = net.ReadString()
local NS_DS_LENGTH = net.ReadUInt(32)
local NS_DS_DATA = net.ReadData(NS_DS_LENGTH)
local NS_DS_PIECE = net.ReadUInt(8)
local NS_DS_TOTAL = net.ReadUInt(8)
if (NS_DS_NAME and NS_DS_DATA and NS_DS_LENGTH) then
player.nsDataStreamName = NS_DS_NAME
player.nsDataStreamData = ""
if (!cache[player.nsDataStreamName]) then
cache[player.nsDataStreamName] = ""
end
if (player.nsDataStreamName and player.nsDataStreamData) then
player.nsDataStreamData = NS_DS_DATA
if (NS_DS_PIECE < NS_DS_TOTAL) then
if (NS_DS_PIECE == 1) then
cache[player.nsDataStreamName] = ""
end
cache[player.nsDataStreamName] = cache[player.nsDataStreamName]..player.nsDataStreamData
else
cache[player.nsDataStreamName] = cache[player.nsDataStreamName]..player.nsDataStreamData
if (stored[player.nsDataStreamName]) then
local bStatus, value = pcall(pon.decode, cache[player.nsDataStreamName])
if (bStatus) then
stored[player.nsDataStreamName](player, unpack(value))
else
ErrorNoHalt("NetStream: '"..NS_DS_NAME.."'\n"..value.."\n")
end
end
cache[player.nsDataStreamName] = nil
player.nsDataStreamName = nil
player.nsDataStreamData = nil
end
end
end
NS_DS_NAME, NS_DS_DATA, NS_DS_LENGTH, NS_DS_PIECE, NS_DS_TOTAL = nil, nil, nil, nil, nil
end)
else
-- A function to start a net stream.
function netstream.Start(name, ...)
local encodedData = pon.encode({...})
if (encodedData and #encodedData > 0) then
net.Start("NetStreamDS")
net.WriteString(name)
net.WriteUInt(#encodedData, 32)
net.WriteData(encodedData, #encodedData)
net.SendToServer()
end
end
if (DBugR) then
netstream.Start = DBugR.Util.Func.AddDetour(netstream.Start, function(name, ...)
local encodedData = pon.encode({...})
DBugR.Profilers.Netstream:AddNetData(name, #encodedData)
end)
end
-- A function to start a net stream.
local queue, nextSend = {}, 0
timer.Create('NetStreamHeavy', 0.05, 0, function()
if nextSend > CurTime() or #queue < 1 then return end
local msg = table.remove(queue, 1)
net.Start("NetStreamHeavy")
net.WriteString(msg[1])
net.WriteUInt(#msg[4], 32)
net.WriteData(msg[4], #msg[4])
net.WriteUInt(msg[3], 8)
net.WriteUInt(msg[2], 8)
net.SendToServer()
nextSend = CurTime() + 0.2
end)
function netstream.Heavy(name, ...)
local dataTable = {...}
local encodedData = pon.encode(dataTable)
local split = netstream.Split(encodedData)
if (encodedData and #encodedData > 0) then
for k, v in ipairs(split) do
queue[#queue + 1] = {name, #split, k, v}
end
end
end
-- A function to send a request.
function netstream.Request(name, data, Callback)
netstream.Hook(name, Callback);
netstream.Start(name, data)
end
net.Receive("NetStreamDS", function(length)
local NS_DS_NAME = net.ReadString()
local NS_DS_LENGTH = net.ReadUInt(32)
local NS_DS_DATA = net.ReadData(NS_DS_LENGTH)
if (NS_DS_NAME and NS_DS_DATA and NS_DS_LENGTH) then
if (stored[NS_DS_NAME]) then
local bStatus, value = pcall(pon.decode, NS_DS_DATA)
if (bStatus) then
stored[NS_DS_NAME](unpack(value))
else
ErrorNoHalt("NetStream: '"..NS_DS_NAME.."'\n"..value.."\n")
end
end
end
NS_DS_NAME, NS_DS_DATA, NS_DS_LENGTH = nil, nil, nil
end)
net.Receive("NetStreamHeavy", function(length)
local NS_DS_NAME = net.ReadString()
local NS_DS_LENGTH = net.ReadUInt(32)
local NS_DS_DATA = net.ReadData(NS_DS_LENGTH)
local NS_DS_PIECE = net.ReadUInt(8)
local NS_DS_TOTAL = net.ReadUInt(8)
if (!cache[NS_DS_NAME]) then
cache[NS_DS_NAME] = ""
end
if (NS_DS_NAME and NS_DS_DATA and NS_DS_LENGTH) then
if (NS_DS_PIECE < NS_DS_TOTAL) then
if (NS_DS_PIECE == 1) then
cache[NS_DS_NAME] = ""
end
cache[NS_DS_NAME] = cache[NS_DS_NAME]..NS_DS_DATA
else
cache[NS_DS_NAME] = cache[NS_DS_NAME]..NS_DS_DATA
if (stored[NS_DS_NAME]) then
local bStatus, value = pcall(pon.decode, cache[NS_DS_NAME])
if (bStatus) then
stored[NS_DS_NAME](unpack(value))
else
ErrorNoHalt("NetStream Heavy: '"..NS_DS_NAME.."'\n"..value.."\n")
end
cache[NS_DS_NAME] = nil
end
end
end
NS_DS_NAME, NS_DS_DATA, NS_DS_LENGTH, NS_DS_PIECE, NS_DS_TOTAL = nil, nil, nil, nil, nil
end)
end |
#!/usr/bin/env texlua
--------------------------------------------------------------------------------
-- FILE: cyrillicnumbers.lua
-- USAGE: called by t-cyrillicnumbers.mkvi
-- DESCRIPTION: part of the Cyrillic Numbers module for ConTeXt
-- REQUIREMENTS: recent ConTeXt MkIV and LuaTeX
-- AUTHOR: Philipp Gesang (phg), <phg42 dot 2a at gmail dot com>
-- VERSION: hg tip
-- CHANGED: 2013-03-28 00:10:47+0100
--------------------------------------------------------------------------------
--
--[[ldx--
<p>read this first:</p>
<p>Жолобов, О. Ф.: <key>Числительные</key>. In: <key>Историческая
грамматика древнерусского языка</key>, vol. 4, Moskva
2006, pp. 58--63</p>
<p>Trunte, Nikolaos H.: <key>Altkirchenslavisch</key>. In:
<key>Словѣньскъи ѩꙁъікъ. Ein praktisches Lehrbuch
des Kirchenslavischen in 30 Lektionen. Zugleich eine
Einführung in die slavische Philologie</key>, vol.
1, München ⁵2005, pp. 161ff.</p>
<p>or have a glance at these:</p>
<typing>
http://www.pravpiter.ru/zads/n018/ta013.htm
http://www.uni-giessen.de/partosch/eurotex99/berdnikov2.pdf
http://ru.wikipedia.org/wiki/Кириллическая_система_счисления
</typing>
--ldx]]--
local iowrite = io.write
local mathceil = math.ceil
local mathfloor = math.floor
local stringformat = string.format
local tableconcat = table.concat
local tableinsert = table.insert
local tostring = tostring
local type = type
local utf8char = unicode.utf8.char
local utf8len = unicode.utf8.len
local cyrnum = {
placetitlo = "font",
prefer100k = false,
titlolocation = "final", -- above final digit
titlospan = 3, -- only with mp
drawdots = true,
debug = false,
}
thirddata = thirddata or { }
thirddata.cyrnum = cyrnum
local dbgpfx = "[cyrnum]"
local dbg = function (...)
if cyrnum.debug then
local args = {...}
if type(args[1]) == "table" then args = args[1] end
iowrite(dbgpfx)
for i=1, #args do
local this = args[i]
local tthis = type(this)
iowrite" "
if tthis == "number" or tthis == "string" then
iowrite(this)
else
iowrite(tostring(this))
end
end
iowrite"\n"
end
end
local cyrillic_numerals = {
{ "а", "в", "г", "д", "е", "ѕ", "з", "и", "ѳ", },
{ "і", "к", "л", "м", "н", "ѯ", "о", "п", "ч", },
{ "р", "с", "т", "у", "ф", "х", "ѱ", "ѡ", "ц", },
}
local cyrillic_1k = "҂"
local cyrillic_100k = utf8char(0x488) -- combining hundred thousands sign
local cyrillic_1m = utf8char(0x489) -- combining million sign
local cyrillic_titlo = utf8char(0x483) -- combining titlo
--[[ldx--
<p>Some string synonyms for user convenience.</p>
--ldx]]--
cyrnum.yes_synonyms = {
yes = true,
yeah = true,
["true"] = true,
}
cyrnum.no_synonyms = {
no = true,
nope = true,
["false"] = true,
}
--[[ldx--
<p><type>m</type> for rounded down middle position, <type>l</type> for final
position. Will default to initial position otherwise.</p>
--ldx]]--
cyrnum.position_synonyms = {
final = "l",
last = "l",
right = "l",
rightmost = "l",
["false"] = "l",
middle = "m",
center = "m",
["true"] = "m",
}
--[[ldx--
<p>Digits above the thirds require special markers, some of which need to be
placed before, others after the determined character.</p>
--ldx]]--
local handle_plus1k = function (digit)
local before, after
if digit == 7 then
after = cyrillic_1m
elseif cyrnum.prefer100k and digit == 6 then
after = cyrillic_100k
elseif digit > 3 then -- insert thousand sign
before = cyrillic_1k
end
return before, after
end
-- digit list = {
-- [1] = character to be printed
-- [2] = real digit of character
-- [3] = print this before character (e.g. thousand signs)
-- [4] = print this after character (e.g. million signs)
-- }
--[[ldx--
<p>The base list of digits denotes empty (zero) digits with "false" values
instead of characters. The function <type>digits_only</type> will extract only
the nonempty digit values, returning a list.</p>
--ldx]]--
local digits_only = function (list)
local result = { }
for i=1, #list do
local elm = list[i]
if type(elm) == "string" then
local before, after
if i > 3 then
before, after = handle_plus1k(i)
end
result[#result+1] = { elm, i, before, after } -- i contains the real digit
end
end
return result
end
--[[ldx--
<p>The different ways for drawing the <italic>titlo</italic> are stored inside
a table. Basically, the options are to use the titlos symbol that is provided
by the font or to draw the titlo in <l n="metapost"/>.</p>
--ldx]]--
local lreverse = function(list)local r={}for i=#list,1,-1 do r[#r+1]=list[i]end return r end
local start_titlo, stop_titlo = [[\cyrnumdrawtitlo{]], "}"
local titlofuncs = {
font = function (list)
local result, titlopos = { }, #list
if cyrnum.titlolocation == "l" then
titlopos = 1
elseif cyrnum.titlolocation == "m" then
titlopos = mathceil(#list/2)
end
for i=#list, 1, -1 do
local char, digit, before, after = list[i][1], list[i][2], list[i][3], list[i][4]
if before then
result[#result+1] = before
end
result[#result+1] = char
if after then
result[#result+1] = after
end
if i == titlopos then
result[#result+1] = cyrillic_titlo
end
end
return result
end,
mp = function (list)
local result = { }
local titlospan = cyrnum.titlospan
local titlotype = cyrnum.titlotype
local titlostart = #list -- default to “all”
if titlotype == true then -- number
titlostart = (#list >= titlospan) and titlospan or #list
end
for i=#list, 1, -1 do
local char, digit, before, after = list[i][1], list[i][2], list[i][3], list[i][4]
--local char, digit, before, after = unpack(list[i])
if i == titlostart then
result[#result+1] = start_titlo
end
if before then
result[#result+1] = before
end
result[#result+1] = char
if after then
result[#result+1] = after
end
end
result[#result+1] = stop_titlo
return result
end,
no = function (list)
local result = { }
for i=#list, 1, -1 do
local char, digit, before, after = list[i][1], list[i][2], list[i][3], list[i][4]
if before then
result[#result+1] = before
end
result[#result+1] = char
if after then
result[#result+1] = after
end
end
return result
end,
}
--[[ldx--
<p>Concatenation of the digit list has to take into account different conditions: whether the user requests the dot markers to be added, whether a titlo is requested etc.</p>
--ldx]]--
local concat_cyrillic_nums = function (list)
local result = ""
local digits = digits_only(list) -- strip placeholders
local nlist, ndigits = #list, #digits
dbg(list)
--dbg(digits)
local titlo = titlofuncs[cyrnum.placetitlo]
if titlo then
result = tableconcat(titlo(digits))
if cyrnum.drawdots then
local sym = cyrnum.dotsymbol
result = sym .. result .. sym
end
end
dbg(result)
return result
end
local do_tocyrillic do_tocyrillic = function (n, result)
if n < 1000 then
local mod100 = n % 100
if #result == 0 and mod100 > 10 and mod100 < 20 then
result[#result+1] = "і"
result[#result+1] = cyrillic_numerals[1][mod100%10] or false
else
result[#result+1] = cyrillic_numerals[1][mathfloor(n%10)] or false
result[#result+1] = cyrillic_numerals[2][mathfloor((n%100)/10)] or false
end
result[#result+1] = cyrillic_numerals[3][mathfloor((n%1000)/100)] or false
else
result = do_tocyrillic(n%1000, result)
result = do_tocyrillic(mathfloor(n/1000), result)
end
return result
end
local tocyrillic = function (n)
local chars = do_tocyrillic(n, { })
return concat_cyrillic_nums(chars)
end
local Tocyrillic = function (n)
local chars = do_tocyrillic(n, { })
return concat_cyrillic_nums(chars, true)
end
converters.tocyrillic = tocyrillic
converters.cyrillicnumerals = tocyrillic
converters.Cyrillicnumerals = Tocyrillic
function commands.cyrillicnumerals (n) context(tocyrillic(n)) end
function commands.Cyrillicnumerals (n) context(Tocyrillic(n)) end
--- Fun ---------------------------------------------------------
local f_peano = [[suc(%s)]]
local do_topeano = function (n)
n = tonumber(n) or 0
if n == 0 then return "0" end
local result = stringformat(f_peano, 0)
if n == 1 then return result end
for i=2, n do
result = stringformat(f_peano, result)
end
return result
end
local s_churchp = [[λf.λx.\;]]
local s_church0 = [[x]]
local s_church1 = [[f\,x]]
local f_church = [[f(%s)]]
local do_tochurch = function (n)
if n == 0 then return s_churchp .. s_church0
elseif n == 1 then return s_churchp .. s_church1 end
local result = stringformat(f_church, s_church1)
for i=2, n do
result = stringformat(f_church, result)
end
return s_churchp .. result
end
converters.topeano = do_topeano
converters.tochurch = do_tochurch
commands.peanonumerals = function (n) context(do_topeano(n)) end
commands.churchnumerals = function (n) context.mathematics(do_tochurch(n)) end
-- vim:ft=lua:ts=2:sw=2:expandtab:fo=croql
|
-----------------------------------------------------------------------------
-- UDP sample: daytime protocol client
-- LuaSocket sample files
-- Author: Diego Nehab
-----------------------------------------------------------------------------
local socket = require"socket"
host = host or "127.0.0.1"
port = port or 13
if arg then
host = arg[1] or host
port = arg[2] or port
end
host = socket.dns.toip(host)
udp = socket.udp()
print("Using host '" ..host.. "' and port " ..port.. "...")
udp:setpeername(host, port)
udp:settimeout(3)
sent, err = udp:send("anything")
if err then print(err) os.exit() end
dgram, err = udp:receive()
if not dgram then print(err) os.exit() end
io.write(dgram)
|
return {
name = "Copper",
desc = "",
sprite = 'copper',
usage = 'wall'
}
|
-- Skybox alternative v0.46 by Ren712
-- Based on GTASA Skybox mod by Shemer
-- knoblauch700@o2.pl
local sphereObjScale=100 -- set object scale
local sphereShadScale={1,1,0.9} -- object scale in VS
local makeAngular=true -- set to true if you have spheric texture
local sphereTexScale={1,1,1} -- scale the texture in PS
local FadeEffect = true -- horizon effect fading
local SkyVis = 0.5 -- sky visibility vs fading fog ammount (0 - sky not visible )
-- color variables below
local ColorAdd=-0.15 -- 0 to -0.4 -- standard colors are too bright
local ColorPow=2 -- 1 to 2 -- contrast
local shadCloudsTexDisabled=false
local modelID=15057 -- that's probably the best model to replace ... or not
--setWeather(7) -- the chosen weather (you might delete that but choose a proper one)
setCloudsEnabled(false)
local skydome_shader = nil
local null_shader = nil
local skydome_texture = nil
local getLastTick,getLastTock = 0,0
function startShaderResource()
if salEffectEnabled then return end
skydome_shader = dxCreateShader ( "shaders/shader_skydome.fx",0,0,true,"object" )
null_shader = dxCreateShader ( "shaders/shader_null.fx" )
skydome_texture=dxCreateTexture("textures/skydome.jpg")
if not skydome_shader or not null_shader or not skydome_texture then
outputChatBox('Could not start Skybox alternative !',255,0,0)
return
else
end
setCloudsEnabled(false)
dxSetShaderValue ( skydome_shader, "gTEX", skydome_texture )
dxSetShaderValue ( skydome_shader, "gAlpha", 1 )
dxSetShaderValue ( skydome_shader, "makeAngular", makeAngular )
dxSetShaderValue ( skydome_shader, "gObjScale", sphereShadScale )
dxSetShaderValue ( skydome_shader, "gTexScale",sphereTexScale )
dxSetShaderValue ( skydome_shader, "gFadeEffect", FadeEffect )
dxSetShaderValue ( skydome_shader, "gSkyVis", SkyVis )
dxSetShaderValue ( skydome_shader, "gColorAdd", ColorAdd )
dxSetShaderValue ( skydome_shader, "gColorPow", ColorPow )
-- apply to texture
engineApplyShaderToWorldTexture ( skydome_shader, "skybox_tex" )
if shadCloudsTexDisabled then engineApplyShaderToWorldTexture ( null_shader, "cloudmasked*" ) end
txd_skybox = engineLoadTXD('models/skybox_model.txd')
engineImportTXD(txd_skybox, modelID)
dff_skybox = engineLoadDFF('models/skybox_model.dff', modelID)
engineReplaceModel(dff_skybox, modelID)
local cam_x,cam_y,cam_z = getElementPosition(getLocalPlayer())
skyBoxBoxa = createObject ( modelID, cam_x, cam_y, cam_z, 0, 0, 0, true )
setObjectScale(skyBoxBoxa,sphereObjScale)
setElementAlpha(skyBoxBoxa,1)
addEventHandler ( "onClientHUDRender", getRootElement (), renderSphere ) -- sky object
addEventHandler ( "onClientHUDRender", getRootElement (), renderTime ) -- time
applyWeatherInfluence()
salEffectEnabled = true
end
function stopShaderResource()
if not salEffectEnabled then return end
removeEventHandler ( "onClientHUDRender", getRootElement (), renderSphere ) -- sky object
removeEventHandler ( "onClientHUDRender", getRootElement (), renderTime ) -- time
if null_shader then
engineRemoveShaderFromWorldTexture ( null_shader, "cloudmasked*" )
destroyElement(null_shader)
null_shader=nil
end
engineRemoveShaderFromWorldTexture ( skydome_shader, "skybox_tex" )
destroyElement(skyBoxBoxa)
destroyElement(skydome_shader)
destroyElement(skydome_texture)
skyBoxBoxa=nil
skydome_shader=nil
skydome_texture=false
salEffectEnabled = false
end
lastWeather=0
function renderSphere()
-- Updates the position of the object
if getTickCount ( ) - getLastTock < 2 then return end
local cam_x, cam_y, cam_z, lx, ly, lz = getCameraMatrix()
if cam_z<=200 then setElementPosition ( skyBoxBoxa, cam_x, cam_y, 80,false )
else setElementPosition ( skyBoxBoxa, cam_x, cam_y, 80+cam_z-200,false ) end
local r1, g1, b1, r2, g2, b2 = getSkyGradient()
local skyBott = {r2/255, g2/255, b2/255, 1}
dxSetShaderValue ( skydome_shader, "gSkyBott", skyBott )
if getWeather()~=lastWeather then applyWeatherInfluence() end
lastWeather=getWeather()
getLastTock = getTickCount ()
end
function renderTime()
local hour, minute = getTime ( )
if getTickCount ( ) - getLastTick < 100 then return end
if not skydome_shader then return end
if hour >= 20 then
local dusk_aspect = ((hour-20)*60+minute)/240
dusk_aspect = 1-dusk_aspect
dxSetShaderValue ( skydome_shader, "gAlpha", dusk_aspect)
end
if hour <= 2 then
dxSetShaderValue ( skydome_shader, "gAlpha", 0)
end
if hour > 2 and hour <= 6 then
local dawn_aspect = ((hour-3)*60+minute)/180
dawn_aspect = dawn_aspect
dxSetShaderValue ( skydome_shader, "gAlpha", dawn_aspect)
end
if hour > 6 and hour < 20 then
dxSetShaderValue ( skydome_shader, "gAlpha", 1)
end
getLastTick = getTickCount ()
end
function applyWeatherInfluence()
setSunSize (0)
setSunColor(0, 0, 0, 0, 0, 0)
end |
if SERVER then
AddCSLuaFile()
AddCSLuaFile("pam/sh_init.lua")
AddCSLuaFile("pam/client/cl_init.lua")
AddCSLuaFile("pam/client/cl_pam.lua")
AddCSLuaFile("pam/sh_extension_handler.lua")
AddCSLuaFile("pam/client/cl_networking.lua")
AddCSLuaFile("pam/client/cl_commands.lua")
include("pam/sh_init.lua")
include("pam/server/sv_init.lua")
include("pam/server/sv_pam.lua")
include("pam/sh_extension_handler.lua")
include("pam/server/sv_networking.lua")
-- add special option resources
local special_icons = file.Find("materials/vgui/pam/special_options/*.vmt", "GAME")
for i = 1, #special_icons do
resource.AddFile("materials/vgui/pam/special_options/" .. special_icons[i])
end
else
include("pam/sh_init.lua")
include("pam/client/cl_init.lua")
include("pam/client/cl_pam.lua")
include("pam/sh_extension_handler.lua")
include("pam/client/cl_networking.lua")
include("pam/client/cl_commands.lua")
end
|
tutorial = {}
tutMap = {}
tutMap.width = 5
tutMap.height = 5
for i = 0, tutMap.width+1 do
tutMap[i] = {}
end
tutMap[1][1] = "C"
tutMap[2][1] = "C"
tutMap[2][2] = "C"
tutMap[2][3] = "C"
tutMap[3][2] = "C"
tutMap[4][2] = "C"
tutMap[5][2] = "C"
tutorialSteps = {}
currentStep = 1
currentStepTitle = ""
currentTutBox = nil
local CODE_variables1 = parseCode([[
-- объявление переменной "variable1":
variable1 = 10
-- а у этой имя variable2:
variable2 = 20
-- складываем их значения и записываем в variable3:
variable3 = variable1 + variable2
-- отображаем результат в консоли:
print(variable3) -- выведет 30
]])
local CODE_variables2 = parseCode([[
-- объявление переменной "variable1":
variable1 = 10
-- еще одна:
variable2 = "testing"
-- так не сработает
-- (такой код выдаст ошибку при загрузке)
variable3 = variable1 + variable2
]])
local CODE_variables3 = parseCode([[
-- добавление "5.1" к концу строки "Lua".
-- в результате получится "Lua 5.1".
myText = "Lua " .. 5.1
variable1 = 10
variable2 = "testing"
-- добавляем 10 в конец строки "testing":
variable3 = variable2 .. variable1
-- результат: "testing10"
]])
local CODE_counter = parseCode([[
function ai.init()
buyTrain(1,1)
-- создаём переменную "counter"
counter = 0
end
function ai.chooseDirection()
-- считаем развилки:
counter = counter + 1
-- выводим номер текущей развилки:
print("Junction number: " .. counter)
end
]])
local CODE_functions1 = parseCode([[
function myFunction(argument1, argument2, ... )
-- обрабатываем полученные аргументы
-- и возможно возвращаем какое-то значение
end
-- вызываем функцию с тремя аргументами:
myFunction(1, "test", "3")
]])
local CODE_functions2 = parseCode([[
function subtract(a, b)
c = a - b
return c
end
result = subtract(10, 5)
print(result) -- должно напечатать '5'
]])
local CODE_ifthenelse1 = parseCode([[
if EXPRESSION1 then
-- действия
elseif EXPRESSION2 then
-- еще действия
else
-- другие действия
end
-- код 'действия' будет выполняться только если
-- EXPRESSION1 принимает значение истины.
-- Скоро вы узнаете что такое EXPRESSION.
]])
local CODE_ifthenelse2 = parseCode([[
variable = 10
if variable == 10 then
print("Значение переменной 10...")
elseif variable > 10000 then
print("Значение переменной - большое число!")
else
print("Значение не 10 но и не очень большое...")
end
]])
local CODE_whileLoop = parseCode([[
width = 10
x = 0
--это выведет 3, затем 6, дальше 9, потом 12.
while x < width do
x = x + 3
print(x)
end
]])
local CODE_whileLoop2 = parseCode([[
function ai.chooseDirection()
-- считаем развилки:
counter = counter + 1
i = 0 -- новая числовая пременная
text = "" -- инициализируем пустую строку
while i < counter do
text = text .. "x"
i = i + 1
end
-- выводим результат:
print(text)
end
]])
local CODE_forLoop = parseCode([[
-- следующий код выведет числа от 1 до 10:
width = 10
for i = 1, width, 1 do
print(i)
end
-- а так - только чётные ( 2, 4, 6, 8, 10)
width = 10
for i = 2, width, 2 do
print(i)
end
]])
local CODE_loop3 = parseCode([[
i = 1
-- просматриваем список пассажиров:
while i <= #passengers do
-- у каждого есть имя, доступ к которому даёт
-- 'passengers[i].name', найдём одного с именем Скайвокер.
if passengers[i].name == "Скайвокер" then
print("Я нашел Люка!!")
break -- прерываем цикл!
end
i = i + 1
end
]])
local CODE_tables1 = parseCode([[
-- пример 1:
myTable = {var1=10, var2="lol", var3="a bear"}
-- пример 2: (допустимы переносы строк)
myTable = {
x_Pos = 10,
y_Pos = 20
}
-- пример 3:
hill1 = {slope="steep", snow=true, size=20}
hill2 = {slope="steep", snow=false, size=10}
]])
local CODE_tables2 = parseCode([[
myTable = {
x = 10,
y = 20
}
-- считаем среднее значение:
result = (myTable.x + myTable.y)/2
print(result)
-- должно вывести 15, потому, что (10+20)/2 = 15
]])
local CODE_tables3 = parseCode([[
myTable = { x = 10, y = 20 }
-- добавляем элемент с именем 'z':
myTable.z = 50
-- удаляем элемент с именем 'x':
myTable.x = nil
-- а это приведет к ошибке, потому, что 'x' уже нет:
a = myTable.x + 10
]])
local CODE_tables4 = parseCode([[
-- если вы опускаете имена полей, Lua автоматически
-- использует номера [1], [2], [3] и т.д.:
myList = {"Apples", "Are", "Red"}
print(myList[1]) -- выведет 'Apples'.
-- меняем "Red" на "Green":
myList[3] = "Green"
-- выведет: "ApplesAreGreen"
print(myList[1] .. myList[2] .. myList[3])
]])
local CODE_hintGoEast = parseCode([[
-- Попробуйте так:
function ai.chooseDirection()
print("I want to go East!")
return "E"
end
]])
local CODE_hintGoEastThenSouth = parseCode([[
function ai.init()
buyTrain(1,1)
counter = 0
end
function ai.chooseDirection()
counter = counter + 1
if counter == 1 then
print("First junction! Go East!")
return "E"
else
print("Go South!")
return "S"
end
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
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:
if currentTutBox then tutorialBox.remove(currentTutBox) end
currentTutBox = tutorialBox.new( TUT_BOX_X, TUT_BOX_Y, tutorialSteps[1].message, tutorialSteps[1].buttons )
STARTUP_MONEY = 25
timeFactor = 0.5
end
function tutorial.start()
aiFileName = "TutorialAI2.lua"
--ai.backupTutorialAI(aiFileName)
ai.createNewTutAI(aiFileName, fileContent)
stats.start( 1 )
tutMap.time = 0
map.print()
loadingScreen.reset()
loadingScreen.addSection("Новая карта")
loadingScreen.addSubSection("Новая карта", "Размер: " .. tutMap.width .. " на " .. tutMap.height)
loadingScreen.addSubSection("Новая карта", "Время: День")
loadingScreen.addSubSection("Новая карта", "Урок 2: Направо или налево?")
train.init()
train.resetImages()
ai.restart() -- make sure aiList is reset!
ok, msg = pcall(ai.new, AI_DIRECTORY .. aiFileName)
if not ok then
print("Err: " .. 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()
end
function tutorial.endRound()
end
local codeBoxX, codeBoxY = 0,0
local tutBoxX, tutBoxY = 0,0
--[[
function additionalInformation(text)
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
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 = "Куда едем?"
tutorialSteps[k].message = "Добро пожаловать во второй урок!\n\nЗдесь вы выучите:\n1) Как проезжать развилки\n2) Основы Lua\n3) Что делать с несколькими пассажирами\n"
--4) What VIPs are"
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Начать урок", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].stepTitle = "Lua: Переменные"
tutorialSteps[k].message = "Сейчас мы будем учиться программровать на Lua.\nТема довольно обширная, но я постараюсь приподнести всё сжато. Может показаться, что тут сразу очень иного информации для новичка, но не пугайтесь - не обязательно запоминать всё сразу...\n\tВ Lua вы можете создавать переменные, просто присваивая значения (справа от знака '=') имени (слева от '='). Посмотрите на пример в листинге."
tutorialSteps[k].event = function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_variables1)
end
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Далее", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "В переменных так же, можно хранить текст. Чтоб сказать Lua что строка должна обрабатываться как текст, вы должны заключить её в кавычки(\").\n\nСтоит заметить, что нельзя складывать текстовые данные с числами, потому, что Lua не знает как 'прибавлять' текст.\nКак всегда - смотрите пример в листинге справа."
tutorialSteps[k].event = function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_variables2)
end
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Доп. инфо", event = additionalInformation("Если вы программировали на других языках прежде, будте осторожны: Lua очень некритично относится к типам переменных. Вы можете присвоить числовое значение переменной, в которой до этого был текст и наоборот. Это не будет ошибкой, но вы сами можете потом запутаться."), inBetweenSteps = true}
tutorialSteps[k].buttons[3] = {name = "Дальше", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Если вы хотите соединить текст и строку вместе, следует поместить '..' между ними. В результате получится строка, которую можно хранить в другой переменной, выводить на консоль, или еще что-нибудь.\n\nКак всегда - пример в листинге."
tutorialSteps[k].event = function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_variables3)
end
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Далее", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Давайте попробуем это на практике!\nНапишем код, который будет считать развилки.\nКогда поезд подъезжает к развилке игра всегда пытается вызвать функцию 'ai.chooseDirection()' из вашего кода. Это значит, что если у вас в коде описана функция ai.chooseDirection, вы можете выполнять какие-то действия когда поезд подъезжает к развилке."
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Далее", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Открывайте только что созданный TutorialAI2.lua из той же папки, что и раньше.\n\nФайл уже содержит немного кода, именно поэтому у вас уже есть один поезд.\nДобавьте код из листина в ваш файл (существующий ai.init следует заменить), затем нажмите 'Рестарт'."
tutorialSteps[k].event = eventCounter(k)
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Доп. инфо", event = additionalInformation("Код не будет работать, если вы забудете строчку 'counter = 0', потому, что перед тем, как добавлять 1 к счётчику, следует его инициализировать. Т.к. ai.init всегда вызывается ПЕРЕД ai.chooseDirection, всё будет работать корректно."), inBetweenSteps = true}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Вроде работает!\n\nПроверьте, правильно ли ИИ считает развилки. Если что-то не так - поправьте код. Ну а если всё как надо - жмите Далее."
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Далее", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].stepTitle = "Lua: if, then, else"
tutorialSteps[k].message = "В коде вам обязательно придётся принимать решения. В этом вам поможет конструкция 'if-then-else'.\n'if' проверяет истинность выражения EXPRESSION, и, если оно истинно выполняет действия, указанные после 'then'. Дальше вы можете использовать 'elseif', 'else' или 'end' для завершения блока кода.\nПосмотрите пример."
tutorialSteps[k].event = function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_ifthenelse1)
end
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Далее", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "'EXPRESSION' - условное выражение, которое Lua принимает за истину или ложь. Если Lua вычислил его как истинное, код будет выполнен, в противном случае - нет. Примеры использования можно посмотреть в листинге. Заметьте, что здесь нельзя использовать знак '='. Вместо него должен быть '=='! Иначе это будет простое присваивание, а не условное выражение.\nНажмите 'Доп. инфо', чтоб посмотреть примеры."
tutorialSteps[k].event = function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_ifthenelse2)
end
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Доп. инфо", event = additionalInformation("1) A == B (A и B равны?)\n2) A > B (A больше, чем B?)\n3) A <= B (A меньше или равна B?)\n4) A ~= B (A не равна B)"), inBetweenSteps = true}
tutorialSteps[k].buttons[3] = {name = "Далее", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Последняя заметка об условных выражениях: Если вы программировали до этого, то, наверняка, встречали запись A != B (A не равно B). По определенным причинам в Lua используется именно A ~= B\n\nif variable ~= 10 then\n...\nend"
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Далее", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].stepTitle = "Lua: Циклы"
tutorialSteps[k].message = "Циклы - очень полезная вещь. Например, цикл while позволяет вам повторять некоторые действия, пока условие EXPRESSION принимает ложное значение.\n\nwhile EXPRESSION do\n(повторяющийся код)\nend"
tutorialSteps[k].event = function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_whileLoop)
end
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Далее", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Пора попробовать!\nДавайте изменим функцию ai.chooseDirection. Вместо количества посещений, будем выводить символ 'x' столько раз, сколько мы были на развилке. (На первой выведем 'x', на второй - 'xx' и т.д.)\nДля этого используем переменную 'counter'. Затем будем дописывать 'x' к концу строки 'counter' количество раз, и в конце выведем полученную строку на консоль."
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Далее", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "... А вот и код. Линия text = \"\" создаёт пустую строку, а i=0 инициализирует еще один счётчик, теперь можно следить сколько 'x' мы добавили к строке.\nПоправьте функцию ai.chooseDirection, перезапустите, и смотрите, что получится.\n\nЕсли всё работает - ура, жмите 'Далее'."
tutorialSteps[k].event = function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_whileLoop2)
end
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Далее", event = nextTutorialStep}
k = k + 1
--[[
tutorialSteps[k] = {}
tutorialSteps[k].message = "For-Loops let you do something a certain number of times. They work like this:\nfor i = START, END, STEP do\n(your code to repeat)\nend\nThis will count from START to END (using STEP as a stepsize)"
tutorialSteps[k].event = function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_forLoop)
end
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Back", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "More Info", event = additionalInformation("There's also the 'generic' for loop which this tutorial won't cover. That's a very nice feature as well, check out the Lua documentation online for details."), inBetweenSteps = true}
tutorialSteps[k].buttons[3] = {name = "Next", event = nextTutorialStep}
k = k + 1
]]--
tutorialSteps[k] = {}
tutorialSteps[k].stepTitle = "Lua: Функции!"
tutorialSteps[k].message = "Вы уже знаете кое-что о функциях из первого урока.\nФункция объявляется с помощью ключевого слова 'function', дальше следует имя функции и передаваемые параметры в круглых скобках. Дальше описывается тело функции - то, что она будет выполнять. Функция может вернуть какие-либо значения при помощи ключевого слова 'return'."
tutorialSteps[k].event = function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_functions1)
end
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Далее", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "В конце функции должно стоять ключевое слово 'end'.\nПосле объявления, функция может быть вызвана по имени и с нужными параметрами."
tutorialSteps[k].event = function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_functions1)
end
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Далее", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Вот еще простой пример.\n При вызове функция возвращает число (c), которое сохраняется в переменную (result). после этого переменная выводится на консоль."
tutorialSteps[k].event = function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_functions2)
end
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Далее", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "На этой карте есть один новый элемент: развилка. Каждый раз, когда поезд подъезжает к развилке, ИИ должен выбрать направление дальнейшего движения. Всего есть четыре направления: север, юг, восток и запад. Например, на этой карте развилка позволяет ехать на север(вверх), восток (направо) и юг (вниз).\nВ коде эти направления обозначаются: \"N\", \"S\", \"E\" и \"W\"."
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Далее", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Сейчас поезд движется по карте и, при встрече развилки не знает куда ему ехать, потому, что мы ещё это не запрограммировали.\nПо умолчанию поезд выберет \"N\", если возможно. Если нет (потому, что он приехал с севера или у развилки нет выхода на север), тогда он будет пробовать \"S\", затем \"E\", потом \"W\", до тех пор, пока мы не скажем ему куда ехать."
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Далее", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Сейчас поезд на развилках только выводит текст.\nСледующим шагом будет выбор нового направления. Сейчас поезд выбирает значения по умолчанию - Север, или если нет возможности ехать на север - Юг.\n\nЕсли функция ai.chooseDirection() вернет \"E\", тогда игра будет знать, что поезд хочет ехать на Восток после развилки. Сделайте, чтоб ваша функция возвращала \"E\" и перезагрузите ИИ."
tutorialSteps[k].buttons = {}
tutorialSteps[k].event = eventChooseEast(k)
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Подсказка!", event = function()
if cBox then codeBox.remove(cBox) end
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_hintGoEast)
end, inBetweenSteps = true}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "У вас получилось! Теперь поезд едет на восток всегда, когда может...\nДавайте еще кое-что попробуем: сейчас сделайте так, чтоб поезд поехал сначала на восток на развязке, а потом ездил только на север и юг. Для того, чтоб это осуществить используйте счётчик и конструкцию 'if-then-else'. Помните: чтобы проверить равенство переменной и значения надо использовать '==', а не '=' ..."
tutorialSteps[k].buttons = {}
tutorialSteps[k].event = eventChooseEastThenSouth(k)
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Доп. инфо", event = additionalInformation("Вудет достаточно сказать поезду ехать на восток, а затем на юг, потому, что если поезд едет с юга и ему говорят ехать на юг, то он автоматически поедет на север (Потому, что на юг нельзя)...\n\nДля решения этой задачи есть несколько решений. Будте осторожны: все команды посте слова 'return' не будут выполняться, потому, что 'return' это команда выхода из функции."), inBetweenSteps = true}
tutorialSteps[k].buttons[3] = {name = "Подсказка!", event = function()
if cBox then codeBox.remove(cBox) end
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_hintGoEastThenSouth)
end, inBetweenSteps = true}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Работает!"
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Далее", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].stepTitle = "Lua: Таблицы"
tutorialSteps[k].message = "Мы почти закончили с теоретической частью.\nДумаю, последнее, что нам нужно - это таблицы Lua.\nТаблицы - это, наверное, самая мощная и полезная вещь, которая есть в Lua."
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Далее", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "По-сути таблица, это контейнер для других переменных. Объявляются таблицы с помощью фигурных скобок { }. Внутри скобок вы опять можете объявлять переменные, так же, как делали это прежде (только надо разделять их запятыми)."
tutorialSteps[k].event = function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_tables1)
end
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Далее", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "После того, как таблица объявлена, вы можете получить доступ к полям при помощи такой записи:\nTABLE.ELEMENT\nПосмотрите пример..."
tutorialSteps[k].event = function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_tables2)
end
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Далее", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Вы можете добавлять в таблицу новые поля (присваивая им текст или числа) и удалять (присваивая 'nil')."
tutorialSteps[k].event = function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_tables3)
end
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Далее", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Список 'passengers', который мы использовали в первом уроке был, как раз, таблицей. Мы обращаемся к элементам по номеру, а не по имени. Для обращения к элементу надо использовать квадратные [ ] скобки, как это было в первом уроке."
tutorialSteps[k].event = function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_tables4)
end
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Далее", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Более сложный пример - прерывание цикла. Например, найдя нужного пассажира в списке, следует прекратить выполнение цикла с помощью ключевого слова 'break'. ('#passengers' - размер списка пассажиров. Но учтите, это работает, только если в качестве индексов используются числа.)\nНе переживайте, если это кажется слишком сложным; В третьем уроке будет подробный пример."
tutorialSteps[k].event = function()
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_loop3)
end
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Далее", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Ну вот и всё, этих знаний о Lua вам пока достаточно!"
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Далее", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].stepTitle = "Готово!"
tutorialSteps[k].message = "Отлично, вы закончили второй урок!\nНажмите 'Еще идеи' чтоб посмотреть что еще такого вы можете сделать перед тем, как перейти к следующему уроку.\n\nВ этом уроке мы выучили много сухой теории, следующее занятие будет более практическим."
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Еще идеи", event = additionalInformation("вы можете попробовать двигаться на восток, потом на север, потом на юг и снова на восток и так далее (E, N, S, E, N, S, E ...).\n чтобы это сделать зоздайте переменную в ai.init(), назовите её \"dir\". Затем каждый раз прибавляйте к ней 1 (dir = dir + 1) внутри функции ai.chooseDirection. Потом возвращайте \"E\", \"N\" или \"S\" если значение dir равняется 1, 2 или 3. Не забывайте сбрасывать переменную dir обратно в 0 или 1, когда она становится больше, чем 3!", CODE_moreIdeas), inBetweenSteps = true}
tutorialSteps[k].buttons[3] = {name = "Далее", event = nextTutorialStep}
k = k + 1
tutorialSteps[k] = {}
tutorialSteps[k].message = "Вы можете перейти сразу к третьему уроку или вернуться в главное меню."
tutorialSteps[k].buttons = {}
tutorialSteps[k].buttons[1] = {name = "Назад", event = prevTutorialStep}
tutorialSteps[k].buttons[2] = {name = "Меню", event = endTutorial}
tutorialSteps[k].buttons[3] = {name = "Следующий урок", event = nextTutorial}
k = k + 1
end
function eventCounter(k)
return function()
local count = 0
cBox = codeBox.new(CODE_BOX_X, CODE_BOX_Y, CODE_counter)
tutorial.consoleEvent = function( str )
if str:sub(1, 13) == "[TutorialAI2]" then
count = count + 1
if count == 2 then
tutorial.consoleEvent = nil
if currentStep == k then
nextTutorialStep()
tutorialBox.succeed()
end
end
end
end
end
end
function eventFirstChooseDirection(k)
return function()
tutorial.chooseDirectionEvent = function()
tutorial.consoleEvent = function (str)
if str:sub(1, 13) == "[TutorialAI2]" then
tutorial.consoleEvent = nil
tutorial.chooseDirectionEvent = nil
tutorial.chooseDirectionEventCleanup = nil
if currentStep == k then
nextTutorialStep()
tutorialBox.succeed()
end
end
end
end
tutorial.chooseDirectionEventCleanup = function()
tutorial.consoleEvent = nil
end
end
end
function eventChooseEast(k)
return function()
tutorial.reachedNewTileEvent = function(x, y)
if x == 3 and y == 2 then
tutorial.reachedNewTileEvent = nil
if currentStep == k then
nextTutorialStep()
tutorialBox.succeed()
end
end
end
end
end
function eventChooseEastThenSouth(k)
junctionCount = 0
local beenEast, beenSouth = false, false
return function()
tutorial.restartEvent = function()
junctionCount = 1
beenEast = true
tutorial.reachedNewTileEvent = function(x, y)
if x == 3 and y == 2 and beenEast == false and beenSouth == false then
beenEast = true
end
if x == 2 and y == 3 then
beenSouth = true
if beenEast == true then
tutorial.reachedNewTileEvent = nil
tutorial.restartEvent = nil
if currentStep == k then
nextTutorialStep()
tutorialBox.succeed()
end
else
if currentStep == k then
if currentTutBox then
currentTutBox.text = "По плану было, чтоб поезд ехал на восток, а затем на юг! Поправьте код и перезагрузите ИИ."
end
end
end
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("Tutorial3.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("Урок 2: Направо или налево?", x + roundStats:getWidth()/2 - FONT_STAT_MSGBOX:getWidth("Урок 2: Направо или налево?")/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.trainPlaced then
--if tutorial.numPassengers == 0 then
--end
--end
end
fileContent = [[
-- Урок 2: Направо или налево?
-- Покупаем поезд в начале раунда и размещаем его в верхнем левом углу:
function ai.init( map, money )
buyTrain(1,1)
end
]]
|
local inventories = {
defines.inventory.character_main,
defines.inventory.character_guns,
defines.inventory.character_ammo,
defines.inventory.character_armor,
defines.inventory.character_vehicle,
defines.inventory.character_trash,
}
return inventories
|
--System objects
|
-- the season was spring
-- and that day it was raining
-- the day I met Her
--
-- Her hair, and mine, too
-- were dense with humidity
-- and the scent of rain
--
-- the earth continued
-- quietly turning with us
-- aboard, unknowing
--
-- our bodies losing
-- heat peacefully to other
-- spaces, darknesses
--
-- on that day I was
-- picked up by Her; that is why
-- I am now Her cat
local haiku = {
{
{
1.915,
3.830,
"here in the darkness"
},
{
5.745,
7.660,
"that knows no end, the earth turns"
},
{
{
10.213,
11.489,
"quiet"
},
{
11.489,
12.766,
"like"
},
{
12.447,
14.200,
"our"
},
{
13.404,
14.681,
"hearts"
},
},
},
{
{
17.234,
19.149,
"hoping that one day",
},
{
21.064,
22.979,
"all the turning will make sense"
},
{
{
24.894,
26.170,
"in getting"
},
{
26.809,
28.085,
"us"
},
{
28.723,
30.000,
"here"
}
}
}
}
local timing = {}
for i=1,#haiku do
for line=1, #haiku[i] do
if type(haiku[i][line][3]) ~= "string" then
for word=1, #haiku[i][line] do
table.insert(timing, {haiku[i][line][word][1], haiku[i][line][word][2]})
end
else
table.insert(timing, {haiku[i][line][1], haiku[i][line][2]})
end
end
end
-----------------------------------------------------------------
local y_offset = 25
local x_offset = 60
local line_height = 19
local haiku_spacing = 80
local fadein_time = 2
local font_path = THEME:GetPathB("ScreenHereInTheDarkness", "overlay/_shared/helvetica neue/_helvetica neue 20px.ini")
local refs = {}
-----------------------------------------------------------------
local index = 1
local time_at_start, uptime
local Update = function(self, dt)
if time_at_start == nil then return end
uptime = GetTimeSinceStart() - time_at_start
if timing[index] and uptime >= timing[index][1] - 0.25 then
refs[index]:smooth( timing[index][2]-timing[index][1] ):diffusealpha(1)
index = index + 1
end
end
-----------------------------------------------------------------
local af = Def.ActorFrame{}
af.InitCommand=function(self) self:SetUpdateFunction( Update ) end
af.OnCommand=function(self) time_at_start = GetTimeSinceStart() end
af.InputEventCommand=function(self, event)
if event.type == "InputEventType_FirstPress" and (event.GameButton=="Start" or event.GameButton=="Back") then
self:smooth(1):diffuse(0,0,0,1):queuecommand("NextScreen")
end
end
af.NextScreenCommand=function(self)
SCREENMAN:GetTopScreen():StartTransitioningScreen("SM_GoToNextScreen")
end
af[#af+1] = LoadActor("./quietly-turning.ogg")..{
OnCommand=function(self) self:play() end
}
af[#af+1] = LoadActor("./earth.png")..{
InitCommand=function(self) self:halign(0):valign(1):xy(0,_screen.h):zoom(0.5):diffusealpha(0) end,
OnCommand=function(self) self:sleep(1):smooth(2):diffusealpha(1) end
}
for i=1,#haiku do
for line=1, #haiku[i] do
-- add a line, word by word
if type(haiku[i][line][3]) ~= "string" then
local line_width = 0
for word=1, #haiku[i][line] do
af[#af+1] = Def.BitmapText{
File=font_path,
Text=haiku[i][line][word][3],
InitCommand=function(self)
table.insert(refs, self)
self:align(0,0):zoom(0.85):diffusealpha(0)
self:x((_screen.cx-100) + i*x_offset + line_width)
self:y(((line-1)*line_height) + (y_offset+(i-1)*haiku_spacing))
-- accumulate current line_width as more words are added to the line
-- 5px of whitespace between each word works well enough here
line_width = line_width + (self:GetWidth() * self:GetZoom()) + 5
end,
}
end
-- add a line
else
af[#af+1] = Def.BitmapText{
File=font_path,
Text=haiku[i][line][3],
InitCommand=function(self)
table.insert(refs, self)
self:align(0,0):zoom(0.85):diffusealpha(0)
self:x((_screen.cx-100) + i*x_offset)
self:y(((line-1)*line_height) + (y_offset+(i-1)*haiku_spacing))
end,
}
end
end
end
return af |
-- Convers Hex Color Codes To RGB
local function hex2rgb (hex)
local hex = hex:gsub("#","")
local R,G,B
if hex:len() == 3 then
R = (tonumber("0x"..hex:sub(1,1))*17)/255
G = (tonumber("0x"..hex:sub(2,2))*17)/255
B = (tonumber("0x"..hex:sub(3,3))*17)/255
else
R = tonumber("0x"..hex:sub(1,2))/255
G = tonumber("0x"..hex:sub(3,4))/255
B = tonumber("0x"..hex:sub(5,6))/255
end
return R,G,B
end
return {
hex2rgb = hex2rgb
} |
local M = {}
--- Is windows
M.is_windows = false
if vim.fn.has("win32") == 1 then
M.is_windows = true
end
return M
|
require("prototypes/items/steel-exoskeleton") |
data:extend({
{
type = "technology",
name="mining-speed-1",
icon = "__5dim_infiniteresearch__/graphics/icon/mining-speed.png",
icon_size = 128,
effects =
{
{
type = "character-mining-speed",
modifier = 0.2,
}
},
unit =
{
count_formula = "20*(L)",
ingredients =
{
{"science-pack-1", 1},
},
time = 10
},
upgrade = true,
max_level = "5",
order="b-f-h",
},
{
type = "technology",
name="mining-speed-6",
icon = "__5dim_infiniteresearch__/graphics/icon/mining-speed.png",
icon_size = 128,
effects =
{
{
type = "character-mining-speed",
modifier = 0.2,
}
},
prerequisites = {"mining-speed-1"},
unit =
{
count_formula = "20*(L)",
ingredients =
{
{"science-pack-1", 1},
{"science-pack-2", 1},
},
time = 10
},
upgrade = true,
max_level = "10",
order="b-f-h",
},
{
type = "technology",
name="mining-speed-11",
icon = "__5dim_infiniteresearch__/graphics/icon/mining-speed.png",
icon_size = 128,
effects =
{
{
type = "character-mining-speed",
modifier = 0.2,
}
},
prerequisites = {"mining-speed-6"},
unit =
{
count_formula = "20*(L)",
ingredients =
{
{"science-pack-1", 1},
{"science-pack-2", 1},
{"science-pack-3", 1},
},
time = 10
},
upgrade = true,
max_level = "15",
order="b-f-h",
},
{
type = "technology",
name="mining-speed-16",
icon = "__5dim_infiniteresearch__/graphics/icon/mining-speed.png",
icon_size = 128,
effects =
{
{
type = "character-mining-speed",
modifier = 0.2,
}
},
prerequisites = {"mining-speed-11"},
unit =
{
count_formula = "20*(L)",
ingredients =
{
{"science-pack-1", 1},
{"science-pack-2", 1},
{"science-pack-3", 1},
{"production-science-pack", 1},
},
time = 10
},
upgrade = true,
max_level = "20",
order="b-f-h",
},
{
type = "technology",
name="mining-speed-21",
icon = "__5dim_infiniteresearch__/graphics/icon/mining-speed.png",
icon_size = 128,
effects =
{
{
type = "character-mining-speed",
modifier = 0.2,
}
},
prerequisites = {"mining-speed-16"},
unit =
{
count_formula = "20*(L)",
ingredients =
{
{"science-pack-1", 1},
{"science-pack-2", 1},
{"science-pack-3", 1},
{"production-science-pack", 1},
{"high-tech-science-pack", 1},
},
time = 10
},
upgrade = true,
max_level = "25",
order="b-f-h",
},
{
type = "technology",
name="mining-speed-26",
icon = "__5dim_infiniteresearch__/graphics/icon/mining-speed.png",
icon_size = 128,
effects =
{
{
type = "character-mining-speed",
modifier = 0.2,
}
},
prerequisites = {"mining-speed-21"},
unit =
{
count_formula = "20*(L)",
ingredients =
{
{"science-pack-1", 1},
{"science-pack-2", 1},
{"science-pack-3", 1},
{"production-science-pack", 1},
{"high-tech-science-pack", 1},
{"space-science-pack", 1}
},
time = 10
},
upgrade = true,
max_level = "infinite",
order="b-f-h",
},
}) |
local tab =
{
andy = 45,
ss = "dd"
}
_G.GetTable = function()
return tab
end
_G.SetTable = function(t)
tab = t
end
function PrintMyAnswer()
_G.PrintGlobalTable("table",tab)
end
|
local updateXpBar = game.ReplicatedStorage.events:WaitForChild("updateXpBar")
local gui = require(game.ReplicatedStorage:WaitForChild("modules").client.gui)
local makeChatMessage = game.ReplicatedStorage.events:WaitForChild("makeChatMessage")
local openClientNote = game.ReplicatedStorage.events:WaitForChild("openClientNote")
local sendItemAlert = game.ReplicatedStorage.events:WaitForChild("sendItemAlert")
local currencyAlert = game.ReplicatedStorage.events:WaitForChild("sendCurrencyAlert")
updateXpBar.OnClientEvent:Connect(function(xp, currentLevel)
gui.setXpBarData(currentLevel, xp)
end)
makeChatMessage.OnClientEvent:Connect(function(message, textColor, textSize)
gui.printChatMessage(message, textColor, textSize)
end)
sendItemAlert.OnClientEvent:Connect(function(itemName)
gui.showItemAlert(itemName)
end)
currencyAlert.OnClientEvent:Connect(function(currency, eventType)
print(eventType)
if eventType == "taken" then
gui.showCurrencyAlert(currency, true)
else
gui.showCurrencyAlert(currency, false)
end
end)
openClientNote.OnClientEvent:Connect(function (noteConfig)
gui.showNote(noteConfig)
end) |
Ai = { }
function Ai:new (o)
o = o or { }
setmetatable(o, self)
self.__index = self
return o
end
Ais = { }
function Ais:addAiTemplate(obj, file)
if (obj == nil) then
print("null template specified for " .. file)
else
addAiTemplate(file, obj)
end
end
function getAiTemplate(crc)
return Ais[crc]
end
|
----------------------------------
-- Area: Bastok Markets [S]
-- NPC: Karlotte
-- Type: Item Deliverer
-- !pos -191.646 -8 -36.349 87
-----------------------------------
local ID = require("scripts/zones/Bastok_Markets_[S]/IDs")
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
player:showText(npc, ID.text.KARLOTTE_DELIVERY_DIALOG);
player:openSendBox();
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end;
|
require( "components/cavern/encounters/encounter_trap_base" )
if encounter_trap_mines == nil then
encounter_trap_mines = class({},{}, encounter_trap_base)
end
LinkLuaModifier( "modifier_trap_techies_land_mine", "components/cavern/modifiers/modifier_trap_techies_land_mine", LUA_MODIFIER_MOTION_NONE )
--------------------------------------------------------------------
function encounter_trap_mines:GetEncounterLevels()
return { 1, 2, 3, 4 }
end
--------------------------------------------------------------------
function encounter_trap_mines:Start()
encounter_trap_base.Start(self)
local MineCount = { 25, 35, 50, 65 }
local nCreepCount = MineCount[ self.hRoom:GetRoomLevel() ]
local hUnits = self:SpawnNonCreepsRandomlyInRoom( "npc_dota_creature_techies_land_mine", nCreepCount, 0.7)
for _,hUnit in pairs(hUnits) do
hUnit:AddNewModifier(hUnit, nil, "modifier_trap_techies_land_mine", { fadetime=0.1, radius=180, radius_random_max=200, proximity_threshold=200, percentage_damage=40, activation_delay=0.9, invisible=true } )
hUnit:SetTeam( DOTA_TEAM_BADGUYS )
end
return true
end
--------------------------------------------------------------------
|
project "lua_bullet"
language "C++"
files {
"src/Bullet3Common/**" ,
"src/Bullet3Geometry/**" ,
"src/Bullet3Serialize/**" ,
"src/BulletDynamics/**" ,
"src/BulletSoftBody/**" ,
"src/Bullet3Collision/**" ,
"src/Bullet3Dynamics/**" ,
"src/BulletCollision/**" ,
"src/BulletInverseDynamics/**" ,
"src/LinearMath/**" ,
}
files { "code/**.cpp" , "code/**.c" , "code/**.h" , "all.h" }
includedirs { "." , "./src" }
defines {"BT_USE_DOUBLE_PRECISION"}
links { "lib_lua" }
KIND{lua="wetgenes.bullet.core"}
|
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local common = ReplicatedStorage.common
local util = common.util
local by = require(util.by)
local catagories = {
{
id = "weapon",
name = "Weapon",
icon = "",
},
{
id = "armor",
name = "Armor",
icon = "",
},
{
id = "hat",
name = "Hat",
icon = "",
},
{
id = "feet",
name = "Feet",
icon = "",
},
{
id = "trinket",
name = "Trinket",
icon = "",
},
}
return {
all = catagories,
byId = by("id", catagories),
} |
local BasePlugin = require "kong.plugins.base_plugin"
local ExternalAuthHandler = BasePlugin:extend()
local http = require "resty.http"
local kong = kong
ExternalAuthHandler.VERSION = "1.0.0"
ExternalAuthHandler.PRIORITY = 900
local function is_ignore_path(request_path, paths)
if paths then
for i, path in ipairs(paths) do
local path_after_replace = path:gsub('*', '.*')
local match_path = string.match(request_path, path_after_replace)
if request_path == match_path then
return true
end
end
end
return false
end
function ExternalAuthHandler:new()
ExternalAuthHandler.super.new(self, "external-auth")
end
function ExternalAuthHandler:access(conf)
ExternalAuthHandler.super.access(self)
local request_path = kong.request.get_path()
if is_ignore_path(request_path, conf.no_verify_paths) == false then
local request_auth_header = kong.request.get_header('Authorization')
local request_headers = {
content_type = "application/json",
authorization = request_auth_header,
}
local client = http.new()
client:set_timeouts(conf.connect_timeout, conf.send_timeout, conf.read_timeout)
local res, err = client:request_uri(conf.auth_service_url, {
method = "POST",
path = conf.auth_service_path,
headers = request_headers,
})
if not res then
return kong.response.exit(500, {message=err})
end
if res.status ~= 200 then
return kong.response.exit(401, {message="Invalid authentication credentials"})
end
ngx.req.set_header('X-Forwarded-Erena-Credentials', res.body)
end
end
return ExternalAuthHandler
|
local lookUpTable = {}
-- lookUpTable["block"] = 1
lookUpTable["wall"] = {21,31}
lookUpTable["wall_edge"] = 22
lookUpTable["wall_top"] = 35
lookUpTable["band_edge"] = 33
lookUpTable["band"] = 34
lookUpTable["slope"] = 3
lookUpTable["slope2Bot"] = 4
lookUpTable["slope2Top"] = 5
lookUpTable["corner"] = 13
lookUpTable["horizontal"] = 14
lookUpTable["innerCorner"] = 23
lookUpTable["vertical"] = 24
lookUpTable["block"] = {1,2,11,12}
lookUpTable["jumpThru"] = 18
lookUpTable["blockSingle"] = 26
lookUpTable["fence"] = 78
lookUpTable["fence_edge"] = 77
lookUpTable["fenceLow"] = 7
lookUpTable["fenceLow_edge"] = 6
lookUpTable["sign"] = {48,49,50}
lookUpTable["sign_bkg"] = {36,37}
lookUpTable["window"] = {22,32,42}
lookUpTable["pipe"] = {28,29,30}
lookUpTable["pipe_corner"] = 27
lookUpTable["baseBoard_edge"] = 43
lookUpTable["baseBoard"] = 44
lookUpTable["curve_edge"] = 41
lookUpTable["side"] = 71
lookUpTable["light_ceiling"] = 38
lookUpTable["light_ground"] = 59
lookUpTable["light_side"] = 60
lookUpTable["window_largeTop"] = 62
lookUpTable["window_largeBottom"] = 72
local Theme = require "roomgen.Theme"
local theme = Theme(lookUpTable,"Hetairoi")
local red_building = {}
red_building["wall"] = {11,21}
red_building["wall_edge"] = {12,22}
red_building["wall_top"] = 32
red_building["band_edge"] = 41
red_building["band"] = 42
red_building["baseBoard_edge"] = 51
red_building["baseBoard"] = 52
red_building["window_largeTop"] = 61
red_building["window_largeBottom"] = 71
local yellow_building = {}
yellow_building["wall"] = {13,23}
yellow_building["wall_edge"] = {14,24}
yellow_building["wall_top"] = 34
yellow_building["band_edge"] = 43
yellow_building["band"] = 44
yellow_building["baseBoard_edge"] = 53
yellow_building["baseBoard"] = 54
local orange_building = {}
orange_building["wall"] = {15,25}
orange_building["wall_edge"] = {16,26}
orange_building["wall_top"] = 36
orange_building["band_edge"] = 45
orange_building["band"] = 46
orange_building["baseBoard_edge"] = 55
orange_building["baseBoard"] = 56
orange_building["block"] = 73
local dark_building = {}
dark_building["wall"] = {17,27}
dark_building["wall_edge"] = {18,28}
dark_building["wall_top"] = 38
dark_building["band_edge"] = 47
dark_building["band"] = 48
dark_building["baseBoard_edge"] = 57
dark_building["baseBoard"] = 58
theme:addSubTheme("red_building",red_building,"Hetairoi_extra")
theme:addSubTheme("yellow_building",yellow_building,"Hetairoi_extra")
theme:addSubTheme("orange_building", orange_building,"Hetairoi_extra")
theme:addSubTheme("dark_building",dark_building,"Hetairoi_extra")
return theme |
require("gldef")
require("StockModels")
--create a local transform as example geometry
local teapot = Transform{
StockModels.Teapot(),
}
--create a clipplane osg object
local clipplane = osg.ClipPlane()
--set direction of plane clipping (-z)
clipplane:setClipPlane(0.0,0.0,-1.0,0.0)
--set plane number (useful for multiple planes)
clipplane:setClipPlaneNum(0)
--create osg clipnode object (all geometry attached here will be clipped)
clipNode = osg.ClipNode()
--add the clipplane to the clipNode
clipNode:addClipPlane(clipplane)
-- add teapot xform to clipNode
clipNode:addChild(teapot)
--alter stateset
dstate = clipNode:getOrCreateStateSet()
dstate:setRenderBinDetails(4,"RenderBin")
dstate:setMode(gldef.GL_CULL_FACE,osg.StateAttribute.Values.OFF+osg.StateAttribute.Values.OVERRIDE)
--add clipNode to world
RelativeTo.World:addChild(clipNode);
|
--[[
https://github.com/yongkangchen/poker-server
Copyright (C) 2016 Yongkang Chen lx1988cyk#gmail.com
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
--]]
local msg = require "msg"
local log = require "log"
local LERR = log.error
local LLOG = log.log
local timer = require "timer"
local visit = require "visit"
local visit_broadcast = visit.broadcast
local visit_check = visit.check
local visit_clean = visit.clean
local visit_add_role = visit.add_role
local visit_del_role = visit.del_role
local visit_is_full = visit.is_full
local visit_player_idx = visit.player_idx
local visit_get_player = visit.get_player
local game
local game_name
local ROOM_MAX_ID = 999999
local room_tbl = {}
local function broadcast(room, ...)
for _, role in pairs(room.players) do
role:send(...)
end
if room.playback then
table.insert(room.playback, table.dump{...})
end
end
local function broadcast_all(room, ...)
broadcast(room, ...)
visit_broadcast(room, ...)
for _, role in pairs(room.mid_players) do
role:send(...)
end
end
local function init_msg(player, distance, idx, is_zhuang, is_visitor)
local player_info = player.info
local hand = player_info.hand
if hand and (distance ~= 0 or is_visitor) then
hand = #hand
end
local data = {
id = player.id,
name = player.name,
idx = idx,
ip = "",
sex = player.sex,
hand = hand,
out = player_info.out,
is_ready = player_info.is_ready,
score = player_info.result.total_score,
is_zhuang = is_zhuang,
is_mid_enter = player_info.is_mid_enter,
}
local set_init_msg = game.set_init_msg
if set_init_msg then
set_init_msg(player, data, player.room)
end
return msg.INIT, data, distance
end
local function get_room_data(room)
local data = room.create_data
if data then
data = table.copy(data)
else
data = {}
end
data.id = room.id
data.round = room.round
data.max_round = room.max_round
data.player_size = room.player_size
data.host_id = room.host.id
data.start_count = room.start_count
data.game_name = game_name
data.gaming = room.gaming
data.can_visit_enter = room.can_visit_enter
data.auto_start_type = room.auto_start_type
data.stop_mid_enter = room.stop_mid_enter
if game.init_room_data then
game.init_room_data(room, data)
end
return data
end
local function delete_room(room)
for idx, role in pairs(room.mid_players) do
room.players[idx] = role
end
room.mid_players = {}
visit_clean(room)
for _, role in pairs(room.players) do
role.room = nil
end
room_tbl[room.id] = nil
end
local function init_playback(room)
room.playback = {
table.dump{msg.CREATE, room:get_data()}
}
for i, role in pairs(room.players) do
table.insert(room.playback, table.dump{init_msg(role, 0, i)})
end
end
local function start_game(room)
room.start_count = room.start_count + 1
room.gaming = true
game.start_room(room)
init_playback(room)
room:broadcast_all(msg.START_GAME)
end
local function end_game(room, ...)
room.can_out = false
room.gaming = false
room.round = room.round + 1
room.ready_count = 0
room.idx = room.next_start_idx or room.idx
local is_over
if room.is_over == nil then
is_over = room.round > room.max_round
else
is_over = room.is_over
end
if room.is_dismiss then
is_over = true
end
local cur_time = os.time()
local result = game.get_result(room, is_over, ...)
if result then
result = table.copy(result)
room:broadcast_all(msg.RESULT, result, is_over, room.is_dismiss)
for idx in pairs(room.players) do
if result[idx] and result[idx].result then
result[idx].result = nil
result[idx].time = cur_time
end
end
room.one_result[room.round - 1] = result
end
room.playback = nil
room.history_time = room.history_time or cur_time
room.history_save = room.history_save or {}
local battle_tbl = {}
battle_tbl.room_id = room.id
battle_tbl.type = room.type
battle_tbl.game_name = game_name
battle_tbl.max_round = room.max_round
battle_tbl.time = room.history_time
battle_tbl.total_result = {}
battle_tbl.one_result = {}
for _, role in pairs(room.players) do
table.insert(battle_tbl.total_result, {
host = role == room.host,
pid = role.id,
name = role.name,
total_score = role.info.result.total_score,
})
end
for round, one_result in ipairs(room.one_result) do
local tbl = {}
battle_tbl.one_result[round] = tbl
for _, v in pairs(one_result) do
table.insert(tbl, {
host = v.is_host,
pid = v.id,
name = v.name,
add_score = v.add_score,
})
end
end
for _, role in pairs(room.players) do
if not room.history_save[role.id] then
room.history_save[role.id] = true
end
end
for idx, role in pairs(room.mid_players) do
role.info.is_mid_enter = nil
room.players[idx] = role
if is_over then
role:send(msg.DISMISS)
end
end
room.mid_players = {}
if is_over then
room:delete()
else
if room.dismiss_time ~= nil then
room:broadcast(msg.APPLY, room.dismiss_tbl, room.dismiss_time - os.time(), true)
end
end
end
MSG_REG[msg.CREATE] = function(player, _, create_tbl, num, ...)
if game.NUM then
if game.NUM[num] ~= num then
LERR("create_room failed, invalid num: %d, pid: %d", num, player.id)
return
end
else
if num ~= game.BASE_ROUND and num ~= game.BASE_ROUND * 2 and (not game.BASE_COUNT or num ~= game.BASE_ROUND * 3) then
LERR("create_room failed, invalid num: %d, pid: %d", num, player.id)
return
end
end
if player.room then
LERR("create_room failed, alread in room: %d, pid: %d", player.room.id, player.id)
player:send(msg.CREATE, 1)
return
end
local room = game.create_room(player, ...)
if not room then
player:send(msg.CREATE)
return
end
local room_gid = math.random(100000, ROOM_MAX_ID)
while room_tbl[room_gid] do
room_gid = math.random(100000, ROOM_MAX_ID)
end
room_tbl[room_gid] = room
room.id = room_gid
room.round = 1
room.max_round = num
room.ready_count = 0
room.players = {}
room.visit_players = {}
room.mid_players = {}
room.start_count = 0
room.host = player
room.one_result = {}
room.dismiss_tbl = {}
room.dismiss_time = nil
room.money_type = type(create_tbl) == "table" and create_tbl.money_type or create_tbl
room.broadcast = broadcast
room.broadcast_all = broadcast_all
room.get_data = get_room_data
room.delete = delete_room
room.end_game = end_game
room.init_msg = init_msg
room.can_visit_enter = game.CAN_VISIT_ENTER
player:send(msg.CREATE, room:get_data()) --这个可以不需要,客户端那边可以判断
if room.can_visit_enter then
player:send(msg.VISITOR_LIST, {[player.id] = player.name})
visit_add_role(player, room)
else
player.room = room
room.players[1] = player
player.info = game.create_info(nil, room, true)
player:send(init_msg(player, 0, 1)) --FIXME: 不确定是否影响其他游戏
end
--require "gd_robot"(room_gid)
LLOG("create room success, room_id: %d, pid: %d", room_gid, player.id)
end
MSG_REG[msg.READY] = function(player, is_ready)
local room = player.room
if not room then
LERR("ready failed, not in room, pid: %d", player.id)
return
end
if room.gaming then
LERR("ready failed, is gaming, room_id: %d, pid: %d", room.id, player.id)
return
end
if not table.index(room.players, player) then --还没有坐下
return
end
is_ready = is_ready == true
local player_info = player.info
if player_info.is_ready == is_ready then
LERR("ready failed, same state, pid: %d", player.id)
return
end
player_info.is_ready = is_ready
local ready_count
if is_ready then
ready_count = room.ready_count + 1
else
ready_count = room.ready_count - 1
end
room.ready_count = ready_count
room:broadcast(msg.READY, player.id, is_ready, ready_count)
if room.auto_start_type and room.auto_start_type == -1 then
room.host:send(msg.READY, player.id, is_ready, ready_count)
end
if room.round == 1 and room.auto_start_type then
if ready_count == room.auto_start_type then
start_game(room)
end
elseif ready_count == room.player_size then
start_game(room)
elseif (game.CAN_MID_ENTER or game.CAN_VISIT_ENTER) and room.round > 1 and ready_count == table.length(room.players) then
start_game(room)
end
LLOG("ready success, room_id: %d, ready_count: %d, pid: %d", room.id, ready_count, player.id)
end
MSG_REG[msg.START_GAME] = function(player)
local room = player.room
if not room then
LERR("start game failed, not in room, pid: %d", player.id)
return
end
if room.start_count ~= 0 then
LERR("already started, room_id: %d, pid: %d", room.id, player.id)
return
end
if room.gaming then
LERR("start game failed, is gaming, room_id: %d, pid: %d", room.id, player.id)
return
end
if room.auto_start_type then
if room.auto_start_type ~= -1 then
LERR("start game failed, auto start_room, room_id: %d, pid: %d", room.id, player.id)
return
end
if player.id ~= room.host.id then
LERR("start game failed, player is not host, room_id: %d, pid: %d", room.id, player.id)
return
end
else
if room.players[1] ~= player then
LERR("start game failed, player is not first player, room_id: %d, pid: %d", room.id, player.id)
return
end
end
if room.ready_count < 2 then
LERR("start game failed, ready_count < 2, room_id: %d, pid: %d", room.id, player.id)
return
end
if room.ready_count ~= table.length(room.players) then
LERR("start game failed, not all ready, room_id: %d, pid: %d", room.id, player.id)
return
end
start_game(room)
end
local function room_is_full(room)
local count = table.length(room.players) + table.length(room.mid_players)
if count >= room.player_size or (room.max_player_size and count >= room.max_player_size) then
return true
end
end
local function should_ask(room, player_id)
local is_full = room_is_full(room)
local can_mid_enter = false
if game.CAN_MID_ENTER and not room.stop_mid_enter then
can_mid_enter = not is_full
end
local can_visit = game.CAN_VISIT_ENTER
if can_visit and room.host.id ~= player_id and visit_is_full(room) then
can_visit = false
end
local ask_data
if can_visit or can_mid_enter then
ask_data = {
can_visit = can_visit,
can_mid_enter = can_mid_enter
}
end
if ask_data and (room.start_count > 0 or is_full) then
return true, ask_data, is_full
end
return false, ask_data, is_full
end
local function send_ask(room, player, ask_data)
local room_data = {
room_id = room.id,
names = {},
}
room_data.round_count = room.max_round - room.start_count
room_data.need_cash = 0
for _, role in pairs(room.players) do
table.insert(room_data.names, role.name)
end
for _, role in pairs(room.mid_players) do
table.insert(room_data.names, role.name)
end
player:send(msg.MID_ENTER, room_data, ask_data)
end
MSG_REG[msg.SIT_DOWN] = function(player)
local room = player.room
if not room then
LERR("sit down failed, not in room, pid: %d", player.id)
return
end
if not visit_del_role(player) then
LERR("not is visitor, pid: %d", player.id)
return
end
if not MSG_REG[msg.ENTER](player, room.id, true, false) then
visit_add_role(player, room)
room:broadcast_all(msg.VISITOR_LIST, {[player.id] = player.name})
return
end
local idx = table.index(room.players, player)
if not idx then
idx = table.index(room.mid_players, player)
end
for role in pairs(room.visit_players) do
role:send(init_msg(player, idx - visit_player_idx(role), idx, nil, true))
end
MSG_REG[msg.READY](player, true)
end
MSG_REG[msg.ENTER] = function(player, room_id, is_mid_enter, is_visit)
if player.room then
LERR("enter room failed, already in room: %d, pid: %d", player.room.id, player.id)
player:send(msg.ENTER, 1)
return
end
local room = room_tbl[room_id]
if not room then
LLOG("enter room failed, invalid room_id: %d, pid: %d", room_id, player.id)
player:send(msg.ENTER, 2)
return
end
if not game.CAN_MID_ENTER then
is_mid_enter = nil
end
local is_ask, ask_data, is_full = should_ask(room, player.id)
if is_mid_enter and not room.gaming then
is_mid_enter = nil
is_ask = nil
end
if not game.CAN_VISIT_ENTER then
is_visit = nil
elseif is_mid_enter == nil and is_visit == nil then
is_visit = true
end
local idx
if is_mid_enter then
if ask_data == nil or not ask_data.can_mid_enter then
player:send(msg.ENTER, 4)
return
end
for i = 1, room.player_size do
if room.players[i] == nil and room.mid_players[i] == nil then
idx = i
room.mid_players[i] = player
break
end
end
player.info = game.create_info(nil, room)
player.info.is_mid_enter = true
elseif is_visit then
if ask_data == nil or not ask_data.can_visit then
player:send(msg.ENTER, 4)
return
end
visit_add_role(player, room)
idx = room_is_full(room) and 1 or visit_player_idx(player)
elseif is_ask then
send_ask(room, player, ask_data)
return
else
if is_full then
player:send(msg.ENTER, 4)
return
end
if room.gaming then
LERR("enter room failed, is gaming, room_id: %d, pid: %d", room.id, player.id)
player:send(msg.ENTER, 6)
return
end
for i = 1, room.player_size do
if room.players[i] == nil then
idx = i
room.players[i] = player
break
end
end
player.info = game.create_info(nil, room)
end
player.room = room
player:send(msg.ENTER, room:get_data(), visit_check(player))
local role_tbl = table.merge(table.copy(room.players), room.mid_players)
for i, role in pairs(role_tbl) do
if not is_visit and role ~= player then
role:send(init_msg(player, idx - i, idx))
end
player:send(init_msg(role, i - idx, i, nil, is_visit))
end
if is_visit then
room:broadcast_all(msg.VISITOR_LIST, {[player.id] = player.name})
end
player:send(msg.VISITOR_LIST, visit_get_player(player))
LLOG("enter room success, room_id: %d, pid: %d", room_id, player.id)
return true
end
MSG_REG[msg.RENTER] = function(player)
local room = player.room
if not room then
LERR("re enter room failed, not in room, pid: %d", player.id)
player:send(msg.RENTER)
return
end
local idx
local is_visit = visit_check(player)
if is_visit then
if room_is_full(room) then
idx = 1
else
idx = visit_player_idx(player)
end
else
if player.info.is_mid_enter then
idx = table.index(room.mid_players, player)
else
idx = table.index(room.players, player)
end
end
if game.CAN_VISIT_ENTER then
player:send(msg.VISITOR_LIST, visit_get_player(player))
end
for i, role in pairs(room.players) do
player:send(init_msg(role, i - idx, i, role == room.zhuang, is_visit))
end
for i, role in pairs(room.mid_players) do
player:send(init_msg(role, i - idx, i, role == room.zhuang, is_visit))
end
room:broadcast_all(msg.OFFLINE, player.id, "")
if room.dismiss_time ~= nil and not is_visit then
player:send(msg.APPLY, room.dismiss_tbl, room.dismiss_time - os.time())
end
game.renter(room, player)
LLOG("re enter room success, room_id: %d, pid: %d", room.id, player.id)
end
local function get_other_player(room)
local dismiss_tbl = room.dismiss_tbl
local tbl = {}
for _, role in pairs(room.players) do
if not table.index(dismiss_tbl, role.id) then
table.insert(tbl, role)
end
end
return tbl
end
local function add_timer(room)
local stoped = false
timer.add_timeout(200, function()
if stoped then
return
end
local players = get_other_player(room)
for _, role in pairs(players) do
MSG_REG[msg.AGREE](role, true)
end
end)
return function()
stoped = true
end
end
MSG_REG[msg.APPLY] = function(player)
local room = player.room
if not room then
LERR("apply dismiss failed, not in room, pid: %d", player.id)
return
end
if room.dismiss_time ~= nil then
LERR("room: %d dismiss is already", room.id)
return
end
if table.length(room.players) == 1 then
MSG_REG[msg.AGREE](player, true)
return
end
table.insert(room.dismiss_tbl, player.id)
room.dismiss_time = os.time() + 200
if room.stop_timer then
room.stop_timer()
end
room.stop_timer = add_timer(player.room)
room:broadcast(msg.APPLY, room.dismiss_tbl, room.dismiss_time - os.time())
end
MSG_REG[msg.DISMISS] = function(player)
local room = player.room
if not room then
LERR("room is not exist by player: %d", player.id)
return
end
if room.start_count > 0 then
LERR("room:%d game is ready", room.id)
return
end
if room.host ~= player then
LERR("is not room host by player: %d", player.id)
return
end
room:broadcast_all(msg.DISMISS)
room:delete()
end
MSG_REG[msg.ROOM_OUT] = function(player)
local room = player.room
if not room then
LERR("room is not exist by player: %d", player.id)
return
end
if visit_del_role(player) then
player:send(msg.ROOM_OUT, player.id)
return
end
if room.start_count > 0 then
LERR("room:%d game is ready", room.id)
return
end
if room.host.id == player.id and not room.group_id then
LERR("is room host by player: %d", player.id)
return
end
if player.info.is_ready then
MSG_REG[msg.READY](player, false)
end
room:broadcast_all(msg.ROOM_OUT, player.id)
for idx, role in pairs(room.players) do
if role == player then
room.players[idx] = nil
break
end
end
player.room = nil
end
local function clear_dismiss(room)
room.dismiss_time = nil
room.dismiss_tbl = {}
if room.stop_timer then
room.stop_timer()
room.stop_timer = nil
end
end
local DISMISS_NEED = {1, 2, 2, 3, 4, 5}
MSG_REG[msg.AGREE] = function(player, is_agree)
local room = player.room
if not room then
LERR("invalid not in room, pid: %d", player.id)
return
end
local dismiss_tbl = room.dismiss_tbl
local dismiss_count = #dismiss_tbl
if dismiss_count == 0 and table.length(room.players) ~= 1 then
LERR("not apply, room_id: %d, pid: %d", room.id, player.id)
return
end
if not is_agree then
LLOG("disagree dismiss room: %d by player: %d", room.id, player.id)
clear_dismiss(room)
room:broadcast(msg.AGREE, false, player.id)
return
end
if table.index(dismiss_tbl, player.id) then
LERR("already agree dismiss room: %d, by player: %d", room.id, player.id)
return
end
table.insert(dismiss_tbl, player.id)
dismiss_count = dismiss_count + 1
local is_dismiss = false
if dismiss_count >= DISMISS_NEED[table.length(room.players)] then
is_dismiss = true
end
if not is_dismiss then
LERR("The room: %d is not enough to dismiss count: %d", room.id, dismiss_count)
room:broadcast(msg.AGREE, true, player.id)
return
end
clear_dismiss(room)
room:broadcast(msg.AGREE, true, player.id, true)
room.is_dismiss = true
room:end_game()
end
MSG_REG[msg.GET_ROOM] = function(player)
local room = player.room
if not room then
LERR("invalid not in room, pid: %d", player.id)
return
end
player:send(msg.GET_ROOM, room:get_data(), visit_check(player))
end
return function(_game_name, _game_path)
game_name = _game_name
game = require("game_require")(game_name, _game_path)
end
|
--[[
© CloudSixteen.com do not share, re-distribute or modify
without permission of its author (kurozael@gmail.com).
--]]
local ITEM = Clockwork.item:New("alcohol_base");
ITEM.name = "ItemWhiskey";
ITEM.uniqueID = "whiskey";
ITEM.cost = 13;
ITEM.model = "models/props_junk/garbage_glassbottle002a.mdl";
ITEM.weight = 1.2;
ITEM.access = "w";
ITEM.business = true;
ITEM.attributes = {Stamina = 2};
ITEM.description = "ItemWhiskeyDesc";
ITEM:Register(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.