天天看点

C++ 调用lua时 dofile,loadfile以及require

C++ 调用lua时 dofile,loadfile以及require

函数 运行机制 返回结果 出现错误
dofile 加载并运行 返回运行的结果 传递给调用者
loadfile

加载,不运行;

想运行得用lua_pcall配合使用

返回编译的结果 l会返回一个错误信息,但不传递给调用者
require

在加载一个.lua文件时,require会先在package.loaded中查找此模块是否存在,如果存在,直接返回模块。

仅调用一次。

暂无研究 暂无研究

dofile编译运行后再使用pcall会报错,返回值为2。

例子:

1.方法一 使用loadfile与lua_pcall

int main()
{ 
     lua_State *L = luaL_newstate();
	if (L == NULL)
	{
		return 1;
	}
	luaL_openlibs(L);	

	int ret = luaL_loadfile(L, "main.lua");

	if (ret)
	{
		printf("Lua doFile Error !\n");
	}
	if (lua_pcall(L, 0, 0, 0) != LUA_OK)
	{
		printf("pcall error \n");
		return 1;
	}
	lua_getglobal(L, "width");
	int width = lua_tonumber(L,-1);
    lua_pop(L, 1);
	printf("%d\n",width);
}
           

2.方法二 使用lua_dofile

int main()
{
	lua_State *L = luaL_newstate();
	if (L == NULL)
	{
		return 1;
	}
	luaL_openlibs(L);	

	int ret = luaL_dofile(L, "main.lua");
	if (ret)
	{
		printf("Lua doFile Error !\n");
	}
	lua_getglobal(L, "width");
	int width = lua_tonumber(L,-1);
    lua_pop(L, 1);
	printf("%d\n",width);
}
           
c++

继续阅读