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

Is it possible to get the size of the function in bytes to see if it coincides with another function, like the C ++ operator sizeof, or evaluate the two functions in some other way to make sure they are equal without knowing that the function / is? Example:

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

If this is not possible, just say it and it will satisfy my answer! Thanks!

EDIT: the body of one function is what I need to check to make sure that it is the same as the other body of the function. The memory link will be different, so I cannot use "==", but the function link name may be different.

+6
source share
2 answers

Using == for functions only checks to see if they reference the same function, which you did not expect.

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

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

f and g are two functions that are equal to your definition. Assuming the t.lua file, run:

 luac -l t.lua 

Output:

 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, both functions have the same instructions on the virtual machine.

+5
source

Will comparing bytecode?

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

Of course, there would be cases where the above did not work. 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 perform the same thing, but generate different byte codes. Perhaps if you indicate what you are trying to achieve, a better solution may be provided than a comparison of functions.

+5
source

Source: https://habr.com/ru/post/988797/


All Articles