tags:

views:

217

answers:

2

I load scripts using luaL_loadfile and then lua_pcall from my game, and was wondering if instead of loading them into the global table, I could load them into a table named after their filename?

For example:

I have I file called "Foo.lua", which contains this:

function DoSomething()
    --something
end

After loading it I want to be able to access it like:

Foo.DoSomething()

Thanks!

+3  A: 

Where they go is determined by the Lua code itself - if the file declares it in the global namespace, it'll go into the global namespace when you run the file via pcall.

The simplest option would be to encourage whoever is writing the Lua files to create their own namespaces (just a Foo = {} at the beginning of the file, and then later on declaring functions as Foo.whatever).

If you want to force things into a private namespace, you'd have to complicate things a bit - basically, find what has changed in the global namespace after running the file and manually move the new items into a private namespace instead.

Amber
+5  A: 

Try something like this. Don't forget to add error checking...

lua_newtable(L);
lua_setglobal(L,filename);
luaL_loadfile(L,filename);
lua_getglobal(L,filename);
lua_setfenv(L,-2);
lua_pcall(L,...);
lhf
Do I have to set the environment back after this? Because when I try calling a function I registered after this I get: "attempt to call global 'print' (a nil value)"
Homeliss
Oh, right. The code I gave replaces the globals for that script by an empty table and it does not have print. I see two solutions: add an __index metamethod to that table pointing to _G or temporarily add a __newindex method to _G before lua_pcall so that all definitions in the script go to your table. I suggest you prototype this first using Lua and then move to C.
lhf