0

I'm calling a function that returns an integer which represents a bitfield of 16 binary inputs each of the colors can either be on or off.

I'm trying to create a function to get the changes between the oldstate and the new state,

e.g.

function getChanges(oldColors,newColors)

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

I've tried subtracting the oldColors from the newColors and the new Colors from the oldColors but this seems to result in chaos should more then 1 value change.

this is to detect rising / falling edges from multiple inputs.

**Edit: there appears to be a subset of the lua bit api available

from: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

(there was supposed to be a table of values here, but I can't work out the syntax for markdown, it would appear stackoverflow ignores the html part of the standard.)

Ryan Leach
  • 4,262
  • 5
  • 34
  • 71
  • Lua doesn't come with bitwise operators. If using 3rd-party libraries is an option for you, here is an overview: http://lua-users.org/wiki/BitwiseOperators ... in fact, if you are using Lua 5.2, one them should be included – Martin Ender Apr 20 '13 at 19:49
  • There appears to be a subset if it isn't 5.2, I added it to the question, But I'm still lost. http://computercraft.info/wiki/Bit_%28API%29 – Ryan Leach Apr 20 '13 at 19:53

1 Answers1

3
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
Egor Skriptunoff
  • 23,359
  • 2
  • 34
  • 64