Lua 矩阵插值

function lerp(a, b, t) -- Linear interpolation
	return a + (b - a)*t
end

function slerp(a, b, t) --Spherical interpolation
	dot = a:Dot(b)
	if dot > 0.99999 or dot < -0.99999 then
		return t <= 0.5 and a or b
	else
		r = math.acos(dot)
		return (a*math.sin((1 - t)*r) + b*math.sin(t*r)) / math.sin(r)
	end
end

function matrixInterpolate(a, b, t)
	local ax, ay, az, a00, a01, a02, a10, a11, a12, a20, a21, a22 = a:components()
	local bx, by, bz, b00, b01, b02, b10, b11, b12, b20, b21, b22 = b:components()
	local v0 = lerp(Vector3.new(ax, ay, az), Vector3.new(bx , by , bz), t) -- Position
	local v1 = slerp(Vector3.new(a00, a01, a02), Vector3.new(b00, b01, b02), t) -- Vector right
	local v2 = slerp(Vector3.new(a10, a11, a12), Vector3.new(b10, b11, b12), t) -- Vector up
	local v3 = slerp(Vector3.new(a20, a21, a22), Vector3.new(b20, b21, b22), t) -- Vector back
	local t = v1:Dot(v2)
	if not (t < 0 or t == 0 or t > 0) then 	-- Failsafe
		return CFrame.new()
	end
	return CFrame.new(
	v0.x, v0.y, v0.z,
	v1.x, v1.y, v1.z,
	v2.x, v2.y, v2.z,
	v3.x, v3.y, v3.z)
end

function animate(weldList, factor, endList)
	startList = {}
	for each, child in pairs(weldList) do
		table.insert(startList, child.C1)
	end
	for loop = 1, factor do
		for each, child in pairs(weldList) do
			child.C1 = matrixInterpolate(startList[each], endList[each], loop/factor)
		end
		wait()
	end
end

-- Rifle reload animation

		animate({shoulders[1], shoulders[2]}, skill, {CFrame.new(-0.340310365, 1.37734306, 0.0396762304, 0.533082128, -0.298985422, -0.791474342, 0.836598635, 0.0467345566, 0.545820475, -0.12620309, -0.953113198, 0.275044024), CFrame.new(0.00948375463, -0.189517677, -0.100000188, 0.137115732, -0.173902646, 0.975170434, -0.971230805, -0.217115387, 0.0978435054, 0.194709271, -0.960531414, -0.198669493)})
		firearm.Handle.Magazine1Weld.Part0, firearm.Handle.Magazine1Weld.C1 = arms[1], parts[1].CFrame:toObjectSpace(arms[1].CFrame)
		firearm.Handle.Magazine2Weld.Part0, firearm.Handle.Magazine2Weld.C1 = arms[1], parts[2].CFrame:toObjectSpace(arms[1].CFrame)
		animate({shoulders[1], shoulders[2]}, skill/2, {CFrame.new(-0.400107473, 1.38669002, -0.150946438, 0.533082128, -0.298985422, -0.791474342, 0.836598635, 0.0467345603, 0.545820475, -0.12620309, -0.953113258, 0.275044024), shoulders[2].C1})
		animate({shoulders[1], shoulders[2]}, skill, {CFrame.new(0.344564468, 0.365162492, 0.142650843, 0.121658817, 0.508820772, -0.85223335, 0.0332551412, 0.856040537, 0.51584059, 0.992016196, -0.0910976082, 0.0872237161), CFrame.new(0.00948375463, -0.189517677, -0.100000188, 0.0795999169, -0.206656024, 0.975170434, -0.992014229, 0.0796000808, 0.0978435054, -0.0978435948, -0.975171328, -0.198669493)})	
		parts[1].Transparency, parts[2].Transparency = 1, 1
		wait(skill/20)
		parts[1].Transparency, parts[2].Transparency = 0, 0
		animate({shoulders[1], shoulders[2]}, skill, {CFrame.new(-0.400107473, 1.38669002, -0.150946438, 0.533082128, -0.298985422, -0.791474342, 0.836598635, 0.0467345603, 0.545820475, -0.12620309, -0.953113258, 0.275044024), CFrame.new(0.00948375463, -0.189517677, -0.100000188, 0.137115732, -0.173902646, 0.975170434, -0.971230805, -0.217115387, 0.0978435054, 0.194709271, -0.960531414, -0.198669493)})
		animate({shoulders[1], shoulders[2]}, skill/2, {CFrame.new(-0.340310365, 1.37734306, 0.0396762304, 0.533082128, -0.298985422, -0.791474342, 0.836598635, 0.0467345566, 0.545820475, -0.12620309, -0.953113198, 0.275044024), shoulders[2].C1})
		firearm.Handle.Magazine1Weld.Part0, firearm.Handle.Magazine1Weld.C1 = firearm.Handle, parts[1].CFrame:toObjectSpace(firearm.Handle.CFrame)
		firearm.Handle.Magazine2Weld.Part0, firearm.Handle.Magazine2Weld.C1 = firearm.Handle, parts[2].CFrame:toObjectSpace(firearm.Handle.CFrame)
		animate({shoulders[1], shoulders[2]}, skill, {CFrame.new(-0.0269896537, 1.7971313, -0.100000046, 0.479425579, -3.7252903e-009, -0.87758261, 0.877582967, -2.98023224e-008, 0.479425788, -2.85333801e-008, -1.00000048, -1.41384575e-008), CFrame.new(0.00948373973, -0.189517662, -0.100000188, 0.0998334214, 0, 0.995004177, -0.995005012, 1.12750769e-007, 0.0998335034, -1.12187486e-007, -1.00000083, 1.12562955e-008)})

