Lua - Is it possible to check if 2 functions are equal?

1.8k views Asked by At

Is it either possible to get the size of a function in bytes to see if it matches another function similar to C++ sizeof operator, or evaluate two functions some other way to see if they are both equal without actually knowing what the function/s are? Example:

local function equals(func1, func2)
   -- check them and return true if equal
end

If this is not possible just say and that will satisfy my answer! Thank you!

EDIT: The body of one function is what I need to check to see if it is the same as another function's body. The reference in memory will be different so I cannot use "==" but the function's reference name can be different.

2

There are 2 answers

2
Yu Hao On BEST ANSWER

Using == for functions only checks if they reference to the same function, which is not what you expected.

This task is rather difficult, if not impossible at all. For really simple cases, here's an idea:

function f(x) return x + 1 end
local g = function(y) return y + 1 end

f and g are two function that are equal by your definition. Assuming the file is t.lua, run:

luac -l t.lua

The output is:

main <t.lua:0,0> (4 instructions at 00000000003081c0)
0+ params, 2 slots, 1 upvalue, 1 local, 1 constant, 2 functions
        1       [1]     CLOSURE         0 0     ; 0000000000308330
        2       [1]     SETTABUP        0 -1 0  ; _ENV "f"
        3       [2]     CLOSURE         0 1     ; 0000000000308dc0
        4       [2]     RETURN          0 1

function <t.lua:1,1> (3 instructions at 0000000000308330)
1 param, 2 slots, 0 upvalues, 1 local, 1 constant, 0 functions
        1       [1]     ADD             1 0 -1  ; - 1
        2       [1]     RETURN          1 2
        3       [1]     RETURN          0 1

function <t.lua:2,2> (3 instructions at 0000000000308dc0)
1 param, 2 slots, 0 upvalues, 1 local, 1 constant, 0 functions
        1       [2]     ADD             1 0 -1  ; - 1
        2       [2]     RETURN          1 2
        3       [2]     RETURN          0 1

As you can see, the two functions have the same instructions in the virtual machine.

4
Ignacio On

Will comparing the bytecode do?

local function equals(func1, func2)
    return string.dump(func1) == string.dump(func2)
end

Surely, there would be some cases were the above would fail. For instance:

local function f1 (...)
    local a = print
    a(...)
end

local function f2 (...)
    print(...)
end


local function equals (f1, f2)
    return string.dump(f1) == string.dump(f2)
end

print(equals(f1,f2))   --> false

Both functions do the same thing, but they generate different bytecode. Maybe if you state what you're trying to achive, a better solution than function comparison can be provided.