加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 在不执行脚本的情况下调用Lua函数

发布时间:2020-12-16 04:51:57 所属栏目:百科 来源:网络整理
导读:我将Lua嵌入到C/C++应用程序中.有没有办法从C/C++调用Lua函数而不先执行整个脚本? 我试过这样做: //call lua script from C/C++ programluaL_loadfile(L,"hello.lua");//call lua function from C/C++ programlua_getglobal(L,"bar");lua_call(L,0); 但它
我将Lua嵌入到C/C++应用程序中.有没有办法从C/C++调用Lua函数而不先执行整个脚本?

我试过这样做:

//call lua script from C/C++ program
luaL_loadfile(L,"hello.lua");

//call lua function from C/C++ program
lua_getglobal(L,"bar");
lua_call(L,0);

但它给了我这个:

PANIC: unprotected error in call to Lua API (attempt to call a nil value)

我这样做时只能调用bar():

//call lua script from C/C++ program
luaL_dofile(L,"hello.lua");  //this executes the script once,which I don't like

//call lua function from C/C++ program
lua_getglobal(L,0);

但它给了我这个:

hello
stackoverflow!!

我想要这个:

stackoverflow!

这是我的lua脚本:

print("hello");

function bar()
 print("stackoverflow!");
end

解决方法

正如freenode上的#lua中讨论的那样luaL_loadfile只是简单地将文件编译成可调用的块,此时文件中没有任何代码运行(包括函数定义),因此为了得到bar的定义必须调用执行块(这是luaL_dofile所做的).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读