我有一个Lua 5.3脚本(仿真器),我想将其移植到使用Lua 5.2的环境中。它使用5.2中不存在的按位运算符;相反,5.2使用函数来执行按位运算。该脚本使用了数百个这样的运算符,而手工转换它们将是乏味的。有没有什么方法可以将文件中的所有运算符转换为函数调用,同时注意括号和运算顺序? (解决方案不必使用Lua;任何语言都可以。)
示例:
if mode == ROTATE_MODE_ROR then
shifts = shifts & shift
local shiftmask = (1 << shifts) - 1
cf = (vr >> ((shifts - 1) & shift)) & 0x01
vr = (vr >> shifts) | ((vr & shiftmask) << ((shift - shifts + 1) & shift))
of = ((vr >> shift) ~ (vr >> (shift - 1))) & 0x01
elseif mode == ROTATE_MODE_ROL then
shifts = shifts & shift
cf = (vr >> ((shift - shifts + 1) & shift)) & 0x01
vr = ((vr << shifts) & ((1 << (shift + 1)) - 1)) | (vr >> ((shift - shifts + 1) & shift))
of = ((vr >> shift) ~ cf) & 0x01
转换为:
if mode == ROTATE_MODE_ROR then
shifts = bit32.band(shifts, shift)
local shiftmask = bit32.lshift(1, shifts) - 1
cf = bit32.band(bit32.rshift(vr, bit32.band((shifts - 1), shift)), 0x01)
vr = bit32.bor(bit32.rshift(vr, shifts), bit32.lshift((bit32.band(vr, shiftmask), bit32.band((shift - shifts + 1), shift))))
of = bit32.band(bit32.bxor(bit32.rshift(vr, shift), bit32.rshift(vr, (shift - 1))), 0x01)
elseif mode == ROTATE_MODE_ROL then
shifts = bit32.band(shifts, shift)
cf = bit32.band(bit32.rshift(vr, bit32.band((shift - shifts + 1), shift)), 0x01)
vr = bit32.bor(bit32.band(bit32.lshift(vr, shifts), (bit32.lshift(1, (shift + 1)) - 1)), bit32.rshift(vr, bit32.band((shift - shifts + 1), shift)))
of = bit32.band(bit32.bxor(bit32.rshift(vr, shift), cf), 0x01)