Lua 简单的IA技术

--[[

Suponhamos que queira construir uma simples AI para seu jogo de luta...
Mas como começar à desenvolver a ideia?

Irei demonstrar a minha visão de tal assunto abaixo usando Lua.

]]--
function ExemploAI()
-- Facilitaria muito se a possibilidade de utilizar Integers como Strings fosse possível sem a necessidade de uma conversão em si.
-- Logo, a seguinte operação se tornaria inválida:

1 = "atacar"

-- Mas onde uma simples mudança faria diferença?
-- Demonstrarei no exemplo abaixo:

0 = "Defender"
1 = "Atacar"
stt = math.random(0,1)

if stt == 1 then
print(0)
end

-- Isso, supondo que nossa IA fosse especial e estivesse atacando à si mesma.
-- Por fim. Seria sim muito útil, tornaria este "Tutorial" ainda mais simples.
-- Mas como nem tudo é um mar de rosas. Bora programar!
end 

-- Começaremos à fazer a IA de verdade agora, mas antes precisamos criar um conceito do que seria uma IA...
-- No nosso exemplo, ela receberá um comando(Input) e deverá responder com outro comando(Output).
-- Ou seja. Se ela for atacada, ela deverá defender... Simples, não?
-- Mas sejamos um pouco mais ambiciosos e miremos em qualidade. Por mais simples que seja nosso projeto.
-- Vou usar Lua pela didática, mas como não vou focar no código em sim. Entenda que tudo descrito aqui, poderá ser reproduzido em qualquer outra linguagem.

function AI1()
-- Para não termos de criar duas instâncias do nosso código. Deixemos a parte interativa nesta mesma função.

--Interativo<
a = "Ataque"
b = "Defesa"
c = "Counter"
se = math.random(1,3)
--Interativo>
-- Com as nossas Variáveis já setadas, podemos começar.

if se == 1 then -- A Var "se" age como o nosso Input, enquanto utilizo Print como nosso Output.
print(b)
if se == 2 then
print(a)
-- Mas ficou simples demais.
-- Uma IA tão linear assim não é boa para um jogo de luta...
-- Façamos algumas modificações, para dar um pouco de "vida" ào nosso pequeno bot.

-- Então ignoremos o código acima e façamos um novo e melhorado...
--Interativo2<
a = "Ataque"
b = "Defesa"
c = "Counter"
se = math.random(1,3)
no = "Ficar parado"
--Interativo2>

de = math.random(1,2)
if se == 1 then
if de == 1 then
print(c)
else
print(b)
end
end

if se == 2 then
if de == 1 then
print(a)
else
print(no)
end
end

-- E dessa forma, podemos indicar a nossa IA para que decida se vai defender, ou atacar. Podendo até mesmo contra-atacar.
-- Mas claro que isso é muito simplório e deve ser levado apenas como uma visão/conceito, do que regra.
-- Abaixo, deixarei esta versão utilizável do código... E use como quiser, pois não sou pseudo-programador fresquinho que bota Copyright em texto. Não ligo pra crédito.



end
end
end


