Where are Lua's "global" local values stored?

541 Views Asked by At

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.

1

There are 1 best solutions below

2
On

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.