I'm having problems getting a Lua 5.2 function to get called from C++.
This is the Lua chunk (named test.lua):
function testFunction ()
print "Hello World"
end
And this is the C++:
int iErr = 0;
//Create a lua state
lua_State *lua = luaL_newstate();
// Load io library
luaopen_io (lua);
//load the chunk we want to execute (test.lua)
iErr = luaL_loadfile(lua, "test.lua");
if (iErr == 0) {
printf("successfully loaded test.lua\n");
// Push the function name onto the stack
lua_getglobal(lua, "testFunction");
printf("called lua_getglobal. lua stack height is now %d\n", lua_gettop(lua));
//Call our function
iErr = lua_pcall(lua, 0, 0, 0);
if (iErr != 0) {
printf("Error code %i attempting to call function: '%s'\n", iErr, lua_tostring(lua, -1));
}
} else {
printf("Error loading test.lua. Error code: %s\n", lua_tostring(lua, -1));
}
lua_close (lua);
When I trace, I see that it loads the test.lua script fine (no error is returned), it then shows that the stack height is 3 after calling the lua_getglobal with the function name.
However, it fails at lua_pcall with the error code 2: 'attempt to call a nil value'.
I've read plenty of examples of Lua 5.2 code, and can't seem to see where I'm going wrong. This looks like it should definitely work (according to what I've read).
I've checked spelling and case sensitivity, and it all matches up.
Have I misunderstood something???
luaL_openlibs
should load it. – Waldron