always "attempt to call a nil value"......when pcall in lua api

Started by
2 comments, last by skybreaker 18 years ago
Hello : I'm a new user of lua,I'm tring to call a simple function in file. in my application:

lua_State* luaVM =  lua_open();
	if (NULL == luaVM)
	{
		MyEngineERR("luaL_error Initializing lua\n");
		return -1;
	}
	if (luaL_loadfile(luaVM,filename)!=0) 
	{
		MyEngineERR((LPSTR)lua_tostring(luaVM, -1));
		lua_pop(luaVM, 1); 
		lua_close(luaVM);
		return -1;
	}
// loading is succesful
        const char name[]="add";
	lua_getglobal(luaVM,name);
//when I remove this line pcall succesful,or I will get a "attempt to call a nil value"
	if(lua_pcall(luaVM,0,0,NULL)!=0)
	{
		MyEngineERR((LPSTR)lua_tostring(luaVM, -1));//
		lua_pop(luaVM, 1);
                lua_close(luaVM);
 	}


in the scripts file:

function add()
a=1+1
end


Am I do somethin wrong?and I'm using lua 5.1.Thanks for any suggestions.
Advertisement
You have loaded your Lua file but not executed it. When you call luaL_loadfile Lua only compiles the file and places it on the stack. Do a lua_pcall before trying to call add and it will put your add function into the globals table.

With the code you have now Lua cannot find add because it was never placed in the globals table (that is why you get the nil message).
As Zorbfish says. The reason for this is that files are just functions. lua_loadfile will put the "function of the file" on the top of the Lua stack for you, but it won't execute that function until you do lua_pcall. When you do execute lua_pcall, the function is executed, and returns a function called "new". That function is added to the globals table, which is why you can access it later by using lua_getglobal.
Jetblade: an open-source 2D platforming game in the style of Metroid and Castlevania, with procedurally-generated levels
It works haha...thanks a lot thanks thanks thanks....

This topic is closed to new replies.

Advertisement