Lua5.2嵌入到C++中。
2014-5-11 10:0:10
收藏:0
阅读:139
评论:1
我第一次尝试在C++中嵌入Lua。我已经搜索了2天,但大多数互联网tutos使用lua5.1,这与lua5.2不兼容。所以我阅读了一些lua文档、示例源代码,最终得到了这个:
main.cpp:
#include "luainc.h"
#include <iostream>
int main(){
int iErr = 0;
lua_State *lua = luaL_newstate (); // Open Lua
luaopen_io (lua); // Load io library
if ((iErr = luaL_loadfile (lua, "hw.lua")) == 0)
{
std::cout<<"step1"<<std::endl;
if ((iErr = lua_pcall (lua, 0, LUA_MULTRET, 0)) == 0)
{
std::cout<<"step2"<<std::endl;
lua_getglobal (lua, "helloWorld"); // Push the function name onto the stack
if (lua_type(lua, lua_gettop(lua)) == LUA_TNIL) {
// if the global variable does not exist then we will bail out with an error.
std::cout<<"global variable not found : helloworld"<<std::endl;
/* error so we will just clear the Lua virtual stack and then return
if we do not clear the Lua stack, we leave garbage that will cause problems with later
function calls from the application. we do this rather than use lua_error() because this function
is called from the application and not through Lua. */
lua_settop (lua, 0);
return -1;
}
// Function is located in the Global Table
/* lua_gettable (lua, LUA_GLOBALSINDEX); */ //lua5.1
lua_pcall (lua, 0, 0, 0);
}
}
lua_close (lua);
return 0;
}
hw.lua:
-- Lua Hello World (hw.lua)
function helloWorld ()
io.write ("hello World")
end
luainc.h:
#ifndef __LUA_INC_H__
#define __LUA_INC_H__
extern "C"
{
#include </home/renardc/Documents/Programmation/Lua_CPP/lua-5.2.2/src/lua.h>
#include </home/renardc/Documents/Programmation/Lua_CPP/lua-5.2.2/src/lauxlib.h>
#include </home/renardc/Documents/Programmation/Lua_CPP/lua-5.2.2/src/lualib.h>
}
#endif // __LUA_INC_H__
我没有错误,输出是:
step1
step2
这应该意味着我的“helloworld”函数已经被找到。但由于输出中看不到“Hello World”,我怀疑函数没有被调用。我做错了什么?
这是我如何编译我的程序:
g++ main.cpp -L/usr/local/include -I/usr/local/include -llua
点赞
评论区的留言会收到邮件通知哦~
推荐文章
- 如何将两个不同的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 代码?
- addEventListener 返回 nil Lua
- Lua中获取用户配置主目录的跨平台方法
首先,为什么不使用
#include "lua.hpp"呢?该文件是 Lua 自带的,并且基本上可以实现你的luainc.h的所有功能。你的代码有两个问题:
当
luaL_loadfile失败时,你没有发出任何错误消息。你使用
lua_pcall调用helloWorld,但没有测试其返回值。当你将
lua_pcall改为lua_call后,你会收到以下错误消息:这意味着在调用
luaopen_io后,你忘记了设置全局变量io。只需添加lua_setglobal(lua,"io")即可使其工作。与 Lua 5.1 不同,除非库本身这样做(这是不鼓励的),否则 Lua 5.2 在打开库时不会自动设置全局变量。为了避免出现意外,你最好使用
luaL_openlibs打开所有标准的 Lua 库。你也可以使用
luaL_dofile替代luaL_loadfile并省略第一个lua_pcall。但是仍需要检查其返回值。