lua-users home
lua-l archive

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


> The idea here is that C functions have at most one local and Lua
> functions always have at least two. I'm not sure why this holds true,
> but that's what script is assuming.

It looks like it checks the "line" parameter of the debug hook (it
will be the second function from the top), which is always `nil` for C
functions and not for Lua functions.

Paul.

On Sun, Aug 23, 2020 at 12:41 AM v <v19930312@gmail.com> wrote:
>
> On Sun, 2020-08-23 at 09:44 +0300, Egor Skriptunoff wrote:
> > local function is_C_function(func)
> >   local x = coroutine.create(func)
> >   debug.sethook(x, function() x=debug.getlocal(2,2) coroutine.yield()
> > end, "c")
> >   coroutine.resume(x)
> >   return not x
> > end
> >
> > Why does this code work?
>
> I think it does the following:
>
> 1. Creates coroutine that will run specified function and sets hook on
> "call" event.
> 2. Starts coroutine. This causes Lua to put called function's context
> on stack and trigger hook.
> 3. Hook function writes the name of second local variable of second
> function from top of the stack (one that triggered the hook and one
> we're checking) to variable `x`. After this, it suspends execution,
> returning control to `is_C_function`.
> 4. It returns if such variable doesn't exist.
>
> The idea here is that C functions have at most one local and Lua
> functions always have at least two. I'm not sure why this holds true,
> but that's what script is assuming.
> --
> v <v19930312@gmail.com>