Where are Lua's “global” local values stored?


Where are Lua's “global” local values stored?



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.


MyGlobal()



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?


MyLocalGlobal()



I'm using Lua 5.3.4.





Probably, MyLocalGlobal does not exist anymore. Local functions are subject to garbage collection after control exits their lexical scope.
– Egor Skriptunoff
Jun 29 at 7:07


MyLocalGlobal




1 Answer
1



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


MyLocalGlobal()



What is really happening when you call lua_load/lua_loadstring:


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.


MyLocalGlobal





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 at 7:15


MyLocalGlobal()





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 at 0:11






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Render GeoTiff to on browser with leaflet

How to get chrome logged in user's email id through website

using states in a react-navigation without redux