function IA()
a = "Ataque"
b = "Defesa"
c = "Counter"
se = math.random(1,3)
no = "Ficar parado"


de = math.random(1,2)
if se == 1 then
if de == 1 then
print(c)
else
print(b)
end
end

if se == 2 then
if de == 1 then
print(a)
else
print(no)
end
end
end

Lua 字符串在lua中分割

function split (s,t)
	local l = {n=0}
	local f = function (s)
		l.n = l.n + 1
		l[l.n] = s
	end
	local p = "%s*(.-)%s*"..t.."%s*"
	s = string.gsub(s,"^%s+","")
	s = string.gsub(s,"%s+$","")
	s = string.gsub(s,p,f)
	l.n = l.n + 1
	l[l.n] = string.gsub(s,"(%s%s*)$","")
	return l
end

Lua Lua:懒惰地图实施:第一轮

require "std.table" -- For memoize

function map(t, f)
    local nt = table.memoize(function (k) return f(t[k]) end)
    local mt = getmetatable(nt)
    function mt:__pairs()
        local k
        local function mynext()
            k,v = next(t, k)
            if k == nil then return nil end
            return k,nt[k]
        end
        return mynext, self
    end
    return nt
end
require "std.base" -- For better table tostring()

local mylist = {1,3,5,7,9}
local newlist = map(mylist, function(v) return 3 * v - 2 end)
assert(mylist[3] == 5)
assert(newlist[3] == 13)

require "std.base" -- For the pairs() that obeys the __pairs metamethod
print("old:", mylist)
print("new(3*v-2):", newlist)

Lua Lua:降序表遍历第2轮:迭代器对象

traverse = {}
function traverse:new(tname)
	local o = {}
	o.names = {}
	o.queue = {}
	o.cur = {
		tbl = nil,
		path = nil,
		state = nil,
	}

	local mt = {}
	function mt:__call(tn)
		return o:iter(tn)
	end
	mt.__index = self
	setmetatable(o, mt)

	if tname then
		o:enqueue(tname)
	end
	return o
end
function traverse:next()
	local v
	local names, queue, cur = self.names, self.queue, self.cur

	local function _poptbl()
		if cur.tbl then
			names[cur.tbl] = nil
		end
		cur.tbl = table.remove(queue, 1)
		cur.path = names[cur.tbl]
		cur.state = nil
	end

	repeat
		-- Find something to return to the user...
		if not cur.state then
			-- Pop a new table off the stack
			_poptbl()
			if not cur.tbl then
				-- No more tables to process
				return nil
			end
		end
		cur.state,v = next(cur.tbl, cur.state)
	until cur.state

	if type(v) == "table" then
		local path = cur.path.."."..cur.state
		names[v] = path
		table.insert(queue, v)
	end
	return cur.path,cur.tbl,cur.state,v
end
function traverse:iter(tname)
	if tname then
		self:enqueue(tname)
	end
	return function(...) return self:next(unpack(arg)) end, nil, nil
end
function traverse:enqueue(tname)
	local v = _G[tname]
	table.insert(self.queue, v)
	self.names[v] = tname
end
function traverse:reset()
	self.names = {}
	self.queue = {}
end
local traverse_mt = {
    __call = function(self, tname)
             	if tname then
             		return self:new(tname):iter()
             	else
             		return self:new()
             	end
             end
}
setmetatable(traverse, traverse_mt)
foo = {a={},b={},c={"bar"},d={e={},f={"moo"}},1,2,3,4,5}
bar = {"alpha", "beta", "theta", omega = {}}

local mytraverser = traverse()
mytraverser:enqueue("bar")
mytraverser:enqueue("foo")
for p,t,k,v in mytraverser() do
--for p,t,k,v in traverse('foo') do
	print(string.format("%s[%s] = %s",tostring(p),tostring(k),tostring(v)))
end
bar[1] = alpha
bar[2] = beta
bar[3] = theta
bar[omega] = table: 0x510650
foo[1] = 1
foo[2] = 2
foo[3] = 3
foo[4] = 4
foo[5] = 5
foo[a] = table: 0x5102d0
foo[c] = table: 0x510370
foo[b] = table: 0x510320
foo[d] = table: 0x5103c0
foo.c[1] = bar
foo.d[e] = table: 0x5104c0
foo.d[f] = table: 0x510510
foo.d.f[1] = moo

Lua 号码到HEX

