lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Fri, Sep 9, 2011 at 11:47 PM, HyperHacker <hyperhacker@gmail.com> wrote:
> so rather than "1 << n", you have to write "(1) '<<' (n)"  [...]
> x = (((h) '&' (0x0F)) '<<' (0x12))
>  '|' (((h) '&' (0xF0)) '<<' (0xA))
>  '|' (((w) '&' (0x0F)) '<<' (8))
>  '|' ((w) '&' (0xF0))

I don't seriously consider doing that type of thing [1] in real code,
though I wonder if LuaJit can work its magic on these approaches.  I
would rather do the ordinary:

  local O, A, L = bit.bor, bit.band, bit.lshift
  x = O( L(A(h, 0x0F), 0x12),
            L(A(h, 0xF0), 0xA),
            L(A(w, 0x0F), 8),
               A(w, 0xF0)         )

You can also do this:

  debug.setmetatable(0, {__index = require'bit32'})
  x = (0):bor(
    h:band(0x0F):lshift(0x12),
    h:band(0xF0):lshift(0xA),
    w:band(0x0F):lshift(8),
    w:band(0xF0)
  )

Under one of the syntax proposals, we could refine that to

  x = (0):['|'](
    h:['&'](0x0F):['<<'](0x12),
    h:['&'](0xF0):['<<'](0xA),
    w:['&'](0x0F):['<<'](8),
    w:['&'](0xF0)
  )

However, rather than abuse Lua syntax, it's more general to pass a
list of "tokens" to an evaluator:

  x = eval(
    '(', h, '&', 0x0F, '<<', 0x12, ')', '|',
    '(', h, '&', 0xF0, '<<', 0xA, ')', '|',
    '(', w, '&', 0x0F, '<<', 8, ')', '|',
    '(', w, '&', 0xF0, ')'
  )

A code generation technique like in [2] could make that quite efficient:

  x = eval[[
    ((P1 & 0x0F) << 0x12) |
    ((P1 & 0xF0) << 0xA) |
    ((P2 & 0x0F) << 8) |
    ((P2 & 0xF0 )
  ]](h, w)

[1] http://lua-users.org/wiki/CustomOperators
[2] http://lua-users.org/wiki/ListComprehensions