2

I need to call a Lua function from C and as long the function is global I can find it in the global table, but if it is declared local, how can I push the address on the stack to call it?

function MyGlobal()
  print("Global")
end

local function MyLocalGlobal()
  print("Local")
end

Calling MyGlobal() from C isn't a problem it works fine. I lookup the function in the global table.

But how do I call MyLocalGlobal() from C? It isn't in the global table, but where is it and how can I push the address?

I'm using Lua 5.3.4.

Max Kielland
  • 5,627
  • 9
  • 60
  • 95
  • 2
    Probably, `MyLocalGlobal` does not exist anymore. Local functions are subject to garbage collection after control exits their lexical scope. – Egor Skriptunoff Jun 29 '18 at 07:07

1 Answers1

2

The MyLocalGlobal() function isn't really global. It's local to the anonymous function that represents the whole chunk of loaded code.

What is really happening when you call lua_load/lua_loadstring:

return function(...) -- implicit functionality outside of code to be loaded

    -- your file starts here --
    function MyGlobal()
      print("Global")
    end

    local function MyLocalGlobal()
      print("Local")
    end
    -- file ends here --

end               -- implicit functionality outside of code to be loaded

You can get MyLocalGlobal later either with debugging facilities (by means of 'debug' library), or you should explicitly return required interface at the end of that source file, and grab/read the interface on native side right after you've loaded/executed the chunk.

Vlad
  • 5,450
  • 1
  • 12
  • 19
  • I'm alread using the debug library to fetch line numbers etc.. but i requires that the lua_Debug has been initialized with the correct stack level. Any ideas how to use the debug library to fetch `MyLocalGlobal()`? – Max Kielland Jun 29 '18 at 07:15
  • That's @Egor's point. Once the chunk has run, the local variable is out of scope so the function value will be garbage collected unless there are other references to it (which there wouldn't be with the code you've shown). Vlad is suggesting that you keep another reference. BTW, functions are values so can be garbage collected.. Function definitions are effectively expressions. Like other expressions, you can't just look them up somewhere. – Tom Blodget Jun 30 '18 at 00:11