3
votes

I'm loading a Lua script to be run multiple times and another Lua script that acts as a library that is supposed to be used by the first script.

Let HelloWorldAPI.lua :

function HelloWorld()
    return "Hello world"
end

And SomeScript.lua :

HelloWorld()

I'm doing things in the following order :

L = luaL_newstate();
luaL_openlibs( L );
luaL_loadfile( L, "HelloWorldAPI.lua" );
luaL_loadfile( L, "SomeScript.lua" );
...
lua_pcall( L, 0, 0, 0 )
...
lua_pcall( L, 0, 0, 0 )
...

(some pieces of code were removed to keep it simple)

But I'm geting an error saying that I'm trying to call a nil value when calling the HelloWorld function.

Why ?

The function that I declared when the lib script was executed should be global and thus available in SomeScript.lua, right ?

Thank you.

2
Why is this tagged as C ? - Shark

2 Answers

3
votes

luaL_loadfile(); loads and compiles a chunk, puts it on top of the stack, but does not execute it yet (so, after the first call to luaL_loadfile the function HelloWorld is not yet defined in the global lua state.

Then, you load the file SomeScript.lua, which is now on top of the stack. The call to lua_pcall now executes this chunk at the top, which tries to call the (not yet) defined function HelloWorld, resulting in the error you observe.

With this in mind, that would be the correct order:

luaL_loadfile( L, "HelloWorldAPI.lua" );
lua_pcall( L, 0, 0, 0 );
luaL_loadfile( L, "SomeScript.lua" );
lua_pcall( L, 0, 0, 0 );

However, to load and immediately execute a file you should use luaL_dofile:

luaL_dofile( L, "HelloWorldAPI.lua" );
luaL_dofile( L, "SomeScript.lua" );
0
votes

luaL_loadfile leaves the compiled script as a function on the stack.

So, the function for SomeScript.lua is at the top, the function for HelloWorldAPI.lua is below it.