--- Returns HEX representation of num
function num2hex(num)
    local hexstr = '0123456789abcdef'
    local s = ''
    while num > 0 do
        local mod = math.fmod(num, 16)
        s = string.sub(hexstr, mod+1, mod+1) .. s
        num = math.floor(num / 16)
    end
    if s == '' then s = '0' end
    return s
end

Lua str2base64

--- Returns BASE64 representation of str
function str2base64(str)
    local b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
    local s64 = ''
    
    while #str > 0 do -- iterate through string
        local bytes_num = 0 -- number of shifted bytes
        local buf = 0 -- input buffer
        for byte_cnt=1,3 do
            buf = (buf * 256)
            if #str > 0 then -- if string not empty, shift 1st byte to buf
                buf = buf + string.byte(str, 1, 1)
                str = string.sub(str, 2)
                bytes_num = bytes_num + 1
            end
        end
        for group_cnt=1,(bytes_num+1) do
            b64char = math.fmod(math.floor(buf/262144), 64) + 1
            s64 = s64 .. string.sub(b64chars, b64char, b64char)
            buf = buf * 64
        end
        for fill_cnt=1,(3-bytes_num) do
            s64 = s64 .. '='
        end
    end
    
    return s64
end

Lua 字符串到HEX

--- Returns HEX representation of str
function str2hex(str)
    local hex = ''
    while #str > 0 do
        local hb = num2hex(string.byte(str, 1, 1))
        if #hb < 2 then hb = '0' .. hb end
        hex = hex .. hb
        str = string.sub(str, 2)
    end
    return hex
end

Lua is_table

if (type(var) == "table") then
 -- do stuff if is table
else
 -- do stuff if is *not* table
end

Lua Lua中的颜色到RGB值表

-- Color to RGB value table for Lua coding with Corona
-- Color values copied from "http://www.w3.org/TR/SVG/types.html#ColorKeywords"
--
-- Usage for Corona toolkit:
-- add this file "colors-rgb.lua" to your working directory
-- add following directive to any file that will use the colors by name:
-- require "colors-rgb"
--
-- in the code, instead of using for example "{210, 105, 30}" for the "chocolate" color,
-- use "colorsRGB.chocolate" or colorsRGB[chocolate]
-- or if you need the individual R,G,B values, you can use either:
-- colorsRGB.chocolate[1] or colorsRGB.R("chocolate") for the R-value
-- or if you need the RGB values for a function list, you can use
-- colorsRGB.RGB("chocolate") that returns the multi value list "210 105 30"
-- this can be used for input in for example "body:setFillColor()", like:
-- body:setFillColor(colorsRGB.RGB("chocolate"))
--
-- Enjoy, Frank (Sep 19, 2010)


colorsRGB = {
aliceblue = {240, 248, 255},
antiquewhite = {250, 235, 215},
aqua = { 0, 255, 255},
aquamarine = {127, 255, 212},
azure = {240, 255, 255},
beige = {245, 245, 220},
bisque = {255, 228, 196},
black = { 0, 0, 0},
blanchedalmond = {255, 235, 205},
blue = { 0, 0, 255},
blueviolet = {138, 43, 226},
brown = {165, 42, 42},
burlywood = {222, 184, 135},
cadetblue = { 95, 158, 160},
chartreuse = {127, 255, 0},
chocolate = {210, 105, 30},
coral = {255, 127, 80},
cornflowerblue = {100, 149, 237},
cornsilk = {255, 248, 220},
crimson = {220, 20, 60},
cyan = { 0, 255, 255},
darkblue = { 0, 0, 139},
darkcyan = { 0, 139, 139},
darkgoldenrod = {184, 134, 11},
darkgray = {169, 169, 169},
darkgreen = { 0, 100, 0},
darkgrey = {169, 169, 169},
darkkhaki = {189, 183, 107},
darkmagenta = {139, 0, 139},
darkolivegreen = { 85, 107, 47},
darkorange = {255, 140, 0},
darkorchid = {153, 50, 204},
darkred = {139, 0, 0},
darksalmon = {233, 150, 122},
darkseagreen = {143, 188, 143},
darkslateblue = { 72, 61, 139},
darkslategray = { 47, 79, 79},
darkslategrey = { 47, 79, 79},
darkturquoise = { 0, 206, 209},
darkviolet = {148, 0, 211},
deeppink = {255, 20, 147},
deepskyblue = { 0, 191, 255},
dimgray = {105, 105, 105},
dimgrey = {105, 105, 105},
dodgerblue = { 30, 144, 255},
firebrick = {178, 34, 34},
floralwhite = {255, 250, 240},
forestgreen = { 34, 139, 34},
fuchsia = {255, 0, 255},
gainsboro = {220, 220, 220},
ghostwhite = {248, 248, 255},
gold = {255, 215, 0},
goldenrod = {218, 165, 32},
gray = {128, 128, 128},
grey = {128, 128, 128},
green = { 0, 128, 0},
greenyellow = {173, 255, 47},
honeydew = {240, 255, 240},
hotpink = {255, 105, 180},
indianred = {205, 92, 92},
indigo = { 75, 0, 130},
ivory = {255, 255, 240},
khaki = {240, 230, 140},
lavender = {230, 230, 250},
lavenderblush = {255, 240, 245},
lawngreen = {124, 252, 0},
lemonchiffon = {255, 250, 205},
lightblue = {173, 216, 230},
lightcoral = {240, 128, 128},
lightcyan = {224, 255, 255},
lightgoldenrodyellow = {250, 250, 210},
lightgray = {211, 211, 211},
lightgreen = {144, 238, 144},
lightgrey = {211, 211, 211},
lightpink = {255, 182, 193},
lightsalmon = {255, 160, 122},
lightseagreen = { 32, 178, 170},
lightskyblue = {135, 206, 250},
lightslategray = {119, 136, 153},
lightslategrey = {119, 136, 153},
lightsteelblue = {176, 196, 222},
lightyellow = {255, 255, 224},
lime = { 0, 255, 0},
limegreen = { 50, 205, 50},
linen = {250, 240, 230},
magenta = {255, 0, 255},
maroon = {128, 0, 0},
mediumaquamarine = {102, 205, 170},
mediumblue = { 0, 0, 205},
mediumorchid = {186, 85, 211},
mediumpurple = {147, 112, 219},
mediumseagreen = { 60, 179, 113},
mediumslateblue = {123, 104, 238},
mediumspringgreen = { 0, 250, 154},
mediumturquoise = { 72, 209, 204},
mediumvioletred = {199, 21, 133},
midnightblue = { 25, 25, 112},
mintcream = {245, 255, 250},
mistyrose = {255, 228, 225},
moccasin = {255, 228, 181},
navajowhite = {255, 222, 173},
navy = { 0, 0, 128},
oldlace = {253, 245, 230},
olive = {128, 128, 0},
olivedrab = {107, 142, 35},
orange = {255, 165, 0},
orangered = {255, 69, 0},
orchid = {218, 112, 214},
palegoldenrod = {238, 232, 170},
palegreen = {152, 251, 152},
paleturquoise = {175, 238, 238},
palevioletred = {219, 112, 147},
papayawhip = {255, 239, 213},
peachpuff = {255, 218, 185},
peru = {205, 133, 63},
pink = {255, 192, 203},
plum = {221, 160, 221},
powderblue = {176, 224, 230},
purple = {128, 0, 128},
red = {255, 0, 0},
rosybrown = {188, 143, 143},
royalblue = { 65, 105, 225},
saddlebrown = {139, 69, 19},
salmon = {250, 128, 114},
sandybrown = {244, 164, 96},
seagreen = { 46, 139, 87},
seashell = {255, 245, 238},
sienna = {160, 82, 45},
silver = {192, 192, 192},
skyblue = {135, 206, 235},
slateblue = {106, 90, 205},
slategray = {112, 128, 144},
slategrey = {112, 128, 144},
snow = {255, 250, 250},
springgreen = { 0, 255, 127},
steelblue = { 70, 130, 180},
tan = {210, 180, 140},
teal = { 0, 128, 128},
thistle = {216, 191, 216},
tomato = {255, 99, 71},
turquoise = { 64, 224, 208},
violet = {238, 130, 238},
wheat = {245, 222, 179},
white = {255, 255, 255},
whitesmoke = {245, 245, 245},
yellow = {255, 255, 0},
yellowgreen = {154, 205, 50}
}

colorsRGB.R = function (name)
return colorsRGB[name][1]
end

colorsRGB.G = function (name)
return colorsRGB[name][2]
end

colorsRGB.B = function (name)
return colorsRGB[name][3]
end

colorsRGB.RGB = function (name)
return colorsRGB[name][1],colorsRGB[name][2],colorsRGB[name][3]
end