lua-users home
lua-l archive

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



Ando Sonenblick wrote:
But alas, after lua_loading and looking for main, I get nil on the stack.

Right, because lua_load has no effect on the globals. I'll explain, but first an anology:

x = 4
print('x', x)

main = 4
print('main', main)

main = function() print'running main' end
print('main', main)
main()

function main() print'running main2' end
print('main', main)
main()

The code above will output:

x       4
main    4
main    function: 0x10045cd0
running main
main    function: 0x10046418
running main2

A function is a value much like the number 4 is a value. You can assign a function to a global variable just like you can assign the number 4 to a global variable, but it doesn't happen unless you run some code that does the assignment. The variable x will not have the value 4 if you don't run the chunk. The variable main will not have a function value if you don't run the chunk.

Functions don't have names; it's an illusion. Functions are values that you can store in a global variable if you choose to. When you register a function, all you are doing is assigning it to a global variable. If you choose not to run the code that stores it in the global variable, then the global variable will be nil.

Now let's talk about lua_load. It didn't exist is Lua 4, there were just the simple functions named lua_dofile, lua_dostring, lua_dobuffer. lua_dofile will load the file, 'compile' it, and execute it. Someone suggested breaking lua_dofile into two steps and separate the load from the execute. So now Lua 5 has the more basic and more flexible lua_load mechanism. You can still find lua_dofile in the auxlib if you want it.

lua_load is more flexible because you can store the function it returns in the global variable main and execute it later. You can even use lua_setfenv to change the function's environment before you execute it. It's great! You can execute the function with lua_call so that it kills your application if there is a runtime error in your function, or you can execute it with lua_pcall and report the error on the stack however you wish.

There are a lot choices, but to be able to understand it and make the 'best' choice, you need to tinker a little and try some of the possibilities.

Yes, sometimes that's painful, but you'll become numb to it eventually :-)

- Peter