Search code examples
clualuajit

Convert C function to Lua


I need convert this C function to a Lua function

I'm porting a simple project to LuaJIT, my port is 99% done, but this function has some problem. What am I missing?

/**
*  X-Or. Does a bit-a-bit exclusive-or of two strings.
*  @param s1: arbitrary binary string.
*  @param s2: arbitrary binary string with same length as s1.
*  @return  a binary string with same length as s1 and s2,
*   where each bit is the exclusive-or of the corresponding bits in s1-s2.
*/


static int ex_or (lua_State *L) {
  size_t l1, l2;
  const char *s1 = luaL_checklstring(L, 1, &l1);
  const char *s2 = luaL_checklstring(L, 2, &l2);
  luaL_Buffer b;
  luaL_argcheck( L, l1 == l2, 2, "lengths must be equal" );
  luaL_buffinit(L, &b);
  while (l1--) luaL_putchar(&b, (*s1++)^(*s2++));
  luaL_pushresult(&b);
  return 1;
}

At moment, my current Lua function is this:

local bit = require('bit')
function ex_or(arg1, arg2)
    if #arg1 == #arg2 then
        local result = ""
        local index = 1
        while index <= #arg1 do
            result = result .. bit.bxor(string.byte(arg1, index), string.byte(arg2, index))
            index = index + 1
        end
        return result
    else
        error("lengths must be equal.")
    end
end

Thanks in advance


Solution

  • you forgot to call string.char on the processed byte:

    result = result .. string.char(bit.bxor(string.byte(arg1, index), string.byte(arg2, index)))
    

    Some more tips:

    1. Use a for loop, that would be faster.
    2. Use extern locals for bit.bxor, string.byte and string.char.
    3. the common name is xor, not ex_or (It wasn't or and is no more... ;-)).