Lua:检测位域中的上升沿/下降沿

Lua:检测位域中的上升沿/下降沿

问题描述:

我在调用一个返回整数的函数,该整数代表16个二进制输入的位域,每个颜色可以打开或关闭。Lua:检测位域中的上升沿/下降沿

我试图创建一个函数来获取原状态数和新状态之间的变化,

例如

function getChanges(oldColors,newColors) 

    sampleOutput = {white = "",orange="added",magenta="removed" .....} 
    return sampleOutput 
end 

我已经试过减去newColors从oldColors新颜色的oldColors但这似乎导致混乱应多于1个值的变化。

这是为了检测来自多个输入的上升沿/下降沿。

* *编辑:有似乎是一个subset of the lua bit api available

来自:ComputerCraft wiki

colors.white  1  0x1  0000000000000001 
colors.orange 2  0x2  0000000000000010 
colors.magenta 4  0x4  0000000000000100 
colors.lightBlue 8  0x8  0000000000001000 
colors.yellow 16  0x10 0000000000010000 
colors.lime  32  0x20 0000000000100000 
colors.pink  64  0x40 0000000001000000 
colors.gray  128  0x80 0000000010000000 
colors.lightGray 256  0x100 0000000100000000 
colors.cyan  512  0x200 0000001000000000 
colors.purple 1024 0x400 0000010000000000 
colors.blue  2048 0x800 0000100000000000 
colors.brown  4096 0x1000 0001000000000000 
colors.green  8192 0x2000 0010000000000000 
colors.red  16384 0x4000 0100000000000000 
colors.black  32768 0x8000 1000000000000000 

(也被认为是此值的表,但我不能工作了语法为markdown,它会出现*忽略标准的html部分。)

+0

Lua不带有位运算符。如果使用第三方库是一个选项,这里是一个概述:http://lua-users.org/wiki/BitwiseOperators ...实际上,如果您使用的是Lua 5.2,那么应该包含它们之一 – 2013-04-20 19:49:54

+0

那里似乎是一个子集,如果它不是5.2,我将它添加到问题中,但我仍然迷失。 http://computercraft.info/wiki/Bit_%28API%29 – 2013-04-20 19:53:34

function getChanges(oldColors,newColors) 
    local added = bit.band(newColors, bit.bnot(oldColors)) 
    local removed = bit.band(oldColors, bit.bnot(newColors)) 
    local color_names = { 
     white = 1, 
     orange = 2, 
     magenta = 4, 
     lightBlue = 8, 
     yellow = 16, 
     lime = 32, 
     pink = 64, 
     gray = 128, 
     lightGray = 256, 
     cyan = 512, 
     purple = 1024, 
     blue = 2048, 
     brown = 4096, 
     green = 8192, 
     red = 16384, 
     black = 32768 
    } 
    local diff = {} 
    for cn, mask in pairs(color_names) do 
     diff[cn] = bit.band(added, mask) ~= 0 and 'added' 
     or bit.band(removed, mask) ~= 0 and 'removed' or '' 
    end 
    return diff 
end 
+0

AH!所以诀窍是和(新,旧!)和(!新,旧)谢谢! – 2013-04-20 20:05:09