Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua issue - Loading a library file before running

Tags:

c

lua

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.

like image 878
Virus721 Avatar asked Jul 17 '26 22:07

Virus721


1 Answers

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" );
like image 118
Ctx Avatar answered Jul 20 '26 12:07

Ctx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!