安全调用Lua中已注册的C++函数。
2011-1-26 6:29:27
收藏:0
阅读:396
评论:1
大家好!我的C++应用程序嵌入了Lua作为脚本。非程序员编辑Lua脚本,然后C++应用程序调用Lua脚本,Lua脚本也调用了C++注册的函数。
我使用Luaplus来完成上述工作。我的问题是:当脚本编辑器出现拼写错误,比如拼写错误的参数,C++应用程序会崩溃!我该怎么做才能防止这种情况发生?谢谢。
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- Lua 虚拟机加密load(string.dump(function)) 后执行失败问题如何解决
- 我想创建一个 Nginx 规则,禁止访问
- 如何将两个不同的lua文件合成一个 东西有点长 大佬请耐心看完 我是小白研究几天了都没搞定
- 如何在roblox studio中1:1导入真实世界的地形?
- 求解,lua_resume的第二次调用继续执行协程问题。
- 【上海普陀区】内向猫网络招募【Skynet游戏框架Lua后端程序员】
- SF爱好求教:如何用lua实现游戏内调用数据库函数实现账号密码注册?
- Lua实现网站后台开发
- LUA错误显式返回,社区常见的规约是怎么样的
- lua5.3下载库失败
- 请问如何实现文本框内容和某个网页搜索框内容连接,并把网页输出来的结果反馈到另外一个文本框上
- lua lanes多线程使用
- 一个kv数据库
- openresty 有没有比较轻量的 docker 镜像
- 想问一下,有大佬用过luacurl吗
- 在Lua执行过程中使用Load函数出现问题
- 为什么 neovim 里没有显示一些特殊字符?
- Lua比较两个表的值(不考虑键的顺序)
- 有个lua简单的项目,外包,有意者加微信 liuheng600456详谈,最好在成都
- 如何在 Visual Studio 2022 中运行 Lua 代码?

看一下lua_cpcall和lua_pcall。它们两个都允许在c中保护调用lua的函数。如果它们返回一个非负数,则调用失败,并且lua栈只包含错误字符串。在cpcall的情况下,栈不会被修改。对于pcall,您将需要查看lua_pushcclosure来安全地调用cfunction。
你所做的就是:创建一个包含所有你想要的lua_*调用的c函数,例如loadfile和dofile。你使用lua_cpcall或lua_pushcclosure和lua_pcall调用这个函数。这使你能够检测是否在你传递给cpcall的函数中出现错误。
示例:
```` function hello() { string hello_ = "Hello Lua!"; struct C { static int call(lua_State* L) { C *p = static_cast<C*>(lua_touserdata(L,-1)); lua_pushstring(L, p->str.c_str() ); lua_getglobal(L, "print"); lua_call(L, 1, 0); //ok lua_pushstring(L, p->str.c_str() ); lua_getglobal(L, "notprint"); lua_call(L, 1, 0); //error -> longjmps return 0; //Number of values on stack to 'return' to lua } const string& str; } p = { hello_ }; //protected call of C::call() above //with &p as 1st/only element on Lua stack //any errors encountered will trigger a longjmp out of lua and //return a non-0 error code and a string on the stack //A return of 0 indicates success and the stack is unmodified //to invoke LUA functions safely use the lua_pcall function int res = lua_cpcall(L, &C::call, &p); if( res ) { string err = lua_tostring(L, -1); lua_pop(L, 1); //Error hanlder here } //load a .lua file if( (res=luaL_loadfile(L, "myLuaFile.lua")) ) { string err = lua_tostring(L, -1); lua_pop(L, 1); //res is one of //LUA_ERRSYNTAX - Lua syntax error //LUA_ERRMEM - Out of memory error //LUE_ERRFILE - File not found/accessible error } //execute it if( (res=lua_pcall(L,0,0,0)) ) { string err = lua_tostring(L, -1); lua_pop(L, 1); // res is one of // LUA_ERRRUN: a runtime error. // LUA_ERRMEM: memory allocation error. // LUA_ERRERR: error while running the error handler function (NULL in this case). } // try to call [a_int,b_str] = Foo(1,2,"3") lua_getglobal(L,"Foo"); if( lua_isfunction(L,lua_gettop(L)) ) { //Foo exists lua_pushnumber(L,1); lua_pushnumber(L,2); lua_pushstring(L,"3"); lua_pushvalue(L, -4); //copy of foo()
if( (res = lua_pcall(L, 3, 2, 0/*default error func*/)) ) { string err = lua_tostring(L, -1); lua_pop(L, 1); //error: see above } int a_int = (int)lua_tointeger(L,-2); string b_str = lua_tostring(L,-1); lua_pop(L,2+1); //2 returns, + extra copy of Foo()} }
```