lua-users home
lua-l archive

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

于 2012-4-13 23:47, dderny 写道:

In a program I have :



function x()

 print(“global x”)




function y()

                local function x()

                      print(“local x”)







from the c function I would like to call

1/ the local x function in y (if available)

2/ the global x func if available.


I have no problem to call the global x function

But no idea on how I could call the localone


Any idea ?










No, you can't access that local function x since its scope is only within function y itself, but not the function called by y.
this is the so called `lexical scoped language'

you may pass a closure of the inner local function x as a parameter to the C function. like this:

  function y ()
      local function x ()

  int SOME_C_FUNCTION (lua_State *L) {
    lua_pushvalue(L, 1);
    /* push the parameters */
    lua_call(L, ...)


btw, you may use the following hack if you are familiar with the implementation of Lua.
this would require accessing inernal data structures of lua, and your C code must be compiled as part of lua and be static linked.
note that use lua's internal implementation detail is NOT recommended. it is totally hack.
but in case you are curious, here is the method:

   from your C function, get a pointer to the closure y which calls the C function. then you can get the Proto of function y,
   and then the Proto of the inner function x. then create a closure for the Proto and